{"version":3,"file":"bin.mjs","names":["make","layer","Schema","Schema","isProviderDriverKind","Schema","Schema","Schema","Schema","GROK_DRIVER_KIND","Schema","RuntimeMode","DEFAULT_RUNTIME_MODE","ProjectCreatedPayload","ProjectMetaUpdatedPayload","ProjectDeletedPayload","ThreadCreatedPayload","ThreadDeletedPayload","ThreadArchivedPayload","ThreadUnarchivedPayload","ThreadSettledPayload","ThreadUnsettledPayload","ThreadSnoozedPayload","ThreadUnsnoozedPayload","ThreadPinnedPayload","ThreadUnpinnedPayload","ThreadPinReorderedPayload","ThreadMetaUpdatedPayload","ThreadRuntimeModeSetPayload","ThreadInteractionModeSetPayload","ThreadRevertedPayload","ThreadSessionSetPayload","ThreadProposedPlanUpsertedPayload","ThreadTurnDiffCompletedPayload","ThreadActivityAppendedPayload","Schema","Schema","HttpServerRespondable","HttpServerResponse","Schema","Schema","Schema","Schema","TrimmedNonEmptyStringSchema","Schema","Schema","RuntimeMode","TrimmedNonEmptyStringSchema","Schema","Schema","Schema","Schema","Schema","ServerConfig","Schema","Schema","Schema","Schema","Schema","Schema","Schema","Schema","Schema","Schema","Schema","ServerConfig","Schema","Schema","layerTest","make","layer","makeTest","make","ServerConfig.ServerConfig","layer","Schema","Schema","toPersistenceSqlOrDecodeError","make","layer","Schema","make","ServerConfig.ServerConfig","AuthPairingLinks.AuthPairingLinkRepository","layer","AuthPairingLinks.layer","Schema","make","ServerConfig.ServerConfig","layer","Schema","toPersistenceSqlOrDecodeError","make","layer","Schema","SIGNING_SECRET_NAME","make","ServerConfig.ServerConfig","ServerSecretStore.ServerSecretStore","AuthSessions.AuthSessionRepository","layer","AuthSessions.layer","crypto","nc","isBytes","abytes","concatBytes","crypto","u64.split","u64.rotrSH","u64.shrSH","u64.rotrSL","u64.shrSL","u64.rotrBH","u64.rotrBL","u64.add4L","u64.add4H","u64.add5L","u64.add5H","u64.add","u64.add3L","u64.add3H","_0n","_1n","bytesToHex","_0n","_1n","_2n","_3n","_4n","gcd","_0n","_1n","bytesToHex","concatBytes","Schema","isRecord","Schema","DpopPublicJwkSchema","ServerSecretStore.isSecretAlreadyExistsError","HttpServerRequest","ServerSecretStore.ServerSecretStore","ServerSecretStore.isSecretStoreError","DEFAULT_RUNTIME_MODE","Migration0001","Migration0002","Migration0003","Migration0004","Migration0005","Migration0006","Migration0007","Migration0008","Migration0009","Migration0010","Migration0011","Migration0012","Migration0013","Migration0014","Migration0015","Migration0016","Migration0017","Migration0018","Migration0019","Migration0020","Migration0021","Migration0022","Migration0023","Migration0024","Migration0025","Migration0026","Migration0027","Migration0028","Migration0029","Migration0030","Migration0031","Migration0032","Migration0033","Migration0034","Migration0035","Migration0036","Migration0037","Migration0038","Schema","PairingGrantStore.isBootstrapCredentialInternalError","SessionStore.isSessionCredentialInvalidError","make","EnvironmentAuthPolicy.EnvironmentAuthPolicy","PairingGrantStore.PairingGrantStore","SessionStore.SessionStore","ServerSecretStore.ServerSecretStore","HttpServerRequest","layer","PairingGrantStore.layer","SessionStore.layer","EnvironmentAuthPolicy.layer","ServerSecretStore.layer","SqlitePersistenceLayer","P","Schema","decodeJsonString","ServerSettingsJson","Schema","isProviderDriverKind","Schema","expandHomePath","Schema","tailscaleServePortFlag","ServerConfig.RuntimeMode","NetService.NetService","ServerConfig.DEFAULT_PORT","expandHomePath","ServerConfig.deriveServerPaths","ServerConfig.ensureServerDirectories","ServerConfig.resolveStaticDir","EnvironmentAuth.EnvironmentAuth","EnvironmentAuth.runtimeLayer","ServerConfig.layer","ttlFlag","labelFlag","EnvironmentAuth.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT","Schema","EnvironmentAuth.EnvironmentAuth","Schema","Schema","ServerConfig.deriveServerPaths","ServerConfig.make","EnvironmentAuth.EnvironmentAuth","ServerConfig.layer","Schema","Schema","toPersistenceSqlOrDecodeError","Schema","ContractsProjectCreatedPayloadSchema","ContractsProjectMetaUpdatedPayloadSchema","ContractsProjectDeletedPayloadSchema","ContractsThreadCreatedPayloadSchema","ContractsThreadArchivedPayloadSchema","ContractsThreadSettledPayloadSchema","ContractsThreadMetaUpdatedPayloadSchema","ContractsThreadRuntimeModeSetPayloadSchema","ContractsThreadInteractionModeSetPayloadSchema","ContractsThreadDeletedPayloadSchema","ContractsThreadUnarchivedPayloadSchema","ContractsThreadUnsettledPayloadSchema","ContractsThreadSnoozedPayloadSchema","ContractsThreadUnsnoozedPayloadSchema","ContractsThreadPinnedPayloadSchema","ContractsThreadUnpinnedPayloadSchema","ContractsThreadPinReorderedPayloadSchema","ContractsThreadMessageSentPayloadSchema","ContractsThreadProposedPlanUpsertedPayloadSchema","ContractsThreadSessionSetPayloadSchema","ContractsThreadTurnDiffCompletedPayloadSchema","ContractsThreadRevertedPayloadSchema","ContractsThreadActivityAppendedPayloadSchema","settledTurnStateForSessionStatus","Schema","nowIso","Schema","Schema","Schema","Schema","Schema","Schema","Schema","Schema","RuntimeMode","Schema","Schema","RuntimeMode","Schema","Schema","ProjectionThreadActivityDbRowSchema","Schema","toPersistenceSqlOrDecodeError","ProjectionThreadMessageDbRowSchema","Schema","Schema","toPersistenceSqlOrDecodeError","Schema","Schema","make","layer","make","layer","deriveLocalBranchNameFromRemoteRef","Schema","DEFAULT_MAX_OUTPUT_BYTES","ChildProcess","make","ChildProcessSpawner","layer","parseRemoteFetchUrls","ProcessRunner.ProcessRunner","make","layer","ProcessRunner.layer","Schema","toPersistenceSqlOrDecodeError","RepositoryIdentityResolver.RepositoryIdentityResolver","ThreadBackgroundLiveness.layer","ThreadPlanProgress.layer","Schema","make","ServerConfig.ServerConfig","Array","layer","compactEnv","readCommandLookupEnv","ChildProcessSpawner","ChildProcess","make","layer","make","layer","Schema","textEncoder","layerTest","make","ServerConfig.ServerConfig","ServerSecretStore.ServerSecretStore","layer","Schema","isNotFoundError","ServerConfig.ServerConfig","make","HttpClient","ServerConfig.ServerConfig","packageJson.version","HttpClientRequest","HttpClientResponse","layer","layerTest","Schema","isRecord","version","packageJson.version","Schema","packageJson.version","make","layer","make","ServerConfig.ServerConfig","ServiceLauncherClient.ServiceLauncherClient","ProcessRunner.ProcessRunner","layer","ProcessRunner.layer","Schema","ProcessRunner.ProcessRunner","Schema","make","ServerConfig.ServerConfig","packageJson.version","layer","ProcessRunner.layer","Schema","ServerConfig.RuntimeMode","AnalyticsService.AnalyticsService","ProjectionSnapshotQuery.ProjectionSnapshotQuery","ServerConfig.ServerConfig","OrchestrationEngine.OrchestrationEngineService","EnvironmentAuth.EnvironmentAuth","ExternalLauncher.ExternalLauncher","make","Keybindings.Keybindings","OrchestrationReactor.OrchestrationReactor","ProviderSessionReaper.ProviderSessionReaper","ServerLifecycleEvents.ServerLifecycleEvents","ServerSettings.ServerSettingsService","ServerEnvironment.ServerEnvironment","ServiceLauncherClient.ServiceLauncherClient","layer","Schema","expandHomePath","make","layer","Schema","WorkspacePaths.layer","RepositoryIdentityResolver.layer","SqlitePersistenceLayerLive","WorkspacePaths.WorkspacePaths","ProjectionSnapshotQuery.ProjectionSnapshotQuery","EnvironmentAuth.EnvironmentAuth","ServerConfig.layer","OrchestrationEngine.OrchestrationEngineService","EnvironmentAuth.runtimeLayer","ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection","Schema","isProtocolMismatch","isDecodeFailed","make","layer","make","layer","DesktopTelemetryReceiver.DesktopTelemetryReceiver","make","HostPowerMonitor.HostPowerMonitor","layer","Schema","ExitRuntime","Schema","make","layer","Schema","optionOnNotFound","make","WorkspacePaths.WorkspacePaths","T3ProjectFileLoader.T3ProjectFileLoader","layer","Schema","WorkspacePaths.WorkspacePaths","ServerConfig.ServerConfig","ProjectFaviconResolver.ProjectFaviconResolver","ServerSecretStore.ServerSecretStore","make","layer","EnvironmentAuth.EnvironmentAuth","EnvironmentAuth.isServerAuthCredentialError","EnvironmentAuth.serverAuthCredentialReason","EnvironmentAuth.isServerAuthInternalError","SessionStore.SessionStore","EnvironmentAuth.isServerAuthInvalidRequestError","EnvironmentAuth.serverAuthInvalidRequestReason","LOOPBACK_HOSTNAMES","ServerConfig.ServerConfig","isLoopbackHostname","EnvironmentAuth.EnvironmentAuth","EnvironmentAuth.isServerAuthCredentialError","EnvironmentAuth.serverAuthCredentialReason","EnvironmentAuth.isServerAuthInternalError","ServerEnvironment.ServerEnvironment","BrowserTraceCollector.BrowserTraceCollector","ServerConfig.resolveStaticDir","Schema","DEFAULT_TIMEOUT_MS","DEFAULT_MAX_OUTPUT_BYTES","OUTPUT_TRUNCATED_MARKER","WORKSPACE_FILES_MAX_OUTPUT_BYTES","splitNullSeparatedPaths","Schema","DEFAULT_TIMEOUT_MS","make","ProcessRunner.ProcessRunner","layer","ProcessRunner.layer","VcsProcess.VcsProcess","make","VcsDriver.VcsDriver","layer","Schema","make","layer","make","VcsProjectConfig.VcsProjectConfig","GitVcsDriver.makeVcsDriver","layer","VcsProjectConfig.layer","make","VcsDriverRegistry.VcsDriverRegistry","layer","Schema","make","ProjectionSnapshotQuery.ProjectionSnapshotQuery","CheckpointStore.CheckpointStore","layer","asRecord","asTrimmedString","WorkspacePaths.WorkspacePaths","Schema","nonEmptyString","makeManualProviderMaintenanceCapabilities","Schema","nowIso","truncateText","make","layer","Schema","make","Net.NetService","ProcessRunner.ProcessRunner","layer","nowIso","Schema","ProcessRunner.ProcessRunner","make","ServerConfig.ServerConfig","PtyAdapter.PtyAdapter","PortScanner.PortDiscovery","makeWithOptions","PtyAdapter.PtySpawnError","layer","ProcessRunner.layer","Schema","make","layer","initialState","make","layer","Schema","make","layer","Schema","WorkspacePaths.WorkspaceRootNotExistsError","WorkspacePaths.WorkspaceRootCreateFailedError","WorkspacePaths.WorkspaceRootStatFailedError","WorkspacePaths.WorkspaceRootNotDirectoryError","WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed","WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut","WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed","expandHomePath","make","WorkspacePaths.WorkspacePaths","WorkspaceSearchIndex.WorkspaceSearchIndexMap","WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS","WorkspaceSearchIndex.workspaceSearchIndexKey","WorkspaceSearchIndex.WorkspaceSearchIndex","layer","Schema","make","WorkspacePaths.WorkspacePaths","WorkspaceEntries.WorkspaceEntries","layer","make","ProviderInstanceRegistry.ProviderInstanceRegistry","layer","Schema","make","ProjectionSnapshotQuery.ProjectionSnapshotQuery","TerminalManager.TerminalManager","layer","Schema","trimOptionalString","DEFAULT_TIMEOUT_MS","Schema","normalizeChangeRequestId","normalizeRepositoryCloneUrls","make","VcsProcess.VcsProcess","SourceControlProvider.sourceBranch","layer","discovery","toChangeRequest","make","AzureDevOpsCli.AzureDevOpsCli","SourceControlProvider.sourceControlRefFromInput","SourceControlProvider.transportSafeSourceControlErrorValue","layer","SourceControlProvider.SourceControlProvider","Schema","trimOptionalString","Schema","SourceControlProvider.parseSourceControlOwnerRef","normalizeRepositoryCloneUrls","shouldPreferSshRemote","make","GitVcsDriver.GitVcsDriver","VcsDriverRegistry.VcsDriverRegistry","SourceControlProvider.sourceBranch","layer","toChangeRequest","make","BitbucketApi.BitbucketApi","SourceControlProvider.sourceControlRefFromInput","SourceControlProvider.transportSafeSourceControlErrorValue","layer","SourceControlProvider.SourceControlProvider","Schema","trimOptionalString","DEFAULT_TIMEOUT_MS","Schema","normalizeRepositoryCloneUrls","make","VcsProcess.VcsProcess","layer","Schema","toChangeRequest","discovery","make","GitHubCli.GitHubCli","SourceControlProvider.transportSafeSourceControlErrorValue","GitHubCli.GitHubChangeRequestListDecodeError","layer","SourceControlProvider.SourceControlProvider","Schema","DEFAULT_TIMEOUT_MS","Schema","make","VcsProcess.VcsProcess","layer","make","GitLabCli.GitLabCli","SourceControlProvider.sourceControlRefFromInput","SourceControlProvider.transportSafeSourceControlErrorValue","layer","SourceControlProvider.SourceControlProvider","SourceControlProvider.transportSafeSourceControlErrorValue","VcsProcess.VcsProcess","VcsDriverRegistry.VcsDriverRegistry","make","GitHubSourceControlProvider.make","GitLabSourceControlProvider.make","BitbucketSourceControlProvider.make","BitbucketSourceControlProvider.makeDiscovery","AzureDevOpsSourceControlProvider.make","GitHubSourceControlProvider.discovery","GitLabSourceControlProvider.discovery","AzureDevOpsSourceControlProvider.discovery","layer","make","GitVcsDriver.GitVcsDriver","SourceControlProviderRegistry.SourceControlProviderRegistry","TextGeneration.TextGeneration","ProviderRegistry.ProviderRegistry","ProjectSetupScriptRunner.ProjectSetupScriptRunner","ServerSettings.ServerSettingsService","ServerSettings.resolveSourceControlWriterModelSelection","layer","make","VcsDriverRegistry.VcsDriverRegistry","GitVcsDriver.GitVcsDriver","GitManager.GitManager","layer","make","GitWorkflowService.GitWorkflowService","BackgroundPolicy.BackgroundPolicy","layer","make","VcsDriverRegistry.VcsDriverRegistry","layer","make","ServerConfig.ServerConfig","VcsDriverRegistry.VcsDriverRegistry","GitVcsDriver.GitVcsDriver","layer","Schema","make","layer","Schema","ResourceMonitorEventSchema","ResourceMonitorCommandSchema","make","ResourceMonitorBinary.ResourceMonitorBinary","layer","make","layer","Schema","make","NativeTelemetryClient.NativeTelemetryClient","DesktopTelemetryReceiver.DesktopTelemetryReceiver","ResourceAttribution.ResourceAttribution","layer","Schema","make","ResourceTelemetry.ResourceTelemetry","layer","make","ResourceTelemetry.ResourceTelemetry","layer","expandHomePath","expandHomePath","expandHomePath","Schema","#buckets","#seen","#toDay","#options","#duplicatesDropped","#outOfWindow","Schema","make","ServerSettings.ServerSettingsService","layer","Schema","make","layer","make","VcsProcess.VcsProcess","SourceControlProviderRegistry.SourceControlProviderRegistry","layer","Schema","make","GitVcsDriver.GitVcsDriver","SourceControlProviderRegistry.SourceControlProviderRegistry","layer","trimmedString","Schema","nowIso","ProjectionSnapshotQuery.ProjectionSnapshotQuery","OrchestrationEngine.OrchestrationEngineService","CheckpointDiffQuery.CheckpointDiffQuery","Keybindings.Keybindings","ExternalLauncher.ExternalLauncher","GitWorkflowService.GitWorkflowService","ReviewService.ReviewService","VcsProvisioningService.VcsProvisioningService","VcsStatusBroadcaster.VcsStatusBroadcaster","TerminalManager.TerminalManager","PreviewManager.PreviewManager","PortScanner.PortDiscovery","ProviderRegistry.ProviderRegistry","ProviderMaintenanceRunner.ProviderMaintenanceRunner","ServerSelfUpdate.ServerSelfUpdate","ServerConfig.ServerConfig","ServerLifecycleEvents.ServerLifecycleEvents","ServerSettings.ServerSettingsService","ServerRuntimeStartup.ServerRuntimeStartup","WorkspaceEntries.WorkspaceEntries","WorkspaceFileSystem.WorkspaceFileSystem","ProjectSetupScriptRunner.ProjectSetupScriptRunner","ServerEnvironment.ServerEnvironment","BackgroundPolicy.BackgroundPolicy","EnvironmentAuth.EnvironmentAuth","SourceControlDiscovery.SourceControlDiscovery","SourceControlRepositoryService.SourceControlRepositoryService","PairingGrantStore.PairingGrantStore","SessionStore.SessionStore","ProcessDiagnostics.ProcessDiagnostics","ProcessResourceMonitor.ProcessResourceMonitor","ResourceTelemetry.ResourceTelemetry","UsageService.UsageService","RelayClient.RelayClient","observeRpcEffect","instrumentRpcEffect","observeRpcStream","instrumentRpcStream","observeRpcStreamEffect","instrumentRpcStreamEffect","ServerSettings.redactServerSettingsForClient","TraceDiagnostics.readTraceDiagnostics","PreviewAutomationBroker.PreviewAutomationBroker","EnvironmentAuth.isServerAuthCredentialError","EnvironmentAuth.serverAuthCredentialReason","EnvironmentAuth.isServerAuthInternalError","ProviderMaintenanceRunner.layer","AzureDevOpsCli.layer","BitbucketApi.layer","GitHubCli.layer","GitLabCli.layer","GitVcsDriver.layer","VcsProjectConfig.layer","VcsProcess.layer","Schema","RuntimeMode","make","layer","Schema","Schema","isRecord","ProviderSessionRuntime.ProviderSessionRuntimeRepository","Schema","make","ResourceAttribution.ResourceAttribution","EventNdjsonLogger.makeEventNdjsonLogStore","layer","ServerEnvironment.ServerEnvironment","make","layer","Schema","AnalyticsService.AnalyticsService","ProviderEventLoggers.ProviderEventLoggers","ProviderAdapterRegistry.ProviderAdapterRegistry","ProviderSessionDirectory.ProviderSessionDirectory","McpSessionRegistry.issueActiveMcpCredential","McpProviderSession.setMcpProviderSession","McpSessionRegistry.revokeActiveMcpThread","McpProviderSession.clearMcpProviderSession","McpSessionRegistry.touchActiveMcpThread","McpSessionRegistry.revokeAllActiveMcpCredentials","ProviderService.ProviderService","Schema","encodeUnknownJsonStringExit","Schema","P","encodeJsonStringForDiagnostics","NetService.NetService","NetService.layer","isTextGenerationError","Schema","Schema","parseYamlDocument","expandHomePath","toTitleCaseWords","claudeQuery","nowIso","Schema","encodeJsonString","encodeUnknownJsonStringExit","Schema","PROVIDER","encodeJsonStringForDiagnostics","asRuntimeItemId","asRuntimeRequestId","toRequestError","unknownMessage","McpProviderSession.readMcpProviderSession","BackgroundPolicy.BackgroundPolicy","Schema","DRIVER_KIND","UPDATE","withInstanceIdentity","encodeJsonString","Schema","ServerConfig.ServerConfig","expandHomePath","Schema","schemaIssueDiagnostics","Schema","ClientNotification","ClientRequest","RequestId","CodexSchema.V1InitializeParams","CodexSchema.V2ThreadStartParams","CodexSchema.V2ThreadResumeParams","CodexSchema.V2ThreadForkParams","CodexSchema.V2ThreadArchiveParams","CodexSchema.V2ThreadDeleteParams","CodexSchema.V2ThreadUnsubscribeParams","CodexSchema.V2ThreadSetNameParams","CodexSchema.V2ThreadGoalSetParams","CodexSchema.V2ThreadGoalGetParams","CodexSchema.V2ThreadGoalClearParams","CodexSchema.V2ThreadMetadataUpdateParams","CodexSchema.V2ThreadUnarchiveParams","CodexSchema.V2ThreadCompactStartParams","CodexSchema.V2ThreadShellCommandParams","CodexSchema.V2ThreadApproveGuardianDeniedActionParams","CodexSchema.V2ThreadRollbackParams","CodexSchema.V2ThreadListParams","CodexSchema.V2ThreadLoadedListParams","CodexSchema.V2ThreadReadParams","CodexSchema.V2ThreadInjectItemsParams","CodexSchema.V2SkillsListParams","CodexSchema.V2SkillsExtraRootsSetParams","CodexSchema.V2HooksListParams","CodexSchema.V2MarketplaceAddParams","CodexSchema.V2MarketplaceRemoveParams","CodexSchema.V2MarketplaceUpgradeParams","CodexSchema.V2PluginListParams","CodexSchema.V2PluginInstalledParams","CodexSchema.V2PluginReadParams","CodexSchema.V2PluginSkillReadParams","CodexSchema.V2PluginShareSaveParams","CodexSchema.V2PluginShareUpdateTargetsParams","CodexSchema.V2PluginShareListParams","CodexSchema.V2PluginShareCheckoutParams","CodexSchema.V2PluginShareDeleteParams","CodexSchema.V2AppsReadParams","CodexSchema.V2AppsListParams","CodexSchema.V2AppsInstalledParams","CodexSchema.V2FsReadFileParams","CodexSchema.V2FsWriteFileParams","CodexSchema.V2FsCreateDirectoryParams","CodexSchema.V2FsGetMetadataParams","CodexSchema.V2FsReadDirectoryParams","CodexSchema.V2FsRemoveParams","CodexSchema.V2FsCopyParams","CodexSchema.V2FsWatchParams","CodexSchema.V2FsUnwatchParams","CodexSchema.V2SkillsConfigWriteParams","CodexSchema.V2PluginInstallParams","CodexSchema.V2PluginUninstallParams","CodexSchema.V2TurnStartParams","CodexSchema.V2TurnSteerParams","CodexSchema.V2TurnInterruptParams","CodexSchema.V2ReviewStartParams","CodexSchema.V2ModelListParams","CodexSchema.V2ModelProviderCapabilitiesReadParams","CodexSchema.V2ExperimentalFeatureListParams","CodexSchema.V2PermissionProfileListParams","CodexSchema.V2ExperimentalFeatureEnablementSetParams","CodexSchema.V2McpServerOauthLoginParams","CodexSchema.V2ListMcpServerStatusParams","CodexSchema.V2McpResourceReadParams","CodexSchema.V2McpServerToolCallParams","CodexSchema.V2WindowsSandboxSetupStartParams","CodexSchema.V2LoginAccountParams","CodexSchema.V2CancelLoginAccountParams","CodexSchema.V2ConsumeAccountRateLimitResetCreditParams","CodexSchema.V2SendAddCreditsNudgeEmailParams","CodexSchema.V2FeedbackUploadParams","CodexSchema.V2CommandExecParams","CodexSchema.V2CommandExecWriteParams","CodexSchema.V2CommandExecTerminateParams","CodexSchema.V2CommandExecResizeParams","CodexSchema.V2ConfigReadParams","CodexSchema.V2ExternalAgentConfigDetectParams","CodexSchema.V2ExternalAgentConfigImportParams","CodexSchema.V2ConfigValueWriteParams","CodexSchema.V2ConfigBatchWriteParams","CodexSchema.V2GetAccountParams","CodexSchema.GetConversationSummaryParams","CodexSchema.GitDiffToRemoteParams","CodexSchema.GetAuthStatusParams","CodexSchema.FuzzyFileSearchParams","CodexSchema.V1InitializeResponse","CodexSchema.V2ThreadStartResponse","CodexSchema.V2ThreadResumeResponse","CodexSchema.V2ThreadForkResponse","CodexSchema.V2ThreadArchiveResponse","CodexSchema.V2ThreadDeleteResponse","CodexSchema.V2ThreadUnsubscribeResponse","CodexSchema.V2ThreadSetNameResponse","CodexSchema.V2ThreadGoalSetResponse","CodexSchema.V2ThreadGoalGetResponse","CodexSchema.V2ThreadGoalClearResponse","CodexSchema.V2ThreadMetadataUpdateResponse","CodexSchema.V2ThreadUnarchiveResponse","CodexSchema.V2ThreadCompactStartResponse","CodexSchema.V2ThreadShellCommandResponse","CodexSchema.V2ThreadApproveGuardianDeniedActionResponse","CodexSchema.V2ThreadRollbackResponse","CodexSchema.V2ThreadListResponse","CodexSchema.V2ThreadLoadedListResponse","CodexSchema.V2ThreadReadResponse","CodexSchema.V2ThreadInjectItemsResponse","CodexSchema.V2SkillsListResponse","CodexSchema.V2SkillsExtraRootsSetResponse","CodexSchema.V2HooksListResponse","CodexSchema.V2MarketplaceAddResponse","CodexSchema.V2MarketplaceRemoveResponse","CodexSchema.V2MarketplaceUpgradeResponse","CodexSchema.V2PluginListResponse","CodexSchema.V2PluginInstalledResponse","CodexSchema.V2PluginReadResponse","CodexSchema.V2PluginSkillReadResponse","CodexSchema.V2PluginShareSaveResponse","CodexSchema.V2PluginShareUpdateTargetsResponse","CodexSchema.V2PluginShareListResponse","CodexSchema.V2PluginShareCheckoutResponse","CodexSchema.V2PluginShareDeleteResponse","CodexSchema.V2AppsReadResponse","CodexSchema.V2AppsListResponse","CodexSchema.V2AppsInstalledResponse","CodexSchema.V2FsReadFileResponse","CodexSchema.V2FsWriteFileResponse","CodexSchema.V2FsCreateDirectoryResponse","CodexSchema.V2FsGetMetadataResponse","CodexSchema.V2FsReadDirectoryResponse","CodexSchema.V2FsRemoveResponse","CodexSchema.V2FsCopyResponse","CodexSchema.V2FsWatchResponse","CodexSchema.V2FsUnwatchResponse","CodexSchema.V2SkillsConfigWriteResponse","CodexSchema.V2PluginInstallResponse","CodexSchema.V2PluginUninstallResponse","CodexSchema.V2TurnStartResponse","CodexSchema.V2TurnSteerResponse","CodexSchema.V2TurnInterruptResponse","CodexSchema.V2ReviewStartResponse","CodexSchema.V2ModelListResponse","CodexSchema.V2ModelProviderCapabilitiesReadResponse","CodexSchema.V2ExperimentalFeatureListResponse","CodexSchema.V2PermissionProfileListResponse","CodexSchema.V2ExperimentalFeatureEnablementSetResponse","CodexSchema.V2McpServerOauthLoginResponse","CodexSchema.V2McpServerRefreshResponse","CodexSchema.V2ListMcpServerStatusResponse","CodexSchema.V2McpResourceReadResponse","CodexSchema.V2McpServerToolCallResponse","CodexSchema.V2WindowsSandboxSetupStartResponse","CodexSchema.V2WindowsSandboxReadinessResponse","CodexSchema.V2LoginAccountResponse","CodexSchema.V2CancelLoginAccountResponse","CodexSchema.V2LogoutAccountResponse","CodexSchema.V2GetAccountRateLimitsResponse","CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse","CodexSchema.V2GetAccountTokenUsageResponse","CodexSchema.V2GetWorkspaceMessagesResponse","CodexSchema.V2SendAddCreditsNudgeEmailResponse","CodexSchema.V2FeedbackUploadResponse","CodexSchema.V2CommandExecResponse","CodexSchema.V2CommandExecWriteResponse","CodexSchema.V2CommandExecTerminateResponse","CodexSchema.V2CommandExecResizeResponse","CodexSchema.V2ConfigReadResponse","CodexSchema.V2ExternalAgentConfigDetectResponse","CodexSchema.V2ExternalAgentConfigImportResponse","CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse","CodexSchema.V2ConfigWriteResponse","CodexSchema.V2ConfigRequirementsReadResponse","CodexSchema.V2GetAccountResponse","CodexSchema.GetConversationSummaryResponse","CodexSchema.GitDiffToRemoteResponse","CodexSchema.GetAuthStatusResponse","CodexSchema.FuzzyFileSearchResponse","CodexSchema.CommandExecutionRequestApprovalParams","CodexSchema.FileChangeRequestApprovalParams","CodexSchema.ToolRequestUserInputParams","CodexSchema.McpServerElicitationRequestParams","CodexSchema.PermissionsRequestApprovalParams","CodexSchema.DynamicToolCallParams","CodexSchema.ChatgptAuthTokensRefreshParams","CodexSchema.AttestationGenerateParams","CodexSchema.ApplyPatchApprovalParams","CodexSchema.ExecCommandApprovalParams","CodexSchema.CommandExecutionRequestApprovalResponse","CodexSchema.FileChangeRequestApprovalResponse","CodexSchema.ToolRequestUserInputResponse","CodexSchema.McpServerElicitationRequestResponse","CodexSchema.PermissionsRequestApprovalResponse","CodexSchema.DynamicToolCallResponse","CodexSchema.ChatgptAuthTokensRefreshResponse","CodexSchema.AttestationGenerateResponse","CodexSchema.ApplyPatchApprovalResponse","CodexSchema.ExecCommandApprovalResponse","CodexSchema.V2ErrorNotification","CodexSchema.V2ThreadStartedNotification","CodexSchema.V2ThreadStatusChangedNotification","CodexSchema.V2ThreadArchivedNotification","CodexSchema.V2ThreadDeletedNotification","CodexSchema.V2ThreadUnarchivedNotification","CodexSchema.V2ThreadClosedNotification","CodexSchema.V2SkillsChangedNotification","CodexSchema.V2ThreadNameUpdatedNotification","CodexSchema.V2ThreadGoalUpdatedNotification","CodexSchema.V2ThreadGoalClearedNotification","CodexSchema.V2EnvironmentConnectionNotification","CodexSchema.V2ThreadSettingsUpdatedNotification","CodexSchema.V2ThreadTokenUsageUpdatedNotification","CodexSchema.V2TurnStartedNotification","CodexSchema.V2HookStartedNotification","CodexSchema.V2TurnCompletedNotification","CodexSchema.V2HookCompletedNotification","CodexSchema.V2TurnDiffUpdatedNotification","CodexSchema.V2TurnPlanUpdatedNotification","CodexSchema.V2ItemStartedNotification","CodexSchema.V2ItemGuardianApprovalReviewStartedNotification","CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification","CodexSchema.V2ItemCompletedNotification","CodexSchema.V2RawResponseItemCompletedNotification","CodexSchema.V2RawResponseCompletedNotification","CodexSchema.V2AgentMessageDeltaNotification","CodexSchema.V2PlanDeltaNotification","CodexSchema.V2CommandExecOutputDeltaNotification","CodexSchema.V2ProcessOutputDeltaNotification","CodexSchema.V2ProcessExitedNotification","CodexSchema.V2CommandExecutionOutputDeltaNotification","CodexSchema.V2TerminalInteractionNotification","CodexSchema.V2FileChangeOutputDeltaNotification","CodexSchema.V2FileChangePatchUpdatedNotification","CodexSchema.V2ServerRequestResolvedNotification","CodexSchema.V2McpToolCallProgressNotification","CodexSchema.V2McpServerOauthLoginCompletedNotification","CodexSchema.V2McpServerStatusUpdatedNotification","CodexSchema.V2AccountUpdatedNotification","CodexSchema.V2AccountRateLimitsUpdatedNotification","CodexSchema.V2AppListUpdatedNotification","CodexSchema.V2RemoteControlStatusChangedNotification","CodexSchema.V2ExternalAgentConfigImportProgressNotification","CodexSchema.V2ExternalAgentConfigImportCompletedNotification","CodexSchema.V2FsChangedNotification","CodexSchema.V2ReasoningSummaryTextDeltaNotification","CodexSchema.V2ReasoningSummaryPartAddedNotification","CodexSchema.V2ReasoningTextDeltaNotification","CodexSchema.V2ContextCompactedNotification","CodexSchema.V2ModelReroutedNotification","CodexSchema.V2ModelVerificationNotification","CodexSchema.V2TurnModerationMetadataNotification","CodexSchema.V2ModelSafetyBufferingUpdatedNotification","CodexSchema.V2WarningNotification","CodexSchema.V2GuardianWarningNotification","CodexSchema.V2DeprecationNoticeNotification","CodexSchema.V2ConfigWarningNotification","CodexSchema.FuzzyFileSearchSessionUpdatedNotification","CodexSchema.FuzzyFileSearchSessionCompletedNotification","CodexSchema.V2ThreadRealtimeStartedNotification","CodexSchema.V2ThreadRealtimeItemAddedNotification","CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification","CodexSchema.V2ThreadRealtimeTranscriptDoneNotification","CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification","CodexSchema.V2ThreadRealtimeSdpNotification","CodexSchema.V2ThreadRealtimeErrorNotification","CodexSchema.V2ThreadRealtimeClosedNotification","CodexSchema.V2WindowsWorldWritableWarningNotification","CodexSchema.V2WindowsSandboxSetupCompletedNotification","CodexSchema.V2AccountLoginCompletedNotification","CodexSchema.V1InitializeParams","CodexSchema.V1InitializeResponse","CodexSchema.V2AccountLoginCompletedNotification","CodexSchema.V2AccountRateLimitsUpdatedNotification","CodexSchema.V2AccountUpdatedNotification","CodexSchema.V2AgentMessageDeltaNotification","CodexSchema.V2AppListUpdatedNotification","CodexSchema.V2AppsInstalledParams","CodexSchema.V2AppsInstalledResponse","CodexSchema.V2AppsListParams","CodexSchema.V2AppsListResponse","CodexSchema.V2AppsReadParams","CodexSchema.V2AppsReadResponse","CodexSchema.V2CancelLoginAccountParams","CodexSchema.V2CancelLoginAccountResponse","CodexSchema.V2CommandExecOutputDeltaNotification","CodexSchema.V2CommandExecParams","CodexSchema.V2CommandExecResizeParams","CodexSchema.V2CommandExecResizeResponse","CodexSchema.V2CommandExecResponse","CodexSchema.V2CommandExecTerminateParams","CodexSchema.V2CommandExecTerminateResponse","CodexSchema.V2CommandExecutionOutputDeltaNotification","CodexSchema.V2CommandExecWriteParams","CodexSchema.V2CommandExecWriteResponse","CodexSchema.V2ConfigBatchWriteParams","CodexSchema.V2ConfigReadParams","CodexSchema.V2ConfigReadResponse","CodexSchema.V2ConfigRequirementsReadResponse","CodexSchema.V2ConfigValueWriteParams","CodexSchema.V2ConfigWarningNotification","CodexSchema.V2ConfigWriteResponse","CodexSchema.V2ConsumeAccountRateLimitResetCreditParams","CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse","CodexSchema.V2ContextCompactedNotification","CodexSchema.V2DeprecationNoticeNotification","CodexSchema.V2EnvironmentConnectionNotification","CodexSchema.V2ErrorNotification","CodexSchema.V2ExperimentalFeatureEnablementSetParams","CodexSchema.V2ExperimentalFeatureEnablementSetResponse","CodexSchema.V2ExperimentalFeatureListParams","CodexSchema.V2ExperimentalFeatureListResponse","CodexSchema.V2ExternalAgentConfigDetectParams","CodexSchema.V2ExternalAgentConfigDetectResponse","CodexSchema.V2ExternalAgentConfigImportCompletedNotification","CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse","CodexSchema.V2ExternalAgentConfigImportParams","CodexSchema.V2ExternalAgentConfigImportProgressNotification","CodexSchema.V2ExternalAgentConfigImportResponse","CodexSchema.V2FeedbackUploadParams","CodexSchema.V2FeedbackUploadResponse","CodexSchema.V2FileChangeOutputDeltaNotification","CodexSchema.V2FileChangePatchUpdatedNotification","CodexSchema.V2FsChangedNotification","CodexSchema.V2FsCopyParams","CodexSchema.V2FsCopyResponse","CodexSchema.V2FsCreateDirectoryParams","CodexSchema.V2FsCreateDirectoryResponse","CodexSchema.V2FsGetMetadataParams","CodexSchema.V2FsGetMetadataResponse","CodexSchema.V2FsReadDirectoryParams","CodexSchema.V2FsReadDirectoryResponse","CodexSchema.V2FsReadFileParams","CodexSchema.V2FsReadFileResponse","CodexSchema.V2FsRemoveParams","CodexSchema.V2FsRemoveResponse","CodexSchema.V2FsUnwatchParams","CodexSchema.V2FsUnwatchResponse","CodexSchema.V2FsWatchParams","CodexSchema.V2FsWatchResponse","CodexSchema.V2FsWriteFileParams","CodexSchema.V2FsWriteFileResponse","CodexSchema.V2GetAccountParams","CodexSchema.V2GetAccountRateLimitsResponse","CodexSchema.V2GetAccountResponse","CodexSchema.V2GetAccountTokenUsageResponse","CodexSchema.V2GetWorkspaceMessagesResponse","CodexSchema.V2GuardianWarningNotification","CodexSchema.V2HookCompletedNotification","CodexSchema.V2HooksListParams","CodexSchema.V2HooksListResponse","CodexSchema.V2HookStartedNotification","CodexSchema.V2ItemCompletedNotification","CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification","CodexSchema.V2ItemGuardianApprovalReviewStartedNotification","CodexSchema.V2ItemStartedNotification","CodexSchema.V2ListMcpServerStatusParams","CodexSchema.V2ListMcpServerStatusResponse","CodexSchema.V2LoginAccountParams","CodexSchema.V2LoginAccountResponse","CodexSchema.V2LogoutAccountResponse","CodexSchema.V2MarketplaceAddParams","CodexSchema.V2MarketplaceAddResponse","CodexSchema.V2MarketplaceRemoveParams","CodexSchema.V2MarketplaceRemoveResponse","CodexSchema.V2MarketplaceUpgradeParams","CodexSchema.V2MarketplaceUpgradeResponse","CodexSchema.V2McpResourceReadParams","CodexSchema.V2McpResourceReadResponse","CodexSchema.V2McpServerOauthLoginCompletedNotification","CodexSchema.V2McpServerOauthLoginParams","CodexSchema.V2McpServerOauthLoginResponse","CodexSchema.V2McpServerRefreshResponse","CodexSchema.V2McpServerStatusUpdatedNotification","CodexSchema.V2McpServerToolCallParams","CodexSchema.V2McpServerToolCallResponse","CodexSchema.V2McpToolCallProgressNotification","CodexSchema.V2ModelListParams","CodexSchema.V2ModelListResponse","CodexSchema.V2ModelProviderCapabilitiesReadParams","CodexSchema.V2ModelProviderCapabilitiesReadResponse","CodexSchema.V2ModelReroutedNotification","CodexSchema.V2ModelSafetyBufferingUpdatedNotification","CodexSchema.V2ModelVerificationNotification","CodexSchema.V2PermissionProfileListParams","CodexSchema.V2PermissionProfileListResponse","CodexSchema.V2PlanDeltaNotification","CodexSchema.V2PluginInstalledParams","CodexSchema.V2PluginInstalledResponse","CodexSchema.V2PluginInstallParams","CodexSchema.V2PluginInstallResponse","CodexSchema.V2PluginListParams","CodexSchema.V2PluginListResponse","CodexSchema.V2PluginReadParams","CodexSchema.V2PluginReadResponse","CodexSchema.V2PluginShareCheckoutParams","CodexSchema.V2PluginShareCheckoutResponse","CodexSchema.V2PluginShareDeleteParams","CodexSchema.V2PluginShareDeleteResponse","CodexSchema.V2PluginShareListParams","CodexSchema.V2PluginShareListResponse","CodexSchema.V2PluginShareSaveParams","CodexSchema.V2PluginShareSaveResponse","CodexSchema.V2PluginShareUpdateTargetsParams","CodexSchema.V2PluginShareUpdateTargetsResponse","CodexSchema.V2PluginSkillReadParams","CodexSchema.V2PluginSkillReadResponse","CodexSchema.V2PluginUninstallParams","CodexSchema.V2PluginUninstallResponse","CodexSchema.V2ProcessExitedNotification","CodexSchema.V2ProcessOutputDeltaNotification","CodexSchema.V2RawResponseCompletedNotification","CodexSchema.V2RawResponseItemCompletedNotification","CodexSchema.V2ReasoningSummaryPartAddedNotification","CodexSchema.V2ReasoningSummaryTextDeltaNotification","CodexSchema.V2ReasoningTextDeltaNotification","CodexSchema.V2RemoteControlStatusChangedNotification","CodexSchema.V2ReviewStartParams","CodexSchema.V2ReviewStartResponse","CodexSchema.V2SendAddCreditsNudgeEmailParams","CodexSchema.V2SendAddCreditsNudgeEmailResponse","CodexSchema.V2ServerRequestResolvedNotification","CodexSchema.V2SkillsChangedNotification","CodexSchema.V2SkillsConfigWriteParams","CodexSchema.V2SkillsConfigWriteResponse","CodexSchema.V2SkillsExtraRootsSetParams","CodexSchema.V2SkillsExtraRootsSetResponse","CodexSchema.V2SkillsListParams","CodexSchema.V2SkillsListResponse","CodexSchema.V2TerminalInteractionNotification","CodexSchema.V2ThreadApproveGuardianDeniedActionParams","CodexSchema.V2ThreadApproveGuardianDeniedActionResponse","CodexSchema.V2ThreadArchivedNotification","CodexSchema.V2ThreadArchiveParams","CodexSchema.V2ThreadArchiveResponse","CodexSchema.V2ThreadClosedNotification","CodexSchema.V2ThreadCompactStartParams","CodexSchema.V2ThreadCompactStartResponse","CodexSchema.V2ThreadDeletedNotification","CodexSchema.V2ThreadDeleteParams","CodexSchema.V2ThreadDeleteResponse","CodexSchema.V2ThreadForkParams","CodexSchema.V2ThreadForkResponse","CodexSchema.V2ThreadGoalClearedNotification","CodexSchema.V2ThreadGoalClearParams","CodexSchema.V2ThreadGoalClearResponse","CodexSchema.V2ThreadGoalGetParams","CodexSchema.V2ThreadGoalGetResponse","CodexSchema.V2ThreadGoalSetParams","CodexSchema.V2ThreadGoalSetResponse","CodexSchema.V2ThreadGoalUpdatedNotification","CodexSchema.V2ThreadInjectItemsParams","CodexSchema.V2ThreadInjectItemsResponse","CodexSchema.V2ThreadListParams","CodexSchema.V2ThreadListResponse","CodexSchema.V2ThreadLoadedListParams","CodexSchema.V2ThreadLoadedListResponse","CodexSchema.V2ThreadMetadataUpdateParams","CodexSchema.V2ThreadMetadataUpdateResponse","CodexSchema.V2ThreadNameUpdatedNotification","CodexSchema.V2ThreadReadParams","CodexSchema.V2ThreadReadResponse","CodexSchema.V2ThreadRealtimeClosedNotification","CodexSchema.V2ThreadRealtimeErrorNotification","CodexSchema.V2ThreadRealtimeItemAddedNotification","CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification","CodexSchema.V2ThreadRealtimeSdpNotification","CodexSchema.V2ThreadRealtimeStartedNotification","CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification","CodexSchema.V2ThreadRealtimeTranscriptDoneNotification","CodexSchema.V2ThreadResumeParams","CodexSchema.V2ThreadResumeResponse","CodexSchema.V2ThreadRollbackParams","CodexSchema.V2ThreadRollbackResponse","CodexSchema.V2ThreadSetNameParams","CodexSchema.V2ThreadSetNameResponse","CodexSchema.V2ThreadSettingsUpdatedNotification","CodexSchema.V2ThreadShellCommandParams","CodexSchema.V2ThreadShellCommandResponse","CodexSchema.V2ThreadStartedNotification","CodexSchema.V2ThreadStartParams","CodexSchema.V2ThreadStartResponse","CodexSchema.V2ThreadStatusChangedNotification","CodexSchema.V2ThreadTokenUsageUpdatedNotification","CodexSchema.V2ThreadUnarchivedNotification","CodexSchema.V2ThreadUnarchiveParams","CodexSchema.V2ThreadUnarchiveResponse","CodexSchema.V2ThreadUnsubscribeParams","CodexSchema.V2ThreadUnsubscribeResponse","CodexSchema.V2TurnCompletedNotification","CodexSchema.V2TurnDiffUpdatedNotification","CodexSchema.V2TurnInterruptParams","CodexSchema.V2TurnInterruptResponse","CodexSchema.V2TurnModerationMetadataNotification","CodexSchema.V2TurnPlanUpdatedNotification","CodexSchema.V2TurnStartedNotification","CodexSchema.V2TurnStartParams","CodexSchema.V2TurnStartResponse","CodexSchema.V2TurnSteerParams","CodexSchema.V2TurnSteerResponse","CodexSchema.V2WarningNotification","CodexSchema.V2WindowsSandboxReadinessResponse","CodexSchema.V2WindowsSandboxSetupCompletedNotification","CodexSchema.V2WindowsSandboxSetupStartParams","CodexSchema.V2WindowsSandboxSetupStartResponse","CodexSchema.V2WindowsWorldWritableWarningNotification","JsonRpcId","Schema","runHandler","Schema","JsonRpcId","CodexError.CodexAppServerError","isObject","CodexError.CodexAppServerTransportError","CodexError.CodexAppServerInputStreamEndedError","encoder","makeChildStdio","makeInMemoryStdio","makeTerminationError","CodexError.CodexAppServerTransportError","CodexError.CodexAppServerProcessExitedError","make","CodexRpc.SERVER_REQUEST_PARAMS","CodexRpc.SERVER_REQUEST_RESPONSES","CodexRpc.CLIENT_REQUEST_PARAMS","CodexRpc.CLIENT_REQUEST_RESPONSES","CodexRpc.CLIENT_NOTIFICATION_PARAMS","CodexRpc.SERVER_NOTIFICATION_PARAMS","runHandler","CodexProtocol.makeCodexAppServerPatchedProtocol","layerChildProcess","makeChildStdio","makeTerminationError","Schema","CodexErrors.CodexAppServerSpawnError","packageJson.version","expandHomePath","ChildProcessSpawner","ChildProcess","CodexClient.layerChildProcess","CodexClient.CodexAppServerClient","Schema","EffectCodexSchema.V2TurnStartResponse","PROVIDER","isCodexResumeCursorSchema","EffectCodexSchema.V2TurnStartParams__CollaborationMode","expandHomePath","CodexErrors.CodexAppServerSpawnError","CodexClient.layerChildProcess","CodexClient.CodexAppServerClient","CodexErrors.CodexAppServerIdentifierGenerationError","CodexRpc.SERVER_NOTIFICATION_METHODS","Schema","CodexErrors.CodexAppServerProcessExitedError","CodexErrors.CodexAppServerTransportError","PROVIDER","trimText","EffectCodexSchema.V2ItemStartedNotification","EffectCodexSchema.V2ItemCompletedNotification","EffectCodexSchema.ServerRequest__ToolRequestUserInputParams","EffectCodexSchema.ToolRequestUserInputParams","EffectCodexSchema.ServerRequest__CommandExecutionRequestApprovalParams","EffectCodexSchema.ServerRequest__FileChangeRequestApprovalParams","EffectCodexSchema.ServerRequest__ApplyPatchApprovalParams","EffectCodexSchema.ServerRequest__ExecCommandApprovalParams","EffectCodexSchema.ServerRequest__DynamicToolCallParams","EffectCodexSchema.V2ThreadStartedNotification","EffectCodexSchema.V2ThreadStatusChangedNotification","EffectCodexSchema.V2ThreadNameUpdatedNotification","EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification","EffectCodexSchema.V2TurnCompletedNotification","EffectCodexSchema.V2TurnPlanUpdatedNotification","EffectCodexSchema.V2TurnDiffUpdatedNotification","EffectCodexSchema.V2PlanDeltaNotification","EffectCodexSchema.V2AgentMessageDeltaNotification","EffectCodexSchema.V2CommandExecutionOutputDeltaNotification","EffectCodexSchema.V2FileChangeOutputDeltaNotification","EffectCodexSchema.V2ReasoningSummaryTextDeltaNotification","EffectCodexSchema.V2ReasoningTextDeltaNotification","EffectCodexSchema.V2McpToolCallProgressNotification","EffectCodexSchema.V2ServerRequestResolvedNotification","EffectCodexSchema.ToolRequestUserInputResponse","EffectCodexSchema.V2ModelReroutedNotification","EffectCodexSchema.V2DeprecationNoticeNotification","EffectCodexSchema.V2ConfigWarningNotification","EffectCodexSchema.V2AccountUpdatedNotification","EffectCodexSchema.V2AccountRateLimitsUpdatedNotification","EffectCodexSchema.V2McpServerOauthLoginCompletedNotification","EffectCodexSchema.V2ThreadRealtimeStartedNotification","EffectCodexSchema.V2ThreadRealtimeItemAddedNotification","EffectCodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification","EffectCodexSchema.V2ThreadRealtimeErrorNotification","EffectCodexSchema.V2ThreadRealtimeClosedNotification","EffectCodexSchema.V2ErrorNotification","EffectCodexSchema.V2WindowsWorldWritableWarningNotification","EffectCodexSchema.V2WindowsSandboxSetupCompletedNotification","McpProviderSession.readMcpProviderSession","Schema","DRIVER_KIND","UPDATE","withInstanceIdentity","Schema","Error","McpServer","Terminal","Schema","AcpSchema.ErrorCode","Schema","AcpError.AcpError","AcpSchema.SessionNotification","AcpSchema.ElicitationCompleteNotification","RpcSerialization","AcpError.AcpProtocolParseError","AcpError.AcpTransportError","AcpError.AcpInputStreamEndedError","RpcServer","AcpSchema.InitializeRequest","AcpSchema.InitializeResponse","AcpSchema.Error","AcpSchema.AuthenticateRequest","AcpSchema.AuthenticateResponse","AcpSchema.LogoutRequest","AcpSchema.LogoutResponse","AcpSchema.NewSessionRequest","AcpSchema.NewSessionResponse","AcpSchema.LoadSessionRequest","AcpSchema.LoadSessionResponse","AcpSchema.ListSessionsRequest","AcpSchema.ListSessionsResponse","AcpSchema.ForkSessionRequest","AcpSchema.ForkSessionResponse","AcpSchema.ResumeSessionRequest","AcpSchema.ResumeSessionResponse","AcpSchema.CloseSessionRequest","AcpSchema.CloseSessionResponse","AcpSchema.PromptRequest","AcpSchema.PromptResponse","AcpSchema.SetSessionModelRequest","AcpSchema.SetSessionModelResponse","AcpSchema.SetSessionConfigOptionRequest","AcpSchema.SetSessionConfigOptionResponse","AcpSchema.ReadTextFileRequest","AcpSchema.ReadTextFileResponse","AcpSchema.WriteTextFileRequest","AcpSchema.WriteTextFileResponse","AcpSchema.RequestPermissionRequest","AcpSchema.RequestPermissionResponse","AcpSchema.ElicitationRequest","AcpSchema.ElicitationResponse","AcpSchema.CreateTerminalRequest","AcpSchema.CreateTerminalResponse","AcpSchema.TerminalOutputRequest","AcpSchema.TerminalOutputResponse","AcpSchema.ReleaseTerminalRequest","AcpSchema.ReleaseTerminalResponse","AcpSchema.WaitForTerminalExitRequest","AcpSchema.WaitForTerminalExitResponse","AcpSchema.KillTerminalRequest","AcpSchema.KillTerminalResponse","Schema","AcpSchema.Error","AcpError.AcpTransportError","encoder","encoder","AcpError.AcpTransportError","AcpError.AcpProcessExitedError","make","AcpProtocol.makeAcpPatchedProtocol","RpcServer","AcpRpcs.ClientRpcs","AcpRpcs.AgentRpcs","normalizeCommandValue","extractCommandFromTitle","isRecord","canonicalItemTypeFromAcpToolKind","make","ChildProcessSpawner","EffectAcpErrors.AcpTransportError","ChildProcess","EffectAcpErrors.AcpSpawnError","EffectAcpClient.layerChildProcess","EffectAcpClient.AcpClient","EffectAcpErrors.AcpRequestError","layer","Schema","AcpSchema.SessionConfigOption","Schema","EMPTY_CAPABILITIES","ChildProcessSpawner","AcpSessionRuntime.layer","AcpSessionRuntime.AcpSessionRuntime","ChildProcess","AcpSessionRuntime.layer","ChildProcessSpawner","AcpSessionRuntime.AcpSessionRuntime","isTextGenerationError","Schema","Schema","EffectAcpErrors.AcpProcessExitedError","EffectAcpErrors.AcpRequestError","encodeUnknownJsonStringExit","Schema","PROVIDER","encodeJsonStringForDiagnostics","settlePendingApprovalsAsCancelled","isRecord","selectAutoApprovedPermissionOption","ChildProcessSpawner","EffectAcpErrors.AcpTransportError","McpProviderSession.readMcpProviderSession","Schema","DRIVER_KIND","UPDATE","withInstanceIdentity","Schema","AcpSessionRuntime.layer","ChildProcessSpawner","AcpSessionRuntime.AcpSessionRuntime","Schema","Schema","PROVIDER","ChildProcessSpawner","EffectAcpErrors.AcpTransportError","McpProviderSession.readMcpProviderSession","Schema","DRIVER_KIND","UPDATE","withInstanceIdentity","Schema","ServerConfig.ServerConfig","OpenCodeRuntime.OpenCodeRuntime","OpenCodeRuntime.openCodeRuntimeErrorDetail","OpenCodeRuntime.parseOpenCodeModelSlug","OpenCodeRuntime.toOpenCodeFileParts","nowIso","McpProviderSession.readMcpProviderSession","Schema","nowIso","Schema","McpInvocationContext.McpInvocationContext","PreviewAutomationBroker.PreviewAutomationBroker","Schema","McpInvocationContext.requireMcpCapability","PreviewAutomationBroker.PreviewAutomationBroker","McpInvocationContext.McpInvocationContext","PreviewAutomationBroker.PreviewAutomationBroker","snapshot","packageJson.version","layer","encode","jwk.isJWK","jwk.isSecretJWK","invalidKeyInput","jwk.isPrivateJWK","jwk.isPublicJWK","b64u","encode","#payload","#payload","#protectedHeader","#unprotectedHeader","b64u","encode","#flattened","#jwt","#protectedHeader","Schema","Schema","Schema","bytesToString","stringToBytes","ServerSecretStore.SecretStoreDecodeError","ServerSecretStore.SecretStoreEncodeError","ServerSecretStore.SecretStoreConcurrentReadError","ServerSecretStore.isSecretStoreError","ServerSecretStore.isSecretAlreadyExistsError","HttpClient","HttpClientRequest","make","ServerSecretStore.ServerSecretStore","ServerEnvironment.ServerEnvironment","ProjectionSnapshotQuery.ProjectionSnapshotQuery","OrchestrationEngine.OrchestrationEngineService","FetchHttpClient","layer","AgentAwarenessRelay.AgentAwarenessRelay","Schema","toTurnId","sameId","make","Schema","make","make","CheckpointStore.CheckpointStore","WorkspaceEntries.WorkspaceEntries","make","TerminalManager.TerminalManager","Schema","Schema","Schema","Schema","ServerProviderSchema","mergeProviderModels","OtlpSerialization","ServerConfig.ServerConfig","ResourceAttribution.ResourceAttribution","OtlpTracer","BrowserTraceCollector.layer","bytesToString","ServerSecretStore.ServerSecretStore","make","ChildProcessSpawner","RelayClient.RelayClient","ChildProcess","layer","ServerSecretStore.ServerSecretStore","Schema","stringToBytes","bytesToString","HttpClient","HttpClientRequest","HttpClientResponse","make","ServerSecretStore.ServerSecretStore","ExternalLauncher.ExternalLauncher","HttpRouter","HttpServerRequest","HttpServerResponse","layer","ServerSecretStore.isSecretStoreError","ServerSecretStore.isSecretAlreadyExistsError","EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError","EnvironmentAuth.ServerAuthLinkedCloudAccountReadError","EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError","Schema","ServerSecretStore.ServerSecretStore","ServerEnvironment.ServerEnvironment","ManagedEndpointRuntime.CloudManagedEndpointRuntime","EnvironmentAuth.EnvironmentAuth","CliTokenManager.CloudCliTokenManager","EnvironmentAuth.ServerAuthCloudLinkJwtSigningError","EnvironmentAuth.isServerAuthInternalError","ServerConfig.ServerConfig","EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError","EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError","EnvironmentAuth.ServerAuthCloudHealthJwtSigningError","EnvironmentAuth.ServerAuthCloudMintJwtSigningError","ResourceAttribution.layer","ServerSecretStore.layer","ResourceMonitorBinary.layer","ServerConfig.ServerConfig","RelayClient.layerCloudflared","ProviderSessionRuntime.layer","SqlitePersistenceLayerLive","VcsProjectConfig.layer","AzureDevOpsCli.layer","BitbucketApi.layer","GitHubCli.layer","GitLabCli.layer","GitVcsDriver.layer","ProjectSetupScriptRunner.layer","TextGeneration.layer","CheckpointDiffQuery.layer","ProcessRunner.layer","PreviewManager.layer","WorkspacePaths.layer","T3ProjectFileLoader.layer","Keybindings.layer","ProviderEventLoggers.layer","OpenCodeRuntime.OpenCodeRuntimeLive","RepositoryIdentityResolver.layer","ServerEnvironment.layer","ExternalLauncher.layer","TraceDiagnostics.layer","AnalyticsService.layer","ServerLifecycleEvents.layer","NetService.layer","ServerRuntimeStartup.ServerRuntimeStartup","McpSessionRegistry.layer","PreviewAutomationBroker.layer","ServerSelfUpdate.layer","ServiceLauncherClient.layer","CloudCliState.readCliDesiredCloudLink","ServerRuntimeStartup.layerWithOptions","VcsProcess.layer","Schema","ProcessRunner.ProcessRunner","BootService.layer","packageJson.version","ProcessRunner.layer","BootService.BootService","NetService.layer","packageJson.version"],"sources":["../../../packages/shared/src/Net.ts","../package.json","../../../packages/contracts/src/baseSchemas.ts","../../../packages/contracts/src/providerInstance.ts","../../../packages/contracts/src/background.ts","../../../packages/contracts/src/auth.ts","../../../packages/contracts/src/environment.ts","../../../packages/contracts/src/model.ts","../../../packages/contracts/src/orchestration.ts","../../../packages/contracts/src/relay.ts","../../../packages/contracts/src/environmentHttp.ts","../../../packages/contracts/src/relayClient.ts","../../../packages/contracts/src/desktopBootstrap.ts","../../../packages/contracts/src/remoteAccess.ts","../../../packages/contracts/src/preview.ts","../../../packages/contracts/src/previewAutomation.ts","../../../packages/contracts/src/ipc.ts","../../../packages/contracts/src/terminal.ts","../../../packages/contracts/src/provider.ts","../../../packages/contracts/src/providerRuntime.ts","../../../packages/contracts/src/keybindings.ts","../../../packages/contracts/src/editor.ts","../../../packages/contracts/src/settings.ts","../../../packages/contracts/src/server.ts","../../../packages/contracts/src/vcs.ts","../../../packages/contracts/src/sourceControl.ts","../../../packages/contracts/src/git.ts","../../../packages/contracts/src/t3ProjectFile.ts","../../../packages/contracts/src/project.ts","../../../packages/contracts/src/filesystem.ts","../../../packages/contracts/src/assets.ts","../../../packages/contracts/src/review.ts","../../../packages/contracts/src/resourceTelemetry.ts","../../../packages/contracts/src/usage.ts","../../../packages/contracts/src/rpc.ts","../../../packages/shared/src/oauthScope.ts","../src/config.ts","../src/auth/utils.ts","../src/auth/EnvironmentAuthPolicy.ts","../src/persistence/Errors.ts","../src/persistence/AuthPairingLinks.ts","../src/auth/PairingGrantStore.ts","../src/auth/ServerSecretStore.ts","../src/persistence/AuthSessions.ts","../src/auth/SessionStore.ts","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/cryptoNode.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/utils.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/modular.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/curve.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/weierstrass.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/_shortw_utils.js","../../../node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/nist.js","../../../packages/shared/src/dpopCommon.ts","../../../packages/shared/src/relaySigning.ts","../../../packages/shared/src/dpop.ts","../src/auth/dpop.ts","../src/persistence/Migrations/001_OrchestrationEvents.ts","../src/persistence/Migrations/002_OrchestrationCommandReceipts.ts","../src/persistence/Migrations/003_CheckpointDiffBlobs.ts","../src/persistence/Migrations/004_ProviderSessionRuntime.ts","../src/persistence/Migrations/005_Projections.ts","../src/persistence/Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts","../src/persistence/Migrations/007_ProjectionThreadMessageAttachments.ts","../src/persistence/Migrations/008_ProjectionThreadActivitySequence.ts","../src/persistence/Migrations/009_ProviderSessionRuntimeMode.ts","../src/persistence/Migrations/010_ProjectionThreadsRuntimeMode.ts","../src/persistence/Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts","../src/persistence/Migrations/012_ProjectionThreadsInteractionMode.ts","../src/persistence/Migrations/013_ProjectionThreadProposedPlans.ts","../src/persistence/Migrations/014_ProjectionThreadProposedPlanImplementation.ts","../src/persistence/Migrations/015_ProjectionTurnsSourceProposedPlan.ts","../src/persistence/Migrations/016_CanonicalizeModelSelections.ts","../src/persistence/Migrations/017_ProjectionThreadsArchivedAt.ts","../src/persistence/Migrations/018_ProjectionThreadsArchivedAtIndex.ts","../src/persistence/Migrations/019_ProjectionSnapshotLookupIndexes.ts","../src/persistence/Migrations/020_AuthAccessManagement.ts","../src/persistence/Migrations/021_AuthSessionClientMetadata.ts","../src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts","../src/persistence/Migrations/023_ProjectionThreadShellSummary.ts","../src/persistence/Migrations/024_BackfillProjectionThreadShellSummary.ts","../src/persistence/Migrations/025_CleanupInvalidProjectionPendingApprovals.ts","../src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.ts","../src/persistence/Migrations/027_ProviderSessionRuntimeInstanceId.ts","../src/persistence/Migrations/028_ProjectionThreadSessionInstanceId.ts","../src/persistence/Migrations/029_ProjectionThreadDetailOrderingIndexes.ts","../src/persistence/Migrations/030_ProjectionThreadShellArchiveIndexes.ts","../src/persistence/Migrations/031_AuthAuthorizationScopes.ts","../src/persistence/Migrations/032_AuthPairingProofKeyThumbprint.ts","../src/persistence/Migrations/033_ProjectionThreadsSettled.ts","../src/persistence/Migrations/034_ProjectionThreadsSnoozed.ts","../src/persistence/Migrations/035_ProjectionThreadTitleRegeneration.ts","../src/persistence/Migrations/036_ProjectionThreadsPinned.ts","../src/persistence/Migrations/037_ProjectionTurnsKeysetIndex.ts","../src/persistence/Migrations/038_ProjectionThreadsPinOrderKey.ts","../src/persistence/Migrations.ts","../src/persistence/Layers/Sqlite.ts","../src/auth/EnvironmentAuth.ts","../src/cliAuthFormat.ts","../../../packages/shared/src/Struct.ts","../../../packages/shared/src/schemaJson.ts","../../../packages/shared/src/model.ts","../../../packages/shared/src/backgroundActivitySettings.ts","../../../packages/shared/src/serverSettings.ts","../src/bootstrap.ts","../../../packages/shared/src/shell.ts","../src/os-jank.ts","../src/cli/config.ts","../src/cli/auth.ts","../../../packages/shared/src/devHome.ts","../../../packages/tailscale/src/tailscale.ts","../src/atomicWrite.ts","../../../packages/shared/src/qrCode.ts","../src/startupAccess.ts","../src/serverRuntimeState.ts","../src/cli/pair.ts","../src/orchestration/Services/OrchestrationEngine.ts","../src/orchestration/Services/ProjectionSnapshotQuery.ts","../src/persistence/Services/OrchestrationCommandReceipts.ts","../src/persistence/Layers/OrchestrationCommandReceipts.ts","../src/persistence/Services/OrchestrationEventStore.ts","../src/persistence/Layers/OrchestrationEventStore.ts","../src/observability/Attributes.ts","../src/observability/Metrics.ts","../src/orchestration/Errors.ts","../../../packages/shared/src/path.ts","../src/orchestration/commandInvariants.ts","../src/orchestration/Schemas.ts","../src/orchestration/projector.ts","../src/orchestration/decider.ts","../src/orchestration/Services/ProjectionPipeline.ts","../src/orchestration/Layers/OrchestrationEngine.ts","../src/persistence/Services/ProjectionPendingApprovals.ts","../src/persistence/Services/ProjectionProjects.ts","../src/persistence/Services/ProjectionState.ts","../src/persistence/Services/ProjectionThreadActivities.ts","../src/persistence/Services/ProjectionThreadMessages.ts","../src/persistence/Services/ProjectionThreadProposedPlans.ts","../src/persistence/Services/ProjectionThreadSessions.ts","../src/persistence/Services/ProjectionTurns.ts","../src/persistence/Services/ProjectionThreads.ts","../src/persistence/Layers/ProjectionPendingApprovals.ts","../src/persistence/Layers/ProjectionProjects.ts","../src/persistence/Layers/ProjectionState.ts","../src/persistence/Layers/ProjectionThreadActivities.ts","../src/persistence/Layers/ProjectionThreadMessages.ts","../src/persistence/Layers/ProjectionThreadProposedPlans.ts","../src/persistence/Layers/ProjectionThreadSessions.ts","../src/persistence/Layers/ProjectionTurns.ts","../src/persistence/Layers/ProjectionThreads.ts","../src/attachmentPaths.ts","../src/imageMime.ts","../src/attachmentStore.ts","../src/orchestration/Layers/ProjectionPipeline.ts","../src/persistence/Services/ProjectionCheckpoints.ts","../src/orchestration/ThreadBackgroundLiveness.ts","../src/orchestration/ThreadPlanProgress.ts","../src/orchestration/threadDetailCursor.ts","../../../packages/shared/src/sourceControl.ts","../../../packages/shared/src/git.ts","../src/stream/collectUint8StreamText.ts","../src/processRunner.ts","../src/project/RepositoryIdentityResolver.ts","../src/orchestration/Layers/ProjectionSnapshotQuery.ts","../src/orchestration/runtimeLayer.ts","../../../packages/shared/src/keybindings.ts","../src/keybindings.ts","../src/process/externalLauncher.ts","../src/orchestration/Services/OrchestrationReactor.ts","../src/serverLifecycleEvents.ts","../src/serverSettings.ts","../src/telemetry/Identify.ts","../src/telemetry/AnalyticsService.ts","../src/cloud/pinnedRuntime.ts","../src/cloud/serviceProtocol.ts","../src/cloud/servicePreflight.ts","../src/cloud/serviceLauncherClient.ts","../src/cloud/selfUpdate.ts","../src/environment/ServerEnvironmentLabel.ts","../src/environment/ServerEnvironment.ts","../src/provider/Services/ProviderSessionReaper.ts","../src/serverActivation.ts","../src/serverRuntimeStartup.ts","../src/workspace/WorkspacePaths.ts","../src/cli/project.ts","../src/utils/subscribeBeforeSnapshot.ts","../src/resourceTelemetry/DesktopTelemetryReceiver.ts","../src/background/HostPowerMonitor.ts","../src/background/BackgroundPolicy.ts","../../../packages/shared/src/devProxy.ts","../../../packages/shared/src/logging.ts","../../../packages/shared/src/observability.ts","../../../packages/shared/src/filePreview.ts","../../../packages/shared/src/projectFavicon.ts","../../../packages/shared/src/t3ProjectFile.ts","../src/project/T3ProjectFileLoader.ts","../src/project/ProjectFaviconResolver.ts","../src/assets/AssetAccess.ts","../src/observability/BrowserTraceCollector.ts","../../../packages/shared/src/relayTracing.ts","../src/cloud/traceRelayRequest.ts","../src/auth/http.ts","../src/httpCors.ts","../src/http.ts","../src/checkpointing/Errors.ts","../src/checkpointing/Utils.ts","../src/git/remoteRefs.ts","../src/vcs/GitVcsDriverCore.ts","../src/vcs/VcsProcess.ts","../src/vcs/VcsDriver.ts","../src/vcs/GitVcsDriver.ts","../src/vcs/VcsProjectConfig.ts","../src/vcs/VcsDriverRegistry.ts","../src/checkpointing/CheckpointStore.ts","../src/checkpointing/CheckpointDiffQuery.ts","../src/orchestration/ActivityPayloadProjection.ts","../src/orchestration/Normalizer.ts","../src/observability/RpcInstrumentation.ts","../src/provider/Services/ProviderRegistry.ts","../src/provider/providerMaintenanceCommandCoordinator.ts","../../../packages/shared/src/semver.ts","../src/provider/providerMaintenance.ts","../src/provider/providerMaintenanceRunner.ts","../../../packages/shared/src/KeyedCoalescingWorker.ts","../../../packages/shared/src/terminalLabels.ts","../../../packages/shared/src/preview.ts","../src/preview/PortScanner.ts","../src/terminal/Manager.ts","../src/mcp/McpInvocationContext.ts","../src/mcp/PreviewAutomationBroker.ts","../src/preview/Manager.ts","../../../packages/shared/src/searchRanking.ts","../src/workspace/WorkspaceSearchIndex.ts","../src/workspace/WorkspaceEntries.ts","../src/workspace/WorkspaceFileSystem.ts","../src/orchestration/workflowScriptQuery.ts","../src/provider/Services/ProviderInstanceRegistry.ts","../src/textGeneration/TextGeneration.ts","../src/textGeneration/TextGenerationPresets.ts","../../../packages/shared/src/projectScripts.ts","../src/project/ProjectSetupScriptRunner.ts","../src/sourceControl/azureDevOpsPullRequests.ts","../src/sourceControl/SourceControlProvider.ts","../src/sourceControl/AzureDevOpsCli.ts","../src/sourceControl/SourceControlProviderDiscovery.ts","../src/sourceControl/AzureDevOpsSourceControlProvider.ts","../src/sourceControl/bitbucketPullRequests.ts","../src/sourceControl/BitbucketApi.ts","../src/sourceControl/BitbucketSourceControlProvider.ts","../src/sourceControl/gitHubPullRequests.ts","../src/sourceControl/GitHubCli.ts","../src/sourceControl/gitHubAuthStatus.ts","../src/sourceControl/GitHubSourceControlProvider.ts","../src/sourceControl/gitLabMergeRequests.ts","../src/sourceControl/GitLabCli.ts","../src/sourceControl/gitLabAuthStatus.ts","../src/sourceControl/GitLabSourceControlProvider.ts","../src/sourceControl/SourceControlProviderRegistry.ts","../src/sourceControl/PrTemplateDetection.ts","../src/git/GitManager.ts","../src/git/GitWorkflowService.ts","../src/vcs/VcsStatusBroadcaster.ts","../src/vcs/VcsProvisioningService.ts","../src/review/ReviewService.ts","../src/auth/RpcAuthorization.ts","../src/resourceTelemetry/Model.ts","../src/resourceTelemetry/ResourceMonitorBinary.ts","../src/resourceTelemetry/NativeTelemetryClient.ts","../src/resourceTelemetry/ResourceAttribution.ts","../src/resourceTelemetry/ResourceTelemetryHistory.ts","../src/resourceTelemetry/ResourceTelemetry.ts","../src/diagnostics/ProcessDiagnostics.ts","../src/diagnostics/ProcessResourceMonitor.ts","../src/pathExpansion.ts","../src/provider/Drivers/ClaudeHome.ts","../src/provider/Drivers/CodexHomeLayout.ts","../src/usage/usageTranscripts.ts","../src/usage/usagePricing.ts","../src/usage/usageAggregation.ts","../src/usage/usageTranscriptReader.ts","../src/usage/usageScanCache.ts","../src/usage/UsageService.ts","../src/diagnostics/TraceDiagnostics.ts","../src/sourceControl/SourceControlDiscovery.ts","../src/sourceControl/SourceControlRepositoryService.ts","../../../packages/shared/src/relayClient.ts","../src/ws.ts","../src/persistence/ProviderSessionRuntime.ts","../src/provider/Errors.ts","../src/provider/Services/ProviderSessionDirectory.ts","../src/provider/Layers/ProviderSessionDirectory.ts","../src/provider/Services/ProviderAdapterRegistry.ts","../src/provider/Layers/ProviderAdapterRegistry.ts","../src/provider/Layers/EventNdjsonLogger.ts","../src/provider/Layers/ProviderEventLoggers.ts","../src/provider/Services/ProviderService.ts","../src/mcp/McpProviderSession.ts","../src/mcp/McpSessionRegistry.ts","../src/provider/Layers/ProviderService.ts","../src/provider/Layers/ProviderSessionReaper.ts","../src/provider/providerSnapshot.ts","../src/provider/opencodeRuntime.ts","../src/textGeneration/TextGenerationUtils.ts","../src/textGeneration/TextGenerationPrompts.ts","../src/provider/Drivers/ClaudeExecutable.ts","../src/provider/Drivers/ClaudeSkills.ts","../src/provider/Layers/ClaudeProvider.ts","../src/textGeneration/ClaudeTextGeneration.ts","../../../packages/shared/src/cliArgs.ts","../src/provider/Layers/ClaudeAdapter.ts","../src/provider/makeManagedServerProvider.ts","../src/provider/ProviderDriver.ts","../src/provider/ProviderInstanceEnvironment.ts","../src/provider/providerUpdateSettings.ts","../src/provider/Drivers/ClaudeDriver.ts","../src/provider/Layers/codexLaunchArgs.ts","../src/codexModelOptions.ts","../src/textGeneration/CodexTextGeneration.ts","../../../packages/effect-codex-app-server/src/errors.ts","../../../packages/effect-codex-app-server/src/_generated/schema.gen.ts","../../../packages/effect-codex-app-server/src/_generated/meta.gen.ts","../../../packages/effect-codex-app-server/src/_generated/namespaces.gen.ts","../../../packages/effect-codex-app-server/src/_internal/shared.ts","../../../packages/effect-codex-app-server/src/protocol.ts","../../../packages/effect-codex-app-server/src/_internal/stdio.ts","../../../packages/effect-codex-app-server/src/client.ts","../src/provider/Layers/CodexProvider.ts","../src/provider/CodexDeveloperInstructions.ts","../src/provider/Layers/CodexSessionRuntime.ts","../src/provider/Layers/CodexAdapter.ts","../src/provider/Drivers/CodexDriver.ts","../../../packages/effect-acp/src/_generated/schema.gen.ts","../../../packages/effect-acp/src/errors.ts","../../../packages/effect-acp/src/_generated/meta.gen.ts","../../../packages/effect-acp/src/protocol.ts","../../../packages/effect-acp/src/rpc.ts","../../../packages/effect-acp/src/_internal/shared.ts","../../../packages/effect-acp/src/_internal/stdio.ts","../../../packages/effect-acp/src/client.ts","../../../packages/shared/src/toolActivity.ts","../src/provider/acp/AcpRuntimeModel.ts","../src/provider/acp/AcpSessionRuntime.ts","../src/provider/acp/CursorAcpExtension.ts","../src/provider/Layers/CursorProvider.ts","../src/provider/acp/CursorAcpSupport.ts","../src/textGeneration/CursorTextGeneration.ts","../src/provider/acp/AcpAdapterSupport.ts","../src/provider/acp/AcpCoreRuntimeEvents.ts","../src/provider/acp/AcpNativeLogging.ts","../src/provider/Layers/CursorAdapter.ts","../src/provider/Drivers/CursorDriver.ts","../src/provider/acp/XAiAcpExtension.ts","../src/provider/acp/GrokAcpSupport.ts","../src/textGeneration/GrokTextGeneration.ts","../src/provider/Layers/GrokAdapter.ts","../src/provider/Layers/GrokProvider.ts","../src/provider/Drivers/GrokDriver.ts","../src/textGeneration/OpenCodeTextGeneration.ts","../src/provider/Layers/OpenCodeAdapter.ts","../src/provider/Layers/OpenCodeProvider.ts","../src/provider/Drivers/OpenCodeDriver.ts","../src/provider/builtInDrivers.ts","../src/provider/Services/ProviderInstanceRegistryMutator.ts","../src/provider/unavailableProviderSnapshot.ts","../src/provider/Layers/ProviderInstanceRegistryLive.ts","../src/provider/Layers/ProviderInstanceRegistryHydration.ts","../src/mcp/toolkits/preview/tools.ts","../src/mcp/toolkits/preview/handlers.ts","../src/mcp/McpHttpServer.ts","../src/orchestration/Services/CheckpointReactor.ts","../src/orchestration/Services/ProviderCommandReactor.ts","../src/orchestration/Services/ProviderRuntimeIngestion.ts","../src/orchestration/Services/ThreadDeletionReactor.ts","../../../packages/shared/src/agentAwareness.ts","../../../packages/shared/src/DrainableWorker.ts","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/buffer_utils.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/base64.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/base64url.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/crypto_key.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/invalid_key_input.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/util/errors.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/is_key_like.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/helpers.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/type_checks.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/signing.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwk_to_key.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/normalize_key.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/asn1.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/key/import.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_crit.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/validate_algorithms.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/check_key_type.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/verify.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/verify.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/lib/jwt_claims_set.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/verify.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/flattened/sign.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jws/compact/sign.js","../../../node_modules/.pnpm/jose@6.2.2/node_modules/jose/dist/webapi/jwt/sign.js","../../../packages/shared/src/relayJwt.ts","../src/cloud/config.ts","../src/cloud/environmentKeys.ts","../src/relay/AgentAwarenessRelay.ts","../src/orchestration/Layers/OrchestrationReactor.ts","../src/orchestration/Services/RuntimeReceiptBus.ts","../src/orchestration/Layers/RuntimeReceiptBus.ts","../src/git/Utils.ts","../src/orchestration/Layers/ProviderRuntimeIngestion.ts","../src/orchestration/Layers/ProviderCommandReactor.ts","../../../node_modules/.pnpm/@pierre+diffs@1.3.0-beta.10_patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb5_4f94257a3bd1f714011bf2de091d7919/node_modules/@pierre/diffs/dist/constants.js","../../../node_modules/.pnpm/@pierre+diffs@1.3.0-beta.10_patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb5_4f94257a3bd1f714011bf2de091d7919/node_modules/@pierre/diffs/dist/utils/cleanLastNewline.js","../../../node_modules/.pnpm/@pierre+diffs@1.3.0-beta.10_patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb5_4f94257a3bd1f714011bf2de091d7919/node_modules/@pierre/diffs/dist/utils/detachString.js","../../../node_modules/.pnpm/@pierre+diffs@1.3.0-beta.10_patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb5_4f94257a3bd1f714011bf2de091d7919/node_modules/@pierre/diffs/dist/utils/realignChangeContent.js","../../../node_modules/.pnpm/@pierre+diffs@1.3.0-beta.10_patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb5_4f94257a3bd1f714011bf2de091d7919/node_modules/@pierre/diffs/dist/utils/parsePatchFiles.js","../src/checkpointing/Diffs.ts","../src/orchestration/Layers/CheckpointReactor.ts","../src/orchestration/Layers/ThreadDeletionReactor.ts","../../../packages/shared/src/remote.ts","../../../packages/shared/src/connectAuth.ts","../../../packages/shared/src/relayAuth.ts","../../../packages/shared/src/relayUrl.ts","../src/cloud/publicConfig.ts","../src/provider/providerStatusCache.ts","../src/provider/Layers/ProviderRegistry.ts","../../../packages/shared/src/httpObservability.ts","../src/serverLogger.ts","../src/observability/Layers/Observability.ts","../src/cloud/ManagedEndpointRuntime.ts","../src/cloud/CliState.ts","../src/cloud/cliAuthHtml.ts","../src/cloud/CliTokenManager.ts","../src/cloud/http.ts","../src/cloud/relayTracing.ts","../src/orchestration/http.ts","../src/server.ts","../src/cli/server.ts","../src/cloud/bootService.ts","../src/cli/service.ts","../src/cli/servicePreflight.ts","../src/bin.ts"],"sourcesContent":["import * as NodeNet from \"node:net\";\n\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Context from \"effect/Context\";\nimport * as Predicate from \"effect/Predicate\";\n\nexport class NetError extends Data.TaggedError(\"NetError\")<{\n  readonly message: string;\n  readonly cause?: unknown;\n}> {}\n\nconst isErrnoExceptionWithCode = (\n  cause: unknown,\n): cause is {\n  readonly code: string;\n} =>\n  Predicate.isObject(cause) &&\n  Predicate.hasProperty(cause, \"code\") &&\n  Predicate.isString(cause.code);\n\nconst closeServer = (server: NodeNet.Server) => {\n  try {\n    server.close();\n  } catch {\n    // Ignore close failures during cleanup.\n  }\n};\n\nexport interface NetServiceShape {\n  /**\n   * Returns true when a TCP server can bind to {host, port}.\n   */\n  readonly canListenOnHost: (port: number, host: string) => Effect.Effect<boolean>;\n\n  /**\n   * Checks loopback availability on both IPv4 and IPv6 localhost addresses.\n   */\n  readonly isPortAvailableOnLoopback: (port: number) => Effect.Effect<boolean>;\n\n  /**\n   * Reserve an ephemeral loopback port and release it immediately.\n   */\n  readonly reserveLoopbackPort: (host?: string) => Effect.Effect<number, NetError>;\n\n  /**\n   * Resolve an available listening port, preferring the provided port first.\n   */\n  readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;\n}\n\n/**\n * NetService - Service tag for startup networking helpers.\n */\nexport class NetService extends Context.Service<NetService, NetServiceShape>()(\n  \"@t3tools/shared/Net/NetService\",\n) {}\n\nexport const make = () => {\n  /**\n   * Returns true when a TCP server can bind to {host, port}.\n   * `EADDRNOTAVAIL` is treated as available so IPv6-absent hosts don't fail\n   * loopback availability checks.\n   */\n  const canListenOnHost = (port: number, host: string): Effect.Effect<boolean> =>\n    Effect.callback<boolean>((resume) => {\n      const server = NodeNet.createServer();\n      let settled = false;\n\n      const settle = (value: boolean) => {\n        if (settled) return;\n        settled = true;\n        resume(Effect.succeed(value));\n      };\n\n      server.unref();\n\n      server.once(\"error\", (cause) => {\n        if (isErrnoExceptionWithCode(cause) && cause.code === \"EADDRNOTAVAIL\") {\n          settle(true);\n          return;\n        }\n        settle(false);\n      });\n\n      server.once(\"listening\", () => {\n        server.close(() => {\n          settle(true);\n        });\n      });\n\n      server.listen({ host, port });\n\n      return Effect.sync(() => {\n        closeServer(server);\n      });\n    });\n\n  const hasListenerOnHost = (port: number, host: string): Effect.Effect<boolean> =>\n    Effect.callback<boolean>((resume) => {\n      const socket = NodeNet.createConnection({ host, port });\n      let settled = false;\n\n      const settle = (value: boolean) => {\n        if (settled) return;\n        settled = true;\n        socket.destroy();\n        resume(Effect.succeed(value));\n      };\n\n      socket.unref();\n      socket.setTimeout(250);\n      socket.once(\"connect\", () => {\n        settle(true);\n      });\n      socket.once(\"error\", () => {\n        settle(false);\n      });\n      socket.once(\"timeout\", () => {\n        settle(false);\n      });\n\n      return Effect.sync(() => {\n        socket.destroy();\n      });\n    });\n\n  const isPortAvailableOnLoopback = (port: number): Effect.Effect<boolean> =>\n    Effect.gen(function* () {\n      const hasListener = yield* Effect.zipWith(\n        hasListenerOnHost(port, \"127.0.0.1\"),\n        hasListenerOnHost(port, \"::1\"),\n        (ipv4, ipv6) => ipv4 || ipv6,\n      );\n      if (hasListener) {\n        return false;\n      }\n\n      return yield* Effect.zipWith(\n        canListenOnHost(port, \"127.0.0.1\"),\n        canListenOnHost(port, \"::1\"),\n        (ipv4, ipv6) => ipv4 && ipv6,\n      );\n    });\n\n  /**\n   * Reserve an ephemeral loopback port and release it immediately.\n   * Returns the reserved port number.\n   */\n  const reserveLoopbackPort = (host = \"127.0.0.1\"): Effect.Effect<number, NetError> =>\n    Effect.callback<number, NetError>((resume) => {\n      const probe = NodeNet.createServer();\n      let settled = false;\n\n      const settle = (effect: Effect.Effect<number, NetError>) => {\n        if (settled) return;\n        settled = true;\n        resume(effect);\n      };\n\n      probe.once(\"error\", (cause) => {\n        settle(Effect.fail(new NetError({ message: \"Failed to reserve loopback port\", cause })));\n      });\n\n      probe.listen(0, host, () => {\n        const address = probe.address();\n        const port = typeof address === \"object\" && address !== null ? address.port : 0;\n        probe.close(() => {\n          if (port > 0) {\n            settle(Effect.succeed(port));\n            return;\n          }\n          settle(Effect.fail(new NetError({ message: \"Failed to reserve loopback port\" })));\n        });\n      });\n\n      return Effect.sync(() => {\n        closeServer(probe);\n      });\n    });\n\n  return {\n    canListenOnHost,\n    isPortAvailableOnLoopback,\n    reserveLoopbackPort,\n    findAvailablePort: (preferred) =>\n      Effect.gen(function* () {\n        if (preferred > 0 && (yield* isPortAvailableOnLoopback(preferred))) {\n          return preferred;\n        }\n        return yield* reserveLoopbackPort();\n      }),\n  } satisfies NetServiceShape;\n};\n\nexport const layer = Layer.sync(NetService, make);\n","","import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\n\nexport const TrimmedString = Schema.String.pipe(\n  Schema.decodeTo(\n    Schema.String,\n    SchemaTransformation.transformOrFail({\n      decode: (value) => Effect.succeed(value.trim()),\n      encode: (value) => Effect.succeed(value.trim()),\n    }),\n  ),\n);\nexport const TrimmedNonEmptyString = TrimmedString.check(Schema.isNonEmpty());\n\nexport const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\nexport const PositiveInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1));\nexport const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));\n\nexport const IsoDateTime = Schema.String;\nexport type IsoDateTime = typeof IsoDateTime.Type;\n\n/**\n * Wire codec for server→client arrays whose element unions grow over time\n * (new literal members, new struct variants). Decoding drops elements the\n * current build cannot decode instead of failing the whole payload — a client\n * has to keep decoding configs sent by servers newer than itself, and\n * rejecting the payload would take down the connection over data the client\n * couldn't act on anyway. Encoding is the plain array encoding.\n */\nexport const ForwardCompatibleArray = <Element extends Schema.Top>(element: Element) => {\n  const decodeElement = Schema.decodeUnknownOption(element as never);\n  return Schema.Array(Schema.Unknown).pipe(\n    Schema.decodeTo(\n      Schema.Array(element),\n      SchemaTransformation.transform<ReadonlyArray<Element[\"Encoded\"]>, ReadonlyArray<unknown>>({\n        decode: (values) =>\n          values.filter((value) => Option.isSome(decodeElement(value))) as ReadonlyArray<\n            Element[\"Encoded\"]\n          >,\n        encode: (values) => values,\n      }),\n    ),\n  );\n};\n\n/**\n * Construct a branded identifier. Enforces non-empty trimmed strings\n */\nconst makeEntityId = <Brand extends string>(brand: Brand) => {\n  return TrimmedNonEmptyString.pipe(Schema.brand(brand));\n};\n\nexport const ThreadId = makeEntityId(\"ThreadId\");\nexport type ThreadId = typeof ThreadId.Type;\nexport const ProjectId = makeEntityId(\"ProjectId\");\nexport type ProjectId = typeof ProjectId.Type;\nexport const EnvironmentId = makeEntityId(\"EnvironmentId\");\nexport type EnvironmentId = typeof EnvironmentId.Type;\nexport const CommandId = makeEntityId(\"CommandId\");\nexport type CommandId = typeof CommandId.Type;\nexport const EventId = makeEntityId(\"EventId\");\nexport type EventId = typeof EventId.Type;\nexport const MessageId = makeEntityId(\"MessageId\");\nexport type MessageId = typeof MessageId.Type;\nexport const TurnId = makeEntityId(\"TurnId\");\nexport type TurnId = typeof TurnId.Type;\nexport const AuthSessionId = makeEntityId(\"AuthSessionId\");\nexport type AuthSessionId = typeof AuthSessionId.Type;\nexport const RpcClientId = NonNegativeInt.pipe(Schema.brand(\"RpcClientId\"));\nexport type RpcClientId = typeof RpcClientId.Type;\n\nexport const ProviderItemId = makeEntityId(\"ProviderItemId\");\nexport type ProviderItemId = typeof ProviderItemId.Type;\nexport const RuntimeSessionId = makeEntityId(\"RuntimeSessionId\");\nexport type RuntimeSessionId = typeof RuntimeSessionId.Type;\nexport const RuntimeItemId = makeEntityId(\"RuntimeItemId\");\nexport type RuntimeItemId = typeof RuntimeItemId.Type;\nexport const RuntimeRequestId = makeEntityId(\"RuntimeRequestId\");\nexport type RuntimeRequestId = typeof RuntimeRequestId.Type;\nexport const RuntimeTaskId = makeEntityId(\"RuntimeTaskId\");\nexport type RuntimeTaskId = typeof RuntimeTaskId.Type;\nexport const ApprovalRequestId = makeEntityId(\"ApprovalRequestId\");\nexport type ApprovalRequestId = typeof ApprovalRequestId.Type;\nexport const CheckpointRef = makeEntityId(\"CheckpointRef\");\nexport type CheckpointRef = typeof CheckpointRef.Type;\n","/**\n * Provider-instance contracts.\n *\n * Splits the historical \"provider kind\" concept into two:\n *\n *   - `ProviderDriverKind` is the implementation kind selector (e.g. codex,\n *     claudeAgent, a fork's `ollama`, …). It picks which driver package\n *     handles the protocol, the probe, the adapter, and text generation.\n *\n *   - `ProviderInstanceId` is the routing key (a user-defined slug).\n *     Threads, sessions, runtime events, and persisted bindings reference\n *     instance ids — never driver kinds — so a user can configure multiple\n *     instances of the same driver (e.g. `codex_personal` + `codex_work`),\n *     each with independent driver-specific configuration.\n *\n * Forward/backward compatibility invariant\n * ----------------------------------------\n * `ProviderDriverKind` is intentionally an **open** branded slug, not a closed\n * literal union. The server hosts forks, ships in PRs that add drivers, and\n * users frequently roll between branches and forks. Any of those paths can\n * leave `ServerSettings`, persisted thread state, or session bindings\n * referencing a driver that the currently-running build does not know about.\n *\n * The rule: parsing any of those payloads must always succeed, and the\n * runtime is responsible for marking the unknown driver/instance as\n * \"unavailable\" rather than crashing. Built-in drivers shipped by the core\n * product happens to register in a given build is not part of the contract\n * layer. Driver availability is discovered through the runtime registry.\n *\n * Driver-specific configuration is similarly opaque at the contracts layer:\n * drivers live in (or will be extracted to) their own packages and own their\n * config schemas. The contracts package only knows the envelope.\n *\n * @module providerInstance\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nconst PROVIDER_SLUG_MAX_CHARS = 64;\n/**\n * Slug pattern shared by driver kinds and instance ids — letters, digits,\n * dashes, underscores. The first character must be a letter so slugs remain\n * JS-identifier friendly when used as object keys, log fields, or telemetry\n * attributes. Mixed case is permitted so historical driver kinds (e.g.\n * `claudeAgent`) can be used verbatim during the migration and so external\n * fork authors retain reasonable freedom.\n */\nconst PROVIDER_SLUG_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;\nconst ENVIRONMENT_VARIABLE_NAME_MAX_CHARS = 128;\nconst ENVIRONMENT_VARIABLE_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\nconst slugSchema = TrimmedNonEmptyString.check(\n  Schema.isMaxLength(PROVIDER_SLUG_MAX_CHARS),\n  Schema.isPattern(PROVIDER_SLUG_PATTERN),\n);\n\n/**\n * `ProviderDriverKind` — open branded slug naming a driver implementation.\n *\n * Constraints (validated at the schema layer):\n *   - starts with a letter\n *   - only letters, digits, `-`, `_` after the first char\n *   - 1..64 characters\n *\n * Notably **not** validated: that the driver is one we know how to load.\n * That check belongs to the runtime registry, which downgrades unknown\n * drivers gracefully (see module docs).\n */\nexport const ProviderDriverKind = slugSchema.pipe(Schema.brand(\"ProviderDriverKind\"));\nexport type ProviderDriverKind = typeof ProviderDriverKind.Type;\n\nconst isProviderDriverKindValue = Schema.is(ProviderDriverKind);\nexport const isProviderDriverKind = (value: unknown): value is ProviderDriverKind =>\n  isProviderDriverKindValue(value);\n\n/**\n * `ProviderInstanceId` — user-defined routing key for a configured provider\n * instance. Same slug rules as `ProviderDriverKind`; branded separately so the\n * type system cannot confuse the two.\n */\nexport const ProviderInstanceId = slugSchema.pipe(Schema.brand(\"ProviderInstanceId\"));\nexport type ProviderInstanceId = typeof ProviderInstanceId.Type;\n\n/**\n * Lightweight reference identifying which driver implements an instance.\n * Carried alongside `ProviderInstanceId` on wire shapes so consumers can\n * branch on driver behavior (icons, capabilities, presentation) without\n * having to look up the instance in the registry.\n */\nexport const ProviderInstanceRef = Schema.Struct({\n  instanceId: ProviderInstanceId,\n  driver: ProviderDriverKind,\n});\nexport type ProviderInstanceRef = typeof ProviderInstanceRef.Type;\n\nexport const ProviderInstanceEnvironmentVariableName = TrimmedNonEmptyString.check(\n  Schema.isMaxLength(ENVIRONMENT_VARIABLE_NAME_MAX_CHARS),\n  Schema.isPattern(ENVIRONMENT_VARIABLE_NAME_PATTERN),\n);\nexport type ProviderInstanceEnvironmentVariableName =\n  typeof ProviderInstanceEnvironmentVariableName.Type;\n\nexport const ProviderInstanceEnvironmentVariable = Schema.Struct({\n  name: ProviderInstanceEnvironmentVariableName,\n  value: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  sensitive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  valueRedacted: Schema.optionalKey(Schema.Boolean),\n});\nexport type ProviderInstanceEnvironmentVariable = typeof ProviderInstanceEnvironmentVariable.Type;\n\nexport const ProviderInstanceEnvironment = Schema.Array(ProviderInstanceEnvironmentVariable);\nexport type ProviderInstanceEnvironment = typeof ProviderInstanceEnvironment.Type;\n\n/**\n * Envelope shape for a provider instance configuration in `ServerSettings`.\n *\n * `driver` is intentionally accepted as any well-formed slug (see module\n * docs). The driver-specific config payload is left as `Schema.Unknown`;\n * each driver registers its own decoder with the runtime registry, and\n * envelopes for unknown drivers are preserved verbatim so they round-trip\n * across version changes without data loss.\n */\nexport const ProviderInstanceConfig = Schema.Struct({\n  driver: ProviderDriverKind,\n  displayName: Schema.optional(TrimmedNonEmptyString),\n  accentColor: Schema.optional(TrimmedNonEmptyString),\n  environment: Schema.optionalKey(ProviderInstanceEnvironment),\n  enabled: Schema.optionalKey(Schema.Boolean),\n  config: Schema.optionalKey(Schema.Unknown),\n});\nexport type ProviderInstanceConfig = typeof ProviderInstanceConfig.Type;\n\n/**\n * Map shape for `ServerSettings.providerInstances`. Keyed by\n * `ProviderInstanceId`, values are envelopes the registry feeds to drivers.\n */\nexport const ProviderInstanceConfigMap = Schema.Record(ProviderInstanceId, ProviderInstanceConfig);\nexport type ProviderInstanceConfigMap = typeof ProviderInstanceConfigMap.Type;\n\n/**\n * Construct the canonical `ProviderInstanceId` used as a back-compat default\n * for a built-in driver. The legacy single-instance-per-driver world used\n * the driver kind itself as the instance id; preserving that mapping keeps\n * existing persisted threads, bindings, and cache files routable across the\n * migration without rewriting their stored selection payloads.\n */\nexport const defaultInstanceIdForDriver = (driver: ProviderDriverKind): ProviderInstanceId =>\n  ProviderInstanceId.make(driver);\n","import * as Schema from \"effect/Schema\";\n\nimport {\n  AuthSessionId,\n  EnvironmentId,\n  RpcClientId,\n  ThreadId,\n  TrimmedNonEmptyString,\n} from \"./baseSchemas.ts\";\nimport { ProviderInstanceId } from \"./providerInstance.ts\";\n\nexport const BackgroundBooleanState = Schema.Literals([\"true\", \"false\", \"unknown\"]);\nexport type BackgroundBooleanState = typeof BackgroundBooleanState.Type;\n\nexport const HostPowerThermalState = Schema.Literals([\n  \"unknown\",\n  \"nominal\",\n  \"fair\",\n  \"serious\",\n  \"critical\",\n]);\nexport type HostPowerThermalState = typeof HostPowerThermalState.Type;\n\nexport const HostPowerSource = Schema.Literals([\n  \"unknown\",\n  \"node-macos-shell\",\n  \"node-macos-native\",\n  \"node-linux\",\n  \"node-windows\",\n  \"electron-main\",\n]);\nexport type HostPowerSource = typeof HostPowerSource.Type;\n\nexport const HostPowerSnapshot = Schema.Struct({\n  source: HostPowerSource,\n  idle: BackgroundBooleanState,\n  idleSeconds: Schema.NullOr(Schema.Number),\n  locked: BackgroundBooleanState,\n  suspended: Schema.Boolean,\n  onBattery: BackgroundBooleanState,\n  lowPowerMode: BackgroundBooleanState,\n  thermalState: HostPowerThermalState,\n  stale: Schema.Boolean,\n  updatedAt: Schema.DateTimeUtc,\n});\nexport type HostPowerSnapshot = typeof HostPowerSnapshot.Type;\n\nexport const BackgroundScope = Schema.Union([\n  Schema.Struct({ type: Schema.Literal(\"server-config\") }),\n  Schema.Struct({\n    type: Schema.Literal(\"provider-status\"),\n    instanceId: Schema.optionalKey(ProviderInstanceId),\n  }),\n  Schema.Struct({ type: Schema.Literal(\"vcs-status\"), cwd: Schema.String }),\n  Schema.Struct({ type: Schema.Literal(\"git-refs\"), cwd: Schema.String }),\n  Schema.Struct({ type: Schema.Literal(\"diagnostics\") }),\n  Schema.Struct({ type: Schema.Literal(\"thread\"), threadId: ThreadId }),\n]);\nexport type BackgroundScope = typeof BackgroundScope.Type;\n\nexport const ClientKind = Schema.Literals([\"web\", \"desktop-renderer\", \"mobile\", \"unknown\"]);\nexport type ClientKind = typeof ClientKind.Type;\n\nexport const ClientActivityClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));\nexport type ClientActivityClientId = typeof ClientActivityClientId.Type;\n\nexport const ClientActivityReportInput = Schema.Struct({\n  environmentId: Schema.optionalKey(EnvironmentId),\n  clientId: ClientActivityClientId,\n  clientKind: ClientKind,\n  visible: Schema.Boolean,\n  focused: Schema.Boolean,\n  recentlyInteracted: Schema.Boolean,\n  appState: Schema.optionalKey(Schema.Literals([\"active\", \"inactive\", \"background\", \"unknown\"])),\n  lowPowerMode: Schema.optionalKey(BackgroundBooleanState),\n  batteryState: Schema.optionalKey(Schema.Literals([\"unknown\", \"unplugged\", \"charging\", \"full\"])),\n  networkType: Schema.optionalKey(Schema.String),\n  scopes: Schema.Array(BackgroundScope),\n  ttlMs: Schema.optionalKey(Schema.Number),\n  observedAt: Schema.DateTimeUtc,\n});\nexport type ClientActivityReportInput = typeof ClientActivityReportInput.Type;\n\nexport const ClientActivityLease = Schema.Struct({\n  sessionId: AuthSessionId,\n  rpcClientId: RpcClientId,\n  clientId: ClientActivityClientId,\n  clientKind: ClientKind,\n  visible: Schema.Boolean,\n  focused: Schema.Boolean,\n  recentlyInteracted: Schema.Boolean,\n  appState: Schema.optionalKey(Schema.Literals([\"active\", \"inactive\", \"background\", \"unknown\"])),\n  lowPowerMode: Schema.optionalKey(BackgroundBooleanState),\n  batteryState: Schema.optionalKey(Schema.Literals([\"unknown\", \"unplugged\", \"charging\", \"full\"])),\n  networkType: Schema.optionalKey(Schema.String),\n  scopes: Schema.Array(BackgroundScope),\n  updatedAt: Schema.DateTimeUtc,\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type ClientActivityLease = typeof ClientActivityLease.Type;\n\nexport const BackgroundPolicySnapshot = Schema.Struct({\n  hostPower: HostPowerSnapshot,\n  leases: Schema.Array(ClientActivityLease),\n  activeForegroundLeaseCount: Schema.Number,\n  activeScopeKeys: Schema.Array(Schema.String),\n  shouldRunOpportunisticWork: Schema.Boolean,\n  updatedAt: Schema.DateTimeUtc,\n});\nexport type BackgroundPolicySnapshot = typeof BackgroundPolicySnapshot.Type;\n","import * as Schema from \"effect/Schema\";\nimport * as HttpApiSchema from \"effect/unstable/httpapi/HttpApiSchema\";\n\nimport { AuthSessionId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\n/**\n * Declares the server's overall authentication posture.\n *\n * This is a high-level policy label that tells clients how the environment is\n * expected to be accessed, not a transport detail and not an exhaustive list\n * of every accepted credential.\n *\n * Typical usage:\n * - rendered in auth/pairing UI so the user understands what kind of\n *   environment they are connecting to\n * - used by clients to decide whether silent desktop bootstrap is expected or\n *   whether an explicit pairing flow should be shown\n *\n * Meanings:\n * - `desktop-managed-local`: local desktop-managed environment with narrow\n *   trusted bootstrap, intended to avoid login prompts on the same machine\n * - `loopback-browser`: standalone local server intended for browser pairing on\n *   the same machine\n * - `remote-reachable`: environment intended to be reached from other devices\n *   or networks, where explicit pairing/auth is expected\n * - `unsafe-no-auth`: intentionally unauthenticated mode; this is an explicit\n *   unsafe escape hatch, not a normal deployment mode\n */\nexport const ServerAuthPolicy = Schema.Literals([\n  \"desktop-managed-local\",\n  \"loopback-browser\",\n  \"remote-reachable\",\n  \"unsafe-no-auth\",\n]);\nexport type ServerAuthPolicy = typeof ServerAuthPolicy.Type;\n\n/**\n * A credential type that can be exchanged for a real authenticated session.\n *\n * Bootstrap methods are for establishing trust at the start of a connection or\n * pairing flow. They are not the long-lived credential used for ordinary\n * authenticated HTTP / WebSocket traffic after pairing succeeds.\n *\n * Current methods:\n * - `desktop-bootstrap`: a trusted local desktop handoff, used so the desktop\n *   shell can pair the renderer without a login screen\n * - `one-time-token`: a short-lived pairing token, suitable for manual pairing\n *   flows such as `/pair?token=...`\n */\nexport const ServerAuthBootstrapMethod = Schema.Literals([\"desktop-bootstrap\", \"one-time-token\"]);\nexport type ServerAuthBootstrapMethod = typeof ServerAuthBootstrapMethod.Type;\n\n/**\n * A credential type accepted for steady-state authenticated requests after a\n * client has already paired.\n *\n * These methods are used by the server-wide auth layer for privileged HTTP and\n * WebSocket access. They are distinct from bootstrap methods so clients can\n * reason clearly about \"pair first, then use session auth\".\n *\n * Current methods:\n * - `browser-session-cookie`: cookie-backed browser session, used by the web\n *   app after bootstrap/pairing\n * - `bearer-access-token`: scoped token suitable for non-cookie or\n *   non-browser clients\n * - `dpop-access-token`: scoped proof-of-possession token used by managed\n *   relay connections\n */\nexport const ServerAuthSessionMethod = Schema.Literals([\n  \"browser-session-cookie\",\n  \"bearer-access-token\",\n  \"dpop-access-token\",\n]);\nexport type ServerAuthSessionMethod = typeof ServerAuthSessionMethod.Type;\n\nexport const AuthOrchestrationReadScope = \"orchestration:read\" as const;\nexport const AuthOrchestrationOperateScope = \"orchestration:operate\" as const;\nexport const AuthTerminalOperateScope = \"terminal:operate\" as const;\nexport const AuthReviewWriteScope = \"review:write\" as const;\nexport const AuthAccessReadScope = \"access:read\" as const;\nexport const AuthAccessWriteScope = \"access:write\" as const;\nexport const AuthRelayReadScope = \"relay:read\" as const;\nexport const AuthRelayWriteScope = \"relay:write\" as const;\nexport const AuthEnvironmentScope = Schema.Literals([\n  AuthOrchestrationReadScope,\n  AuthOrchestrationOperateScope,\n  AuthTerminalOperateScope,\n  AuthReviewWriteScope,\n  AuthAccessReadScope,\n  AuthAccessWriteScope,\n  AuthRelayReadScope,\n  AuthRelayWriteScope,\n]);\nexport type AuthEnvironmentScope = typeof AuthEnvironmentScope.Type;\nexport const AuthEnvironmentScopes = Schema.Array(AuthEnvironmentScope);\nexport type AuthEnvironmentScopes = typeof AuthEnvironmentScopes.Type;\n\nexport const AuthStandardClientScopes = [\n  AuthOrchestrationReadScope,\n  AuthOrchestrationOperateScope,\n  AuthTerminalOperateScope,\n  AuthReviewWriteScope,\n  AuthRelayReadScope,\n] as const;\nexport const AuthAdministrativeScopes = [\n  ...AuthStandardClientScopes,\n  AuthAccessReadScope,\n  AuthAccessWriteScope,\n  AuthRelayWriteScope,\n] as const;\n\nexport const AuthTokenExchangeGrantType =\n  \"urn:ietf:params:oauth:grant-type:token-exchange\" as const;\nexport const AuthAccessTokenType = \"urn:ietf:params:oauth:token-type:access_token\" as const;\nexport const AuthEnvironmentBootstrapTokenType =\n  \"urn:t3:params:oauth:token-type:environment-bootstrap\" as const;\n\n/**\n * Server-advertised auth capabilities for a specific execution environment.\n *\n * Clients should treat this as the authoritative description of how that\n * environment expects to be paired and how authenticated requests should be\n * made afterward.\n *\n * Field meanings:\n * - `policy`: high-level auth posture for the environment\n * - `bootstrapMethods`: pairing/bootstrap methods the server is currently\n *   willing to accept\n * - `sessionMethods`: authenticated request/session methods the server supports\n *   once pairing is complete\n * - `sessionCookieName`: cookie name clients should expect when\n *   `browser-session-cookie` is in use\n *\n * This descriptor is intentionally capability-oriented. It lets clients choose\n * the right UX without embedding server-specific auth logic or assuming a\n * single access method.\n */\nexport const ServerAuthDescriptor = Schema.Struct({\n  policy: ServerAuthPolicy,\n  bootstrapMethods: Schema.Array(ServerAuthBootstrapMethod),\n  sessionMethods: Schema.Array(ServerAuthSessionMethod),\n  sessionCookieName: TrimmedNonEmptyString,\n});\nexport type ServerAuthDescriptor = typeof ServerAuthDescriptor.Type;\n\nexport const AuthBrowserSessionRequest = Schema.Struct({\n  credential: TrimmedNonEmptyString,\n});\nexport type AuthBrowserSessionRequest = typeof AuthBrowserSessionRequest.Type;\n\nexport const AuthBrowserSessionResult = Schema.Struct({\n  authenticated: Schema.Literal(true),\n  scopes: AuthEnvironmentScopes,\n  sessionMethod: ServerAuthSessionMethod,\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type AuthBrowserSessionResult = typeof AuthBrowserSessionResult.Type;\n\nexport const AuthClientMetadataDeviceType = Schema.Literals([\n  \"desktop\",\n  \"mobile\",\n  \"tablet\",\n  \"bot\",\n  \"unknown\",\n]);\nexport type AuthClientMetadataDeviceType = typeof AuthClientMetadataDeviceType.Type;\n\nexport const AuthClientPresentationMetadata = Schema.Struct({\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  deviceType: Schema.optionalKey(AuthClientMetadataDeviceType),\n  os: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type AuthClientPresentationMetadata = typeof AuthClientPresentationMetadata.Type;\n\nexport const AuthTokenExchangeRequest = Schema.Struct({\n  grant_type: Schema.Literal(AuthTokenExchangeGrantType),\n  subject_token: TrimmedNonEmptyString,\n  subject_token_type: Schema.Literal(AuthEnvironmentBootstrapTokenType),\n  requested_token_type: Schema.Literal(AuthAccessTokenType),\n  scope: Schema.optionalKey(TrimmedNonEmptyString),\n  client_label: Schema.optionalKey(TrimmedNonEmptyString),\n  client_device_type: Schema.optionalKey(AuthClientMetadataDeviceType),\n  client_os: Schema.optionalKey(TrimmedNonEmptyString),\n}).pipe(HttpApiSchema.asFormUrlEncoded());\nexport type AuthTokenExchangeRequest = typeof AuthTokenExchangeRequest.Type;\n\nexport const AuthAccessTokenResult = Schema.Struct({\n  access_token: TrimmedNonEmptyString,\n  issued_token_type: Schema.Literal(AuthAccessTokenType),\n  token_type: Schema.Literals([\"Bearer\", \"DPoP\"]),\n  expires_in: Schema.Number,\n  scope: TrimmedNonEmptyString,\n});\nexport type AuthAccessTokenResult = typeof AuthAccessTokenResult.Type;\n\nexport const AuthWebSocketTicketResult = Schema.Struct({\n  ticket: TrimmedNonEmptyString,\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type AuthWebSocketTicketResult = typeof AuthWebSocketTicketResult.Type;\n\nexport const AuthPairingCredentialResult = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  credential: TrimmedNonEmptyString,\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type AuthPairingCredentialResult = typeof AuthPairingCredentialResult.Type;\n\nexport const AuthPairingLink = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  credential: TrimmedNonEmptyString,\n  scopes: AuthEnvironmentScopes,\n  subject: TrimmedNonEmptyString,\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  createdAt: Schema.DateTimeUtc,\n  expiresAt: Schema.DateTimeUtc,\n});\nexport type AuthPairingLink = typeof AuthPairingLink.Type;\n\nexport const AuthClientMetadata = Schema.Struct({\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  ipAddress: Schema.optionalKey(TrimmedNonEmptyString),\n  userAgent: Schema.optionalKey(TrimmedNonEmptyString),\n  deviceType: AuthClientMetadataDeviceType,\n  os: Schema.optionalKey(TrimmedNonEmptyString),\n  browser: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type AuthClientMetadata = typeof AuthClientMetadata.Type;\n\nexport const AuthClientSession = Schema.Struct({\n  sessionId: AuthSessionId,\n  subject: TrimmedNonEmptyString,\n  scopes: AuthEnvironmentScopes,\n  method: ServerAuthSessionMethod,\n  client: AuthClientMetadata,\n  issuedAt: Schema.DateTimeUtc,\n  expiresAt: Schema.DateTimeUtc,\n  lastConnectedAt: Schema.NullOr(Schema.DateTimeUtc),\n  connected: Schema.Boolean,\n  current: Schema.Boolean,\n});\nexport type AuthClientSession = typeof AuthClientSession.Type;\n\nexport const AuthAccessSnapshot = Schema.Struct({\n  pairingLinks: Schema.Array(AuthPairingLink),\n  clientSessions: Schema.Array(AuthClientSession),\n});\nexport type AuthAccessSnapshot = typeof AuthAccessSnapshot.Type;\n\nexport const AuthAccessStreamSnapshotEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"snapshot\"),\n  payload: AuthAccessSnapshot,\n});\nexport type AuthAccessStreamSnapshotEvent = typeof AuthAccessStreamSnapshotEvent.Type;\n\nexport const AuthAccessStreamPairingLinkUpsertedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"pairingLinkUpserted\"),\n  payload: AuthPairingLink,\n});\nexport type AuthAccessStreamPairingLinkUpsertedEvent =\n  typeof AuthAccessStreamPairingLinkUpsertedEvent.Type;\n\nexport const AuthAccessStreamPairingLinkRemovedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"pairingLinkRemoved\"),\n  payload: Schema.Struct({\n    id: TrimmedNonEmptyString,\n  }),\n});\nexport type AuthAccessStreamPairingLinkRemovedEvent =\n  typeof AuthAccessStreamPairingLinkRemovedEvent.Type;\n\nexport class AuthAccessStreamError extends Schema.TaggedErrorClass<AuthAccessStreamError>()(\n  \"AuthAccessStreamError\",\n  {\n    message: Schema.String,\n  },\n) {}\n\nexport class EnvironmentAuthorizationError extends Schema.TaggedErrorClass<EnvironmentAuthorizationError>()(\n  \"EnvironmentAuthorizationError\",\n  {\n    message: Schema.String,\n    requiredScope: AuthEnvironmentScope,\n  },\n) {}\n\nexport const AuthAccessStreamClientUpsertedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"clientUpserted\"),\n  payload: AuthClientSession,\n});\nexport type AuthAccessStreamClientUpsertedEvent = typeof AuthAccessStreamClientUpsertedEvent.Type;\n\nexport const AuthAccessStreamClientRemovedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  revision: Schema.Number,\n  type: Schema.Literal(\"clientRemoved\"),\n  payload: Schema.Struct({\n    sessionId: AuthSessionId,\n  }),\n});\nexport type AuthAccessStreamClientRemovedEvent = typeof AuthAccessStreamClientRemovedEvent.Type;\n\nexport const AuthAccessStreamEvent = Schema.Union([\n  AuthAccessStreamSnapshotEvent,\n  AuthAccessStreamPairingLinkUpsertedEvent,\n  AuthAccessStreamPairingLinkRemovedEvent,\n  AuthAccessStreamClientUpsertedEvent,\n  AuthAccessStreamClientRemovedEvent,\n]);\nexport type AuthAccessStreamEvent = typeof AuthAccessStreamEvent.Type;\n\nexport const AuthRevokePairingLinkInput = Schema.Struct({\n  id: TrimmedNonEmptyString,\n});\nexport type AuthRevokePairingLinkInput = typeof AuthRevokePairingLinkInput.Type;\n\nexport const AuthRevokeClientSessionInput = Schema.Struct({\n  sessionId: AuthSessionId,\n});\nexport type AuthRevokeClientSessionInput = typeof AuthRevokeClientSessionInput.Type;\n\nexport const AuthCreatePairingCredentialInput = Schema.Struct({\n  label: Schema.optionalKey(TrimmedNonEmptyString),\n  scopes: Schema.optionalKey(AuthEnvironmentScopes),\n});\nexport type AuthCreatePairingCredentialInput = typeof AuthCreatePairingCredentialInput.Type;\n\nexport const AuthSessionState = Schema.Struct({\n  authenticated: Schema.Boolean,\n  auth: ServerAuthDescriptor,\n  scopes: Schema.optionalKey(AuthEnvironmentScopes),\n  sessionMethod: Schema.optionalKey(ServerAuthSessionMethod),\n  expiresAt: Schema.optionalKey(Schema.DateTimeUtc),\n});\nexport type AuthSessionState = typeof AuthSessionState.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { EnvironmentId, ProjectId, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const ExecutionEnvironmentPlatformOs = Schema.Literals([\n  \"darwin\",\n  \"linux\",\n  \"windows\",\n  \"unknown\",\n]);\nexport type ExecutionEnvironmentPlatformOs = typeof ExecutionEnvironmentPlatformOs.Type;\n\nexport const ExecutionEnvironmentPlatformArch = Schema.Literals([\"arm64\", \"x64\", \"other\"]);\nexport type ExecutionEnvironmentPlatformArch = typeof ExecutionEnvironmentPlatformArch.Type;\n\nexport const ExecutionEnvironmentPlatform = Schema.Struct({\n  os: ExecutionEnvironmentPlatformOs,\n  arch: ExecutionEnvironmentPlatformArch,\n});\nexport type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.Type;\n\n/** How a server can replace itself with another version when asked over RPC.\n    New servers only advertise the stable launcher-backed \"boot-service\" path;\n    \"respawn\" remains decodable for compatibility with older servers. */\nexport const ServerSelfUpdateMethod = Schema.Literals([\"boot-service\", \"respawn\"]);\nexport type ServerSelfUpdateMethod = typeof ServerSelfUpdateMethod.Type;\n\n/** What update path a client should offer for a server: one of the RPC\n    self-update methods above, or \"desktop-managed\" when the backend's\n    version belongs to the Synaptic Code desktop app supervising it. Updating the\n    app on that machine is the only way to update the server. */\nexport const ServerSelfUpdateCapability = Schema.Literals([\n  \"boot-service\",\n  \"respawn\",\n  \"desktop-managed\",\n]);\nexport type ServerSelfUpdateCapability = typeof ServerSelfUpdateCapability.Type;\n\nexport const ExecutionEnvironmentCapabilities = Schema.Struct({\n  repositoryIdentity: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  connectionProbe: Schema.optionalKey(Schema.Boolean),\n  /** Server understands thread.settle / thread.unsettle commands. Absent on\n      pre-settlement servers, so clients treat missing as unsupported and\n      never send the commands under version skew. */\n  threadSettlement: Schema.optionalKey(Schema.Boolean),\n  /** Server understands thread.snooze / thread.unsnooze commands. Same\n      version-skew contract as threadSettlement. */\n  threadSnooze: Schema.optionalKey(Schema.Boolean),\n  /** Server understands thread.pin / thread.unpin commands. Same\n      version-skew contract as threadSettlement. */\n  threadPinning: Schema.optionalKey(Schema.Boolean),\n  /** Server understands thread.pin.reorder (and orderKey on thread.pin).\n      Same version-skew contract as threadSettlement. */\n  threadPinReorder: Schema.optionalKey(Schema.Boolean),\n  /** Server understands regenerateTitle on thread.meta.update. Absent on\n      older servers, so clients hide the action instead of sending it. */\n  threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),\n  /** The update path clients should offer for this server. Absent on\n      servers that must be relaunched manually (dev checkouts, Windows\n      foreground runs, pre-update servers). */\n  serverSelfUpdate: Schema.optionalKey(ServerSelfUpdateCapability),\n  /** Server can stream self-update progress before acknowledging the\n      restart. Clients fall back to server.updateServer when absent. */\n  serverSelfUpdateProgress: Schema.optionalKey(Schema.Boolean),\n});\nexport type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;\n\nexport const ExecutionEnvironmentDescriptor = Schema.Struct({\n  environmentId: EnvironmentId,\n  label: TrimmedNonEmptyString,\n  platform: ExecutionEnvironmentPlatform,\n  serverVersion: TrimmedNonEmptyString,\n  capabilities: ExecutionEnvironmentCapabilities,\n});\nexport type ExecutionEnvironmentDescriptor = typeof ExecutionEnvironmentDescriptor.Type;\n\nexport const EnvironmentConnectionState = Schema.Literals([\n  \"connecting\",\n  \"connected\",\n  \"disconnected\",\n  \"error\",\n]);\nexport type EnvironmentConnectionState = typeof EnvironmentConnectionState.Type;\n\nexport const RepositoryIdentityLocator = Schema.Struct({\n  source: Schema.Literal(\"git-remote\"),\n  remoteName: TrimmedNonEmptyString,\n  remoteUrl: TrimmedNonEmptyString,\n});\nexport type RepositoryIdentityLocator = typeof RepositoryIdentityLocator.Type;\n\nexport const RepositoryIdentity = Schema.Struct({\n  canonicalKey: TrimmedNonEmptyString,\n  locator: RepositoryIdentityLocator,\n  rootPath: Schema.optionalKey(TrimmedNonEmptyString),\n  displayName: Schema.optionalKey(TrimmedNonEmptyString),\n  provider: Schema.optionalKey(TrimmedNonEmptyString),\n  owner: Schema.optionalKey(TrimmedNonEmptyString),\n  name: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type RepositoryIdentity = typeof RepositoryIdentity.Type;\n\nexport const ScopedProjectRef = Schema.Struct({\n  environmentId: EnvironmentId,\n  projectId: ProjectId,\n});\nexport type ScopedProjectRef = typeof ScopedProjectRef.Type;\n\nexport const ScopedThreadRef = Schema.Struct({\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n});\nexport type ScopedThreadRef = typeof ScopedThreadRef.Type;\n\nexport const ScopedThreadSessionRef = Schema.Struct({\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n});\nexport type ScopedThreadSessionRef = typeof ScopedThreadSessionRef.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { ProviderDriverKind } from \"./providerInstance.ts\";\n\nexport const ProviderOptionDescriptorType = Schema.Literals([\"select\", \"boolean\"]);\nexport type ProviderOptionDescriptorType = typeof ProviderOptionDescriptorType.Type;\n\nexport const ProviderOptionChoice = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  description: Schema.optional(TrimmedNonEmptyString),\n  isDefault: Schema.optional(Schema.Boolean),\n});\nexport type ProviderOptionChoice = typeof ProviderOptionChoice.Type;\n\nconst ProviderOptionDescriptorBase = {\n  id: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  description: Schema.optional(TrimmedNonEmptyString),\n} as const;\n\nexport const SelectProviderOptionDescriptor = Schema.Struct({\n  ...ProviderOptionDescriptorBase,\n  type: Schema.Literal(\"select\"),\n  options: Schema.Array(ProviderOptionChoice),\n  currentValue: Schema.optional(TrimmedNonEmptyString),\n  promptInjectedValues: Schema.optional(Schema.Array(TrimmedNonEmptyString)),\n});\nexport type SelectProviderOptionDescriptor = typeof SelectProviderOptionDescriptor.Type;\n\nexport const BooleanProviderOptionDescriptor = Schema.Struct({\n  ...ProviderOptionDescriptorBase,\n  type: Schema.Literal(\"boolean\"),\n  currentValue: Schema.optional(Schema.Boolean),\n});\nexport type BooleanProviderOptionDescriptor = typeof BooleanProviderOptionDescriptor.Type;\n\nexport const ProviderOptionDescriptor = Schema.Union([\n  SelectProviderOptionDescriptor,\n  BooleanProviderOptionDescriptor,\n]);\nexport type ProviderOptionDescriptor = typeof ProviderOptionDescriptor.Type;\n\nexport const ProviderOptionSelectionValue = Schema.Union([TrimmedNonEmptyString, Schema.Boolean]);\nexport type ProviderOptionSelectionValue = typeof ProviderOptionSelectionValue.Type;\n\nexport const ProviderOptionSelection = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  value: ProviderOptionSelectionValue,\n});\nexport type ProviderOptionSelection = typeof ProviderOptionSelection.Type;\n\n/**\n * Legacy on-disk shape for provider option selections, kept readable by the\n * decoder so we can tolerate stored data written before the v3 array shape.\n *\n * Persisted historically as `{ effort: \"max\", fastMode: true, ... }` inside\n * `modelSelection.options`. Migration 026 rewrites stored rows to the\n * canonical array shape, but we still see the legacy form in:\n *   - `settings.json` files from older client builds,\n *   - SQLite databases that have not yet run migration 026,\n *   - any future regression that re-introduces the legacy shape.\n */\nconst LegacyProviderOptionSelectionsObject = Schema.Record(Schema.String, Schema.Unknown);\n\nconst ProviderOptionSelectionsFromLegacyObject = LegacyProviderOptionSelectionsObject.pipe(\n  Schema.decodeTo(\n    Schema.Array(ProviderOptionSelection),\n    SchemaTransformation.transformOrFail({\n      decode: (record) => Effect.succeed(coerceLegacyOptionsObjectToArray(record)),\n      encode: (selections) => Effect.succeed(canonicalSelectionsToLegacyObject(selections)),\n    }),\n  ),\n);\n\n/**\n * Schema for the `options` field of every `ModelSelection` variant.\n *\n * Accepts both:\n *   - the canonical array shape `Array<{ id, value }>` (preferred), and\n *   - the legacy object shape `Record<string, string | boolean | …>` from\n *     pre-migration data.\n *\n * Always normalizes to the canonical array on decode and re-encodes as the\n * canonical array, so any legacy storage gets cleaned up the next time the\n * containing record is written back.\n */\nexport const ProviderOptionSelections = Schema.Union([\n  Schema.Array(ProviderOptionSelection),\n  ProviderOptionSelectionsFromLegacyObject,\n]);\nexport type ProviderOptionSelections = typeof ProviderOptionSelections.Type;\n\nfunction coerceLegacyOptionsObjectToArray(\n  record: Record<string, unknown>,\n): ReadonlyArray<ProviderOptionSelection> {\n  const entries: Array<ProviderOptionSelection> = [];\n  for (const [rawKey, rawValue] of Object.entries(record)) {\n    const id = typeof rawKey === \"string\" ? rawKey.trim() : \"\";\n    if (id.length === 0) continue;\n    if (typeof rawValue === \"string\") {\n      const trimmed = rawValue.trim();\n      if (trimmed.length > 0) entries.push({ id, value: trimmed });\n    } else if (typeof rawValue === \"boolean\") {\n      entries.push({ id, value: rawValue });\n    }\n    // Drop anything else (numbers, null, nested objects/arrays) to match the\n    // permissive normalization performed by migration 026.\n  }\n  return entries;\n}\n\nfunction canonicalSelectionsToLegacyObject(\n  selections: ReadonlyArray<ProviderOptionSelection>,\n): Record<string, string | boolean> {\n  const out: Record<string, string | boolean> = {};\n  for (const { id, value } of selections) {\n    out[id] = value;\n  }\n  return out;\n}\n\nexport const ModelCapabilities = Schema.Struct({\n  optionDescriptors: Schema.optional(Schema.Array(ProviderOptionDescriptor)),\n});\nexport type ModelCapabilities = typeof ModelCapabilities.Type;\n\nconst CODEX_DRIVER_KIND = ProviderDriverKind.make(\"codex\");\nconst CLAUDE_DRIVER_KIND = ProviderDriverKind.make(\"claudeAgent\");\nconst CURSOR_DRIVER_KIND = ProviderDriverKind.make(\"cursor\");\nconst GROK_DRIVER_KIND = ProviderDriverKind.make(\"grok\");\nconst OPENCODE_DRIVER_KIND = ProviderDriverKind.make(\"opencode\");\n\nexport const DEFAULT_MODEL = \"gpt-5.6-sol\";\n\n/**\n * Codex default-model preference, most preferred first. The provider snapshot\n * marks the first of these present in the live `model/list` response as\n * default; when none are available, Codex's own `isDefault` flag wins.\n */\nexport const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [\n  \"gpt-5.6-sol\",\n  \"gpt-5.6-terra\",\n];\nexport const DEFAULT_TEXT_GENERATION_MODEL = \"gpt-5.6-luna\";\nexport const DEFAULT_TEXT_GENERATION_REASONING_EFFORT = \"low\";\n\nexport const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {\n  [CODEX_DRIVER_KIND]: DEFAULT_MODEL,\n  [CLAUDE_DRIVER_KIND]: \"claude-sonnet-5\",\n  [CURSOR_DRIVER_KIND]: \"auto\",\n  [GROK_DRIVER_KIND]: \"grok-build\",\n  [OPENCODE_DRIVER_KIND]: \"openai/gpt-5\",\n};\n\n/** Per-provider text generation model defaults. */\nexport const DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER: Partial<\n  Record<ProviderDriverKind, string>\n> = {\n  [CODEX_DRIVER_KIND]: DEFAULT_TEXT_GENERATION_MODEL,\n  [CLAUDE_DRIVER_KIND]: \"claude-haiku-4-5\",\n  [CURSOR_DRIVER_KIND]: \"composer-2\",\n  [OPENCODE_DRIVER_KIND]: \"openai/gpt-5\",\n};\n\nexport const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<\n  Record<ProviderDriverKind, Record<string, string>>\n> = {\n  [CODEX_DRIVER_KIND]: {\n    \"gpt-5-codex\": \"gpt-5.4\",\n    \"5.4\": \"gpt-5.4\",\n    \"5.3\": \"gpt-5.3-codex\",\n    \"gpt-5.3\": \"gpt-5.3-codex\",\n    \"5.3-spark\": \"gpt-5.3-codex-spark\",\n    \"gpt-5.3-spark\": \"gpt-5.3-codex-spark\",\n  },\n  [CLAUDE_DRIVER_KIND]: {\n    opus: \"claude-opus-5\",\n    \"opus-5\": \"claude-opus-5\",\n    \"claude-opus-5.0\": \"claude-opus-5\",\n    \"claude-opus-5-0\": \"claude-opus-5\",\n    \"opus-4.8\": \"claude-opus-4-8\",\n    \"claude-opus-4.8\": \"claude-opus-4-8\",\n    \"opus-4.7\": \"claude-opus-4-7\",\n    \"claude-opus-4.7\": \"claude-opus-4-7\",\n    \"opus-4.6\": \"claude-opus-4-6\",\n    \"claude-opus-4.6\": \"claude-opus-4-6\",\n    \"claude-opus-4-6-20251117\": \"claude-opus-4-6\",\n    sonnet: \"claude-sonnet-5\",\n    \"sonnet-5\": \"claude-sonnet-5\",\n    \"claude-sonnet-5.0\": \"claude-sonnet-5\",\n    \"claude-sonnet-5-0\": \"claude-sonnet-5\",\n    \"sonnet-4.6\": \"claude-sonnet-4-6\",\n    \"claude-sonnet-4.6\": \"claude-sonnet-4-6\",\n    \"claude-sonnet-4-6-20251117\": \"claude-sonnet-4-6\",\n    haiku: \"claude-haiku-4-5\",\n    \"haiku-4.5\": \"claude-haiku-4-5\",\n    \"claude-haiku-4.5\": \"claude-haiku-4-5\",\n    \"claude-haiku-4-5-20251001\": \"claude-haiku-4-5\",\n  },\n  [CURSOR_DRIVER_KIND]: {\n    composer: \"composer-2\",\n    \"composer-1.5\": \"composer-1.5\",\n    \"composer-1\": \"composer-1.5\",\n    \"opus-4.6-thinking\": \"claude-opus-4-6\",\n    \"opus-4.6\": \"claude-opus-4-6\",\n    \"sonnet-4.6-thinking\": \"claude-sonnet-4-6\",\n    \"sonnet-4.6\": \"claude-sonnet-4-6\",\n    \"opus-4.5-thinking\": \"claude-opus-4-5\",\n    \"opus-4.5\": \"claude-opus-4-5\",\n  },\n  [OPENCODE_DRIVER_KIND]: {},\n};\n\n// ── Provider display names ────────────────────────────────────────────\n\nexport const PROVIDER_DISPLAY_NAMES: Partial<Record<ProviderDriverKind, string>> = {\n  [CODEX_DRIVER_KIND]: \"Codex\",\n  [CLAUDE_DRIVER_KIND]: \"Claude\",\n  [CURSOR_DRIVER_KIND]: \"Cursor\",\n  [GROK_DRIVER_KIND]: \"Grok\",\n  [OPENCODE_DRIVER_KIND]: \"OpenCode\",\n};\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport * as Struct from \"effect/Struct\";\nimport { ProviderOptionSelections } from \"./model.ts\";\nimport { RepositoryIdentity } from \"./environment.ts\";\nimport {\n  ApprovalRequestId,\n  CheckpointRef,\n  CommandId,\n  EventId,\n  IsoDateTime,\n  MessageId,\n  NonNegativeInt,\n  PositiveInt,\n  ProjectId,\n  ProviderItemId,\n  ThreadId,\n  TrimmedNonEmptyString,\n  TrimmedString,\n  TurnId,\n} from \"./baseSchemas.ts\";\nimport { ProviderInstanceId } from \"./providerInstance.ts\";\n\nexport const ORCHESTRATION_WS_METHODS = {\n  dispatchCommand: \"orchestration.dispatchCommand\",\n  getWorkflowScript: \"orchestration.getWorkflowScript\",\n  getTurnDiff: \"orchestration.getTurnDiff\",\n  getFullThreadDiff: \"orchestration.getFullThreadDiff\",\n  searchThreads: \"orchestration.searchThreads\",\n  getArchivedShellSnapshot: \"orchestration.getArchivedShellSnapshot\",\n  subscribeShell: \"orchestration.subscribeShell\",\n  subscribeThread: \"orchestration.subscribeThread\",\n} as const;\n\nexport const ProviderApprovalPolicy = Schema.Literals([\n  \"untrusted\",\n  \"on-failure\",\n  \"on-request\",\n  \"never\",\n]);\nexport type ProviderApprovalPolicy = typeof ProviderApprovalPolicy.Type;\nexport const ProviderSandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\nexport type ProviderSandboxMode = typeof ProviderSandboxMode.Type;\n\n/**\n * `ModelSelection` — selection of a model on a configured provider instance.\n *\n * The routing key is `instanceId` (a user-defined slug identifying one\n * configured provider instance). Drivers, credentials, working-directory\n * bindings, and any other per-instance state are recovered from the\n * runtime registry via the instance id.\n *\n * Wire legacy: persisted selections produced before the driver/instance\n * split carried a `provider: <driver-id>` field instead. The schema absorbs\n * that shape via a pre-decoding transform — `{provider, model}` is promoted\n * to `{instanceId: defaultInstanceIdForDriver(provider), model}`. No\n * post-decode compatibility code lives in the runtime; the transform is the\n * only compat surface.\n */\nconst ModelSelectionWire = Schema.Struct({\n  instanceId: ProviderInstanceId,\n  model: TrimmedNonEmptyString,\n  options: Schema.optionalKey(ProviderOptionSelections),\n});\n\n// Source shape for persisted legacy payloads. Fields are typed as\n// `Schema.Unknown` so malformed drafts still make it into the transform and\n// fail validation through the target schema (with proper error messages)\n// rather than at the source-struct layer where the error is less actionable.\nconst ModelSelectionSource = Schema.Struct({\n  provider: Schema.optional(Schema.Unknown),\n  instanceId: Schema.optional(Schema.Unknown),\n  model: Schema.Unknown,\n  options: Schema.optional(Schema.Unknown),\n});\n\nexport const ModelSelection = ModelSelectionSource.pipe(\n  Schema.decodeTo(\n    ModelSelectionWire,\n    SchemaTransformation.transformOrFail({\n      decode: (raw) => {\n        // Resolve the routing key: prefer an explicit `instanceId`; fall\n        // back to promoting the legacy `provider` slug (the canonical\n        // `defaultInstanceIdForDriver` mapping) so persisted rollout-era\n        // payloads decode without data loss. The target schema brands the\n        // string as `ProviderInstanceId`.\n        const instanceIdSource =\n          raw.instanceId !== undefined\n            ? raw.instanceId\n            : typeof raw.provider === \"string\"\n              ? raw.provider\n              : undefined;\n        const base: Record<string, unknown> = {\n          instanceId: instanceIdSource,\n          model: raw.model,\n        };\n        if (raw.options !== undefined) base.options = raw.options;\n        return Effect.succeed(base as typeof ModelSelectionWire.Encoded);\n      },\n      encode: (value) => {\n        const base: Record<string, unknown> = {\n          model: value.model,\n          instanceId: value.instanceId,\n        };\n        if (value.options !== undefined) base.options = value.options;\n        return Effect.succeed(base as typeof ModelSelectionSource.Encoded);\n      },\n    }),\n  ),\n);\nexport type ModelSelection = typeof ModelSelection.Type;\n\nexport const RuntimeMode = Schema.Literals([\n  \"approval-required\",\n  \"auto-accept-edits\",\n  \"auto\",\n  \"full-access\",\n]);\nexport type RuntimeMode = typeof RuntimeMode.Type;\nexport const DEFAULT_RUNTIME_MODE: RuntimeMode = \"full-access\";\nexport const ProviderInteractionMode = Schema.Literals([\"default\", \"plan\"]);\nexport type ProviderInteractionMode = typeof ProviderInteractionMode.Type;\nexport const DEFAULT_PROVIDER_INTERACTION_MODE: ProviderInteractionMode = \"default\";\nexport const ProviderRequestKind = Schema.Literals([\"command\", \"file-read\", \"file-change\"]);\nexport type ProviderRequestKind = typeof ProviderRequestKind.Type;\nexport const AssistantDeliveryMode = Schema.Literals([\"buffered\", \"streaming\"]);\nexport type AssistantDeliveryMode = typeof AssistantDeliveryMode.Type;\nexport const ProviderApprovalDecision = Schema.Literals([\n  \"accept\",\n  \"acceptForSession\",\n  \"decline\",\n  \"cancel\",\n]);\nexport type ProviderApprovalDecision = typeof ProviderApprovalDecision.Type;\nexport const ProviderUserInputAnswers = Schema.Record(Schema.String, Schema.Unknown);\nexport type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type;\n\nexport const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;\nexport const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;\nexport const PROVIDER_SEND_TURN_MAX_IMAGE_BYTES = 10 * 1024 * 1024;\nconst PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS = 14_000_000;\nconst CHAT_ATTACHMENT_ID_MAX_CHARS = 128;\n// Correlation id is command id by design in this model.\nexport const CorrelationId = CommandId;\nexport type CorrelationId = typeof CorrelationId.Type;\n\nconst ChatAttachmentId = TrimmedNonEmptyString.check(\n  Schema.isMaxLength(CHAT_ATTACHMENT_ID_MAX_CHARS),\n  Schema.isPattern(/^[a-z0-9_-]+$/i),\n);\nexport type ChatAttachmentId = typeof ChatAttachmentId.Type;\n\nexport const ChatImageAttachment = Schema.Struct({\n  type: Schema.Literal(\"image\"),\n  id: ChatAttachmentId,\n  name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),\n  mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\\//i)),\n  sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),\n});\nexport type ChatImageAttachment = typeof ChatImageAttachment.Type;\n\nconst UploadChatImageAttachment = Schema.Struct({\n  type: Schema.Literal(\"image\"),\n  name: TrimmedNonEmptyString.check(Schema.isMaxLength(255)),\n  mimeType: TrimmedNonEmptyString.check(Schema.isMaxLength(100), Schema.isPattern(/^image\\//i)),\n  sizeBytes: NonNegativeInt.check(Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES)),\n  dataUrl: TrimmedNonEmptyString.check(\n    Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_IMAGE_DATA_URL_CHARS),\n  ),\n});\nexport type UploadChatImageAttachment = typeof UploadChatImageAttachment.Type;\n\nexport const ChatAttachment = Schema.Union([ChatImageAttachment]);\nexport type ChatAttachment = typeof ChatAttachment.Type;\nconst UploadChatAttachment = Schema.Union([UploadChatImageAttachment]);\nexport type UploadChatAttachment = typeof UploadChatAttachment.Type;\n\nexport const ProjectScriptIcon = Schema.Literals([\n  \"play\",\n  \"test\",\n  \"lint\",\n  \"configure\",\n  \"build\",\n  \"debug\",\n]);\nexport type ProjectScriptIcon = typeof ProjectScriptIcon.Type;\n\nexport const ProjectScript = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  name: TrimmedNonEmptyString,\n  command: TrimmedNonEmptyString,\n  icon: ProjectScriptIcon,\n  runOnWorktreeCreate: Schema.Boolean,\n  /**\n   * URL to open in the in-app browser preview when this script runs (or\n   * when the user explicitly requests a preview). Optional; only honored on\n   * the desktop build.\n   */\n  previewUrl: Schema.optional(TrimmedNonEmptyString),\n  /**\n   * When true, automatically open the preview panel pointed at `previewUrl`\n   * the moment this script starts. Ignored without `previewUrl` or on web.\n   */\n  autoOpenPreview: Schema.optional(Schema.Boolean),\n});\nexport type ProjectScript = typeof ProjectScript.Type;\n\nexport const OrchestrationProject = Schema.Struct({\n  id: ProjectId,\n  title: TrimmedNonEmptyString,\n  workspaceRoot: TrimmedNonEmptyString,\n  repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),\n  defaultModelSelection: Schema.NullOr(ModelSelection),\n  scripts: Schema.Array(ProjectScript),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  deletedAt: Schema.NullOr(IsoDateTime),\n});\nexport type OrchestrationProject = typeof OrchestrationProject.Type;\n\nexport const OrchestrationMessageRole = Schema.Literals([\"user\", \"assistant\", \"system\"]);\nexport type OrchestrationMessageRole = typeof OrchestrationMessageRole.Type;\n\nexport const OrchestrationMessage = Schema.Struct({\n  id: MessageId,\n  role: OrchestrationMessageRole,\n  text: Schema.String,\n  attachments: Schema.optional(Schema.Array(ChatAttachment)),\n  turnId: Schema.NullOr(TurnId),\n  streaming: Schema.Boolean,\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationMessage = typeof OrchestrationMessage.Type;\n\nexport const OrchestrationProposedPlanId = TrimmedNonEmptyString;\nexport type OrchestrationProposedPlanId = typeof OrchestrationProposedPlanId.Type;\n\nexport const OrchestrationProposedPlan = Schema.Struct({\n  id: OrchestrationProposedPlanId,\n  turnId: Schema.NullOr(TurnId),\n  planMarkdown: TrimmedNonEmptyString,\n  implementedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  implementationThreadId: Schema.NullOr(ThreadId).pipe(\n    Schema.withDecodingDefault(Effect.succeed(null)),\n  ),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationProposedPlan = typeof OrchestrationProposedPlan.Type;\n\nconst SourceProposedPlanReference = Schema.Struct({\n  threadId: ThreadId,\n  planId: OrchestrationProposedPlanId,\n});\n\nexport const OrchestrationSessionStatus = Schema.Literals([\n  \"idle\",\n  \"starting\",\n  \"running\",\n  \"ready\",\n  \"interrupted\",\n  \"stopped\",\n  \"error\",\n]);\nexport type OrchestrationSessionStatus = typeof OrchestrationSessionStatus.Type;\n\nexport const OrchestrationSession = Schema.Struct({\n  threadId: ThreadId,\n  status: OrchestrationSessionStatus,\n  providerName: Schema.NullOr(TrimmedNonEmptyString),\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),\n  activeTurnId: Schema.NullOr(TurnId),\n  lastError: Schema.NullOr(TrimmedNonEmptyString),\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationSession = typeof OrchestrationSession.Type;\n\nexport const OrchestrationCheckpointFile = Schema.Struct({\n  path: TrimmedNonEmptyString,\n  kind: TrimmedNonEmptyString,\n  additions: NonNegativeInt,\n  deletions: NonNegativeInt,\n});\nexport type OrchestrationCheckpointFile = typeof OrchestrationCheckpointFile.Type;\n\nexport const OrchestrationCheckpointStatus = Schema.Literals([\"ready\", \"missing\", \"error\"]);\nexport type OrchestrationCheckpointStatus = typeof OrchestrationCheckpointStatus.Type;\n\nexport const OrchestrationCheckpointSummary = Schema.Struct({\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.NullOr(MessageId),\n  completedAt: IsoDateTime,\n});\nexport type OrchestrationCheckpointSummary = typeof OrchestrationCheckpointSummary.Type;\n\nexport const OrchestrationThreadActivityTone = Schema.Literals([\n  \"info\",\n  \"tool\",\n  \"approval\",\n  \"error\",\n]);\nexport type OrchestrationThreadActivityTone = typeof OrchestrationThreadActivityTone.Type;\n\nexport const OrchestrationThreadActivity = Schema.Struct({\n  id: EventId,\n  tone: OrchestrationThreadActivityTone,\n  kind: TrimmedNonEmptyString,\n  summary: TrimmedNonEmptyString,\n  payload: Schema.Unknown,\n  turnId: Schema.NullOr(TurnId),\n  sequence: Schema.optional(NonNegativeInt),\n  createdAt: IsoDateTime,\n});\nexport type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;\n\nconst OrchestrationLatestTurnState = Schema.Literals([\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"error\",\n]);\nexport type OrchestrationLatestTurnState = typeof OrchestrationLatestTurnState.Type;\n\nexport const OrchestrationLatestTurn = Schema.Struct({\n  turnId: TurnId,\n  state: OrchestrationLatestTurnState,\n  requestedAt: IsoDateTime,\n  startedAt: Schema.NullOr(IsoDateTime),\n  completedAt: Schema.NullOr(IsoDateTime),\n  assistantMessageId: Schema.NullOr(MessageId),\n  sourceProposedPlan: Schema.optional(SourceProposedPlanReference),\n});\nexport type OrchestrationLatestTurn = typeof OrchestrationLatestTurn.Type;\n\nexport const ThreadTitleRegeneration = Schema.Struct({\n  requestId: CommandId,\n  startedAt: IsoDateTime,\n});\nexport type ThreadTitleRegeneration = typeof ThreadTitleRegeneration.Type;\n\nexport const OrchestrationThread = Schema.Struct({\n  id: ThreadId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  latestTurn: Schema.NullOr(OrchestrationLatestTurn),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  settledOverride: Schema.NullOr(Schema.Literals([\"settled\", \"active\"])).pipe(\n    Schema.withDecodingDefault(Effect.succeed(null)),\n  ),\n  settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  // Snooze is an overlay on the active lifecycle, not a fourth destination:\n  // a snoozed thread stays \"active\" in the model and is only suppressed from\n  // the inbox until snoozedUntil passes (or the thread raises its hand).\n  // Optional so payloads from pre-snooze servers still decode.\n  snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),\n  snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  // A pin overrides the settled/snoozed lifecycle: while pinnedAt is set the\n  // thread renders in the pinned block and never classifies into a shelf.\n  // Optional so payloads from pre-pinning servers still decode.\n  pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  // Fractional index for user-arranged pinned order. Keyed threads sort by\n  // string comparison ahead of keyless ones (which keep creation order), so\n  // servers never need each other's threads to agree on the merged list.\n  // Optional so payloads from pre-reorder servers still decode.\n  pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  // Pending-only state. Optional so older servers remain compatible.\n  titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),\n  deletedAt: Schema.NullOr(IsoDateTime),\n  messages: Schema.Array(OrchestrationMessage),\n  proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(\n    Schema.withDecodingDefault(Effect.succeed([])),\n  ),\n  activities: Schema.Array(OrchestrationThreadActivity),\n  checkpoints: Schema.Array(OrchestrationCheckpointSummary),\n  session: Schema.NullOr(OrchestrationSession),\n});\nexport type OrchestrationThread = typeof OrchestrationThread.Type;\n\nexport const OrchestrationReadModel = Schema.Struct({\n  snapshotSequence: NonNegativeInt,\n  projects: Schema.Array(OrchestrationProject),\n  threads: Schema.Array(OrchestrationThread),\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationReadModel = typeof OrchestrationReadModel.Type;\n\nexport const OrchestrationProjectShell = Schema.Struct({\n  id: ProjectId,\n  title: TrimmedNonEmptyString,\n  workspaceRoot: TrimmedNonEmptyString,\n  repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),\n  defaultModelSelection: Schema.NullOr(ModelSelection),\n  scripts: Schema.Array(ProjectScript),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationProjectShell = typeof OrchestrationProjectShell.Type;\n\nexport const OrchestrationThreadShell = Schema.Struct({\n  id: ThreadId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  latestTurn: Schema.NullOr(OrchestrationLatestTurn),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  settledOverride: Schema.NullOr(Schema.Literals([\"settled\", \"active\"])).pipe(\n    Schema.withDecodingDefault(Effect.succeed(null)),\n  ),\n  settledAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(Effect.succeed(null))),\n  snoozedUntil: Schema.optional(Schema.NullOr(IsoDateTime)),\n  snoozedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),\n  session: Schema.NullOr(OrchestrationSession),\n  latestUserMessageAt: Schema.NullOr(IsoDateTime),\n  hasPendingApprovals: Schema.Boolean,\n  hasPendingUserInput: Schema.Boolean,\n  hasActionableProposedPlan: Schema.Boolean,\n  /**\n   * Native background work alive after the turn settles: \"working\" while\n   * subagents/workflows run, \"monitoring\" when watch loops are the only\n   * live work. Optional so old servers/clients interop; absent = none.\n   */\n  backgroundLiveness: Schema.optional(Schema.NullOr(Schema.Literals([\"working\", \"monitoring\"]))),\n  /**\n   * Current plan step while a turn runs, for the Working indicators\n   * (sidebar row, in-chat working line). Cleared when the turn settles —\n   * never persists as stale UI. Optional so old servers/clients interop.\n   */\n  planProgress: Schema.optional(\n    Schema.NullOr(\n      Schema.Struct({\n        step: TrimmedNonEmptyString,\n        completedSteps: NonNegativeInt,\n        totalSteps: NonNegativeInt,\n      }),\n    ),\n  ),\n});\nexport type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type;\n\nexport const OrchestrationShellSnapshot = Schema.Struct({\n  snapshotSequence: NonNegativeInt,\n  projects: Schema.Array(OrchestrationProjectShell),\n  threads: Schema.Array(OrchestrationThreadShell),\n  updatedAt: IsoDateTime,\n});\nexport type OrchestrationShellSnapshot = typeof OrchestrationShellSnapshot.Type;\n\nexport const OrchestrationShellStreamEvent = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"project-upserted\"),\n    sequence: NonNegativeInt,\n    project: OrchestrationProjectShell,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"project-removed\"),\n    sequence: NonNegativeInt,\n    projectId: ProjectId,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"thread-upserted\"),\n    sequence: NonNegativeInt,\n    thread: OrchestrationThreadShell,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"thread-removed\"),\n    sequence: NonNegativeInt,\n    threadId: ThreadId,\n  }),\n]);\nexport type OrchestrationShellStreamEvent = typeof OrchestrationShellStreamEvent.Type;\n\nexport const OrchestrationShellStreamItem = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"synchronized\"),\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"snapshot\"),\n    snapshot: OrchestrationShellSnapshot,\n  }),\n  OrchestrationShellStreamEvent,\n]);\nexport type OrchestrationShellStreamItem = typeof OrchestrationShellStreamItem.Type;\n\nexport const OrchestrationSubscribeShellInput = Schema.Struct({\n  /**\n   * When provided, the server skips the initial full shell snapshot and instead\n   * replays shell events after this sequence before streaming live events.\n   * Clients that already hold a cached (or HTTP-loaded) shell snapshot pass its\n   * sequence here so the subscription resumes without re-sending the entire\n   * projects/threads list (overlapping events are deduped by sequence on the\n   * client).\n   */\n  afterSequence: Schema.optionalKey(NonNegativeInt),\n  /**\n   * Requests an explicit marker after the subscription has emitted its initial\n   * snapshot or catch-up replay and before it begins emitting live events.\n   */\n  requestCompletionMarker: Schema.optionalKey(Schema.Boolean),\n});\nexport type OrchestrationSubscribeShellInput = typeof OrchestrationSubscribeShellInput.Type;\n\nexport const OrchestrationSubscribeThreadInput = Schema.Struct({\n  threadId: ThreadId,\n  /**\n   * When provided, the server skips the initial snapshot frame and instead\n   * replays events after this sequence before streaming live events. Clients\n   * that load the snapshot over HTTP pass the snapshot's sequence here so the\n   * live subscription resumes without a gap (overlapping events are deduped by\n   * sequence on the client).\n   */\n  afterSequence: Schema.optionalKey(NonNegativeInt),\n  /**\n   * Requests an explicit marker after the subscription has emitted its initial\n   * snapshot or catch-up replay and before it begins emitting live events.\n   */\n  requestCompletionMarker: Schema.optionalKey(Schema.Boolean),\n  /**\n   * When provided, the fallback snapshot frame (sent when `afterSequence` is\n   * missing or the catch-up gap is too large) is windowed to the last\n   * `turnLimit` user-anchored turns and carries `page` metadata. Absent means\n   * the fallback snapshot is the full thread, preserving pre-pagination client\n   * behavior. Live events are unaffected either way.\n   */\n  turnLimit: Schema.optionalKey(PositiveInt),\n});\nexport type OrchestrationSubscribeThreadInput = typeof OrchestrationSubscribeThreadInput.Type;\n\n/**\n * Bounds a thread detail read to a window of recent turns. `turnLimit` counts\n * turns with a user pending message (subagent/fan-out turns between them ride\n * along), so the window always contains the last N user prompts. `beforeCursor`\n * requests the disjoint page of older turns strictly before a previously\n * returned cursor. Requests without a window get the full thread; pagination is\n * strictly opt-in so older clients keep today's behavior on both HTTP and the\n * WebSocket fallback snapshot.\n */\nexport const OrchestrationThreadDetailWindow = Schema.Struct({\n  turnLimit: Schema.optionalKey(PositiveInt),\n  beforeCursor: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type OrchestrationThreadDetailWindow = typeof OrchestrationThreadDetailWindow.Type;\n\n/**\n * Page metadata for a windowed thread detail read. `beforeCursor` is opaque and\n * exclusive: passing it back returns the adjacent disjoint slice of older\n * turns. `null` means the thread is fully loaded below this page. The\n * `snapshotSequence` mirrors the top-level snapshot sequence so history pages\n * can be sequence-checked against live state before merging.\n */\nexport const OrchestrationThreadDetailPage = Schema.Struct({\n  beforeCursor: Schema.NullOr(TrimmedNonEmptyString),\n  hasMore: Schema.Boolean,\n  snapshotSequence: NonNegativeInt,\n  /**\n   * Highest event sequence applied to THIS thread at page read time. The\n   * global `snapshotSequence` advances with every thread's events, so a\n   * client cannot wait for it via its per-thread subscription; this\n   * thread-scoped watermark is reachable. A client merging an older page\n   * must first have applied live events up to it — otherwise a streaming\n   * turn outside the loaded window could have deltas replayed on top of\n   * page content that already includes them, duplicating text.\n   */\n  threadSequence: Schema.optionalKey(NonNegativeInt),\n});\nexport type OrchestrationThreadDetailPage = typeof OrchestrationThreadDetailPage.Type;\n\nexport const OrchestrationThreadDetailSnapshot = Schema.Struct({\n  snapshotSequence: NonNegativeInt,\n  thread: OrchestrationThread,\n  // Present only on windowed responses. Absent on full snapshots (and from\n  // pre-pagination servers), which clients treat as fully loaded.\n  page: Schema.optional(OrchestrationThreadDetailPage),\n});\nexport type OrchestrationThreadDetailSnapshot = typeof OrchestrationThreadDetailSnapshot.Type;\n\nexport const ProjectCreateCommand = Schema.Struct({\n  type: Schema.Literal(\"project.create\"),\n  commandId: CommandId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  workspaceRoot: TrimmedNonEmptyString,\n  createWorkspaceRootIfMissing: Schema.optional(Schema.Boolean),\n  defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),\n  createdAt: IsoDateTime,\n});\n\nconst ProjectMetaUpdateCommand = Schema.Struct({\n  type: Schema.Literal(\"project.meta.update\"),\n  commandId: CommandId,\n  projectId: ProjectId,\n  title: Schema.optional(TrimmedNonEmptyString),\n  workspaceRoot: Schema.optional(TrimmedNonEmptyString),\n  defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),\n  scripts: Schema.optional(Schema.Array(ProjectScript)),\n});\n\nconst ProjectDeleteCommand = Schema.Struct({\n  type: Schema.Literal(\"project.delete\"),\n  commandId: CommandId,\n  projectId: ProjectId,\n  force: Schema.optional(Schema.Boolean),\n});\n\nconst ThreadCreateCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.create\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadDeleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.delete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadArchiveCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.archive\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadUnarchiveCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.unarchive\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadSettleCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.settle\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadUnsettleCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.unsettle\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  // Commands only carry \"user\": activity un-settles are decided server-side\n  // (the decider emits thread.unsettled(reason: \"activity\") events directly,\n  // never through this command), so a client cannot forge the neutral reset.\n  reason: Schema.Literal(\"user\"),\n});\n\nconst ThreadSnoozeCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.snooze\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  // The wake time. Event-based wake conditions (PR merged, review posted)\n  // will arrive as an optional condition field alongside this; time-based\n  // snooze is just the first kind of condition.\n  snoozedUntil: IsoDateTime,\n});\n\nconst ThreadUnsnoozeCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.unsnooze\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  // Commands only carry \"user\": activity wakes are decided server-side (the\n  // decider emits thread.unsnoozed(reason: \"activity\") directly), and timer\n  // wakes need no event at all — clients derive visibility from snoozedUntil,\n  // so a passed wake time simply stops classifying as snoozed.\n  reason: Schema.Literal(\"user\"),\n});\n\nconst ThreadPinCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.pin\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  // Initial slot in the user-arranged pinned order (see ThreadPinReorderCommand).\n  // Optional: clients on pre-reorder servers omit it, and the pinned block\n  // falls back to creation order for keyless threads.\n  orderKey: Schema.optional(TrimmedNonEmptyString),\n});\n\nconst ThreadUnpinCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.unpin\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n});\n\nconst ThreadPinReorderCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.pin.reorder\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  // Fractional index key: pinned threads sort by plain string comparison of\n  // these keys, so a drag writes one key to one thread — neighbors (possibly\n  // on other servers) are never touched. Clients compute a key that sorts\n  // between the dropped position's neighbors.\n  orderKey: TrimmedNonEmptyString,\n});\n\nconst ThreadMetaUpdateCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.meta.update\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  title: Schema.optional(TrimmedNonEmptyString),\n  regenerateTitle: Schema.optional(Schema.Literal(true)),\n  modelSelection: Schema.optional(ModelSelection),\n  branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n}).check(\n  Schema.makeFilter(\n    (input) =>\n      !(input.title !== undefined && input.regenerateTitle === true) ||\n      \"title and regenerateTitle cannot be specified together\",\n  ),\n);\n\nconst ThreadRuntimeModeSetCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.runtime-mode.set\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  runtimeMode: RuntimeMode,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadInteractionModeSetCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.interaction-mode.set\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  interactionMode: ProviderInteractionMode,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTurnStartBootstrapCreateThread = Schema.Struct({\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode,\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTurnStartBootstrapPrepareWorktree = Schema.Struct({\n  projectCwd: TrimmedNonEmptyString,\n  baseBranch: TrimmedNonEmptyString,\n  branch: Schema.optional(TrimmedNonEmptyString),\n  startFromOrigin: Schema.optional(Schema.Boolean),\n});\n\nconst ThreadTurnStartBootstrap = Schema.Struct({\n  createThread: Schema.optional(ThreadTurnStartBootstrapCreateThread),\n  prepareWorktree: Schema.optional(ThreadTurnStartBootstrapPrepareWorktree),\n  runSetupScript: Schema.optional(Schema.Boolean),\n});\n\nexport type ThreadTurnStartBootstrap = typeof ThreadTurnStartBootstrap.Type;\n\nexport const ThreadTurnStartCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.turn.start\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  message: Schema.Struct({\n    messageId: MessageId,\n    role: Schema.Literal(\"user\"),\n    text: Schema.String,\n    attachments: Schema.Array(ChatAttachment),\n  }),\n  modelSelection: Schema.optional(ModelSelection),\n  titleSeed: Schema.optional(TrimmedNonEmptyString),\n  runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  bootstrap: Schema.optional(ThreadTurnStartBootstrap),\n  sourceProposedPlan: Schema.optional(SourceProposedPlanReference),\n  createdAt: IsoDateTime,\n});\n\nconst ClientThreadTurnStartCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.turn.start\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  message: Schema.Struct({\n    messageId: MessageId,\n    role: Schema.Literal(\"user\"),\n    text: Schema.String,\n    attachments: Schema.Array(UploadChatAttachment),\n  }),\n  modelSelection: Schema.optional(ModelSelection),\n  titleSeed: Schema.optional(TrimmedNonEmptyString),\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode,\n  bootstrap: Schema.optional(ThreadTurnStartBootstrap),\n  sourceProposedPlan: Schema.optional(SourceProposedPlanReference),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTurnInterruptCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.turn.interrupt\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  turnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadApprovalRespondCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.approval.respond\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  decision: ProviderApprovalDecision,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadUserInputRespondCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.user-input.respond\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  answers: ProviderUserInputAnswers,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadCheckpointRevertCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.checkpoint.revert\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  turnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadSessionStopCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.session.stop\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  createdAt: IsoDateTime,\n});\n\nconst DispatchableClientOrchestrationCommand = Schema.Union([\n  ProjectCreateCommand,\n  ProjectMetaUpdateCommand,\n  ProjectDeleteCommand,\n  ThreadCreateCommand,\n  ThreadDeleteCommand,\n  ThreadArchiveCommand,\n  ThreadUnarchiveCommand,\n  ThreadSettleCommand,\n  ThreadUnsettleCommand,\n  ThreadSnoozeCommand,\n  ThreadUnsnoozeCommand,\n  ThreadPinCommand,\n  ThreadUnpinCommand,\n  ThreadPinReorderCommand,\n  ThreadMetaUpdateCommand,\n  ThreadRuntimeModeSetCommand,\n  ThreadInteractionModeSetCommand,\n  ThreadTurnStartCommand,\n  ThreadTurnInterruptCommand,\n  ThreadApprovalRespondCommand,\n  ThreadUserInputRespondCommand,\n  ThreadCheckpointRevertCommand,\n  ThreadSessionStopCommand,\n]);\nexport type DispatchableClientOrchestrationCommand =\n  typeof DispatchableClientOrchestrationCommand.Type;\n\nexport const ClientOrchestrationCommand = Schema.Union([\n  ProjectCreateCommand,\n  ProjectMetaUpdateCommand,\n  ProjectDeleteCommand,\n  ThreadCreateCommand,\n  ThreadDeleteCommand,\n  ThreadArchiveCommand,\n  ThreadUnarchiveCommand,\n  ThreadSettleCommand,\n  ThreadUnsettleCommand,\n  ThreadSnoozeCommand,\n  ThreadUnsnoozeCommand,\n  ThreadPinCommand,\n  ThreadUnpinCommand,\n  ThreadPinReorderCommand,\n  ThreadMetaUpdateCommand,\n  ThreadRuntimeModeSetCommand,\n  ThreadInteractionModeSetCommand,\n  ClientThreadTurnStartCommand,\n  ThreadTurnInterruptCommand,\n  ThreadApprovalRespondCommand,\n  ThreadUserInputRespondCommand,\n  ThreadCheckpointRevertCommand,\n  ThreadSessionStopCommand,\n]);\nexport type ClientOrchestrationCommand = typeof ClientOrchestrationCommand.Type;\n\nconst ThreadSessionSetCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.session.set\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  session: OrchestrationSession,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadMessageAssistantDeltaCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.message.assistant.delta\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  messageId: MessageId,\n  delta: Schema.String,\n  turnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadMessageAssistantCompleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.message.assistant.complete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  messageId: MessageId,\n  turnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n});\n\nconst ThreadProposedPlanUpsertCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.proposed-plan.upsert\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  proposedPlan: OrchestrationProposedPlan,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTurnDiffCompleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.turn.diff.complete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  turnId: TurnId,\n  completedAt: IsoDateTime,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.optional(MessageId),\n  checkpointTurnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadActivityAppendCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.activity.append\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  activity: OrchestrationThreadActivity,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadRevertCompleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.revert.complete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  turnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadTitleRegenerationCompleteCommand = Schema.Struct({\n  type: Schema.Literal(\"thread.title.regeneration.complete\"),\n  commandId: CommandId,\n  threadId: ThreadId,\n  requestId: CommandId,\n  title: Schema.optional(TrimmedNonEmptyString),\n});\n\nconst InternalOrchestrationCommand = Schema.Union([\n  ThreadSessionSetCommand,\n  ThreadMessageAssistantDeltaCommand,\n  ThreadMessageAssistantCompleteCommand,\n  ThreadProposedPlanUpsertCommand,\n  ThreadTurnDiffCompleteCommand,\n  ThreadActivityAppendCommand,\n  ThreadRevertCompleteCommand,\n  ThreadTitleRegenerationCompleteCommand,\n]);\nexport type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;\n\nexport const OrchestrationCommand = Schema.Union([\n  DispatchableClientOrchestrationCommand,\n  InternalOrchestrationCommand,\n]);\nexport type OrchestrationCommand = typeof OrchestrationCommand.Type;\n\nexport const OrchestrationEventType = Schema.Literals([\n  \"project.created\",\n  \"project.meta-updated\",\n  \"project.deleted\",\n  \"thread.created\",\n  \"thread.deleted\",\n  \"thread.archived\",\n  \"thread.unarchived\",\n  \"thread.settled\",\n  \"thread.unsettled\",\n  \"thread.snoozed\",\n  \"thread.unsnoozed\",\n  \"thread.pinned\",\n  \"thread.unpinned\",\n  \"thread.pin-reordered\",\n  \"thread.meta-updated\",\n  \"thread.runtime-mode-set\",\n  \"thread.interaction-mode-set\",\n  \"thread.message-sent\",\n  \"thread.turn-start-requested\",\n  \"thread.turn-interrupt-requested\",\n  \"thread.approval-response-requested\",\n  \"thread.user-input-response-requested\",\n  \"thread.checkpoint-revert-requested\",\n  \"thread.reverted\",\n  \"thread.session-stop-requested\",\n  \"thread.session-set\",\n  \"thread.proposed-plan-upserted\",\n  \"thread.turn-diff-completed\",\n  \"thread.activity-appended\",\n]);\nexport type OrchestrationEventType = typeof OrchestrationEventType.Type;\n\nexport const OrchestrationAggregateKind = Schema.Literals([\"project\", \"thread\"]);\nexport type OrchestrationAggregateKind = typeof OrchestrationAggregateKind.Type;\nexport const OrchestrationActorKind = Schema.Literals([\"client\", \"server\", \"provider\"]);\n\nexport const ProjectCreatedPayload = Schema.Struct({\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  workspaceRoot: TrimmedNonEmptyString,\n  repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),\n  defaultModelSelection: Schema.NullOr(ModelSelection),\n  scripts: Schema.Array(ProjectScript),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ProjectMetaUpdatedPayload = Schema.Struct({\n  projectId: ProjectId,\n  title: Schema.optional(TrimmedNonEmptyString),\n  workspaceRoot: Schema.optional(TrimmedNonEmptyString),\n  repositoryIdentity: Schema.optional(Schema.NullOr(RepositoryIdentity)),\n  defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),\n  scripts: Schema.optional(Schema.Array(ProjectScript)),\n  updatedAt: IsoDateTime,\n});\n\nexport const ProjectDeletedPayload = Schema.Struct({\n  projectId: ProjectId,\n  deletedAt: IsoDateTime,\n});\n\nexport const ThreadCreatedPayload = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  title: TrimmedNonEmptyString,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  branch: Schema.NullOr(TrimmedNonEmptyString),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyString),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadDeletedPayload = Schema.Struct({\n  threadId: ThreadId,\n  deletedAt: IsoDateTime,\n});\n\nexport const ThreadArchivedPayload = Schema.Struct({\n  threadId: ThreadId,\n  archivedAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadUnarchivedPayload = Schema.Struct({\n  threadId: ThreadId,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadSettledPayload = Schema.Struct({\n  threadId: ThreadId,\n  settledAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadUnsettledPayload = Schema.Struct({\n  threadId: ThreadId,\n  reason: Schema.Literals([\"user\", \"activity\"]),\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadSnoozedPayload = Schema.Struct({\n  threadId: ThreadId,\n  snoozedUntil: IsoDateTime,\n  snoozedAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadUnsnoozedPayload = Schema.Struct({\n  threadId: ThreadId,\n  // user: explicit \"wake now\". activity: real work arrived (user message /\n  // session coming alive) and the decider cleared the snooze — mirrors\n  // thread.unsettled's activity resets. Timer wakes emit no event: clients\n  // derive them from snoozedUntil passing.\n  reason: Schema.Literals([\"user\", \"activity\"]),\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadPinnedPayload = Schema.Struct({\n  threadId: ThreadId,\n  pinnedAt: IsoDateTime,\n  // Absent on re-pins of an already-pinned thread (the existing key wins)\n  // and on pins from clients that predate reordering.\n  pinOrderKey: Schema.optional(TrimmedNonEmptyString),\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadUnpinnedPayload = Schema.Struct({\n  threadId: ThreadId,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadPinReorderedPayload = Schema.Struct({\n  threadId: ThreadId,\n  orderKey: TrimmedNonEmptyString,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadMetaUpdatedPayload = Schema.Struct({\n  threadId: ThreadId,\n  title: Schema.optional(TrimmedNonEmptyString),\n  /** Intent marker consumed by the title-generation reactor. Keeping this on\n      the existing event lets older clients safely ignore the new field. */\n  regenerateTitle: Schema.optional(Schema.Literal(true)),\n  /** Title at request time, used to avoid overwriting a later manual rename. */\n  previousTitle: Schema.optional(TrimmedNonEmptyString),\n  /** Pending state shared with clients. Null clears a matching request. */\n  titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),\n  modelSelection: Schema.optional(ModelSelection),\n  branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadRuntimeModeSetPayload = Schema.Struct({\n  threadId: ThreadId,\n  runtimeMode: RuntimeMode,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadInteractionModeSetPayload = Schema.Struct({\n  threadId: ThreadId,\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadMessageSentPayload = Schema.Struct({\n  threadId: ThreadId,\n  messageId: MessageId,\n  role: OrchestrationMessageRole,\n  text: Schema.String,\n  attachments: Schema.optional(Schema.Array(ChatAttachment)),\n  turnId: Schema.NullOr(TurnId),\n  streaming: Schema.Boolean,\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\n\nexport const ThreadTurnStartRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  messageId: MessageId,\n  modelSelection: Schema.optional(ModelSelection),\n  titleSeed: Schema.optional(TrimmedNonEmptyString),\n  runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),\n  interactionMode: ProviderInteractionMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROVIDER_INTERACTION_MODE)),\n  ),\n  sourceProposedPlan: Schema.optional(SourceProposedPlanReference),\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadTurnInterruptRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  turnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadApprovalResponseRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  decision: ProviderApprovalDecision,\n  createdAt: IsoDateTime,\n});\n\nconst ThreadUserInputResponseRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  answers: ProviderUserInputAnswers,\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadCheckpointRevertRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  turnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadRevertedPayload = Schema.Struct({\n  threadId: ThreadId,\n  turnCount: NonNegativeInt,\n});\n\nexport const ThreadSessionStopRequestedPayload = Schema.Struct({\n  threadId: ThreadId,\n  createdAt: IsoDateTime,\n});\n\nexport const ThreadSessionSetPayload = Schema.Struct({\n  threadId: ThreadId,\n  session: OrchestrationSession,\n});\n\nexport const ThreadProposedPlanUpsertedPayload = Schema.Struct({\n  threadId: ThreadId,\n  proposedPlan: OrchestrationProposedPlan,\n});\n\nexport const ThreadTurnDiffCompletedPayload = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.NullOr(MessageId),\n  completedAt: IsoDateTime,\n});\n\nexport const ThreadActivityAppendedPayload = Schema.Struct({\n  threadId: ThreadId,\n  activity: OrchestrationThreadActivity,\n});\n\nexport const OrchestrationEventMetadata = Schema.Struct({\n  providerTurnId: Schema.optional(TrimmedNonEmptyString),\n  providerItemId: Schema.optional(ProviderItemId),\n  adapterKey: Schema.optional(TrimmedNonEmptyString),\n  requestId: Schema.optional(ApprovalRequestId),\n  ingestedAt: Schema.optional(IsoDateTime),\n});\nexport type OrchestrationEventMetadata = typeof OrchestrationEventMetadata.Type;\n\nconst EventBaseFields = {\n  sequence: NonNegativeInt,\n  eventId: EventId,\n  aggregateKind: OrchestrationAggregateKind,\n  aggregateId: Schema.Union([ProjectId, ThreadId]),\n  occurredAt: IsoDateTime,\n  commandId: Schema.NullOr(CommandId),\n  causationEventId: Schema.NullOr(EventId),\n  correlationId: Schema.NullOr(CommandId),\n  metadata: OrchestrationEventMetadata,\n} as const;\n\nexport const OrchestrationEvent = Schema.Union([\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"project.created\"),\n    payload: ProjectCreatedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"project.meta-updated\"),\n    payload: ProjectMetaUpdatedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"project.deleted\"),\n    payload: ProjectDeletedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.created\"),\n    payload: ThreadCreatedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.deleted\"),\n    payload: ThreadDeletedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.archived\"),\n    payload: ThreadArchivedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.unarchived\"),\n    payload: ThreadUnarchivedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.settled\"),\n    payload: ThreadSettledPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.unsettled\"),\n    payload: ThreadUnsettledPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.snoozed\"),\n    payload: ThreadSnoozedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.unsnoozed\"),\n    payload: ThreadUnsnoozedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.pinned\"),\n    payload: ThreadPinnedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.unpinned\"),\n    payload: ThreadUnpinnedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.pin-reordered\"),\n    payload: ThreadPinReorderedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.meta-updated\"),\n    payload: ThreadMetaUpdatedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.runtime-mode-set\"),\n    payload: ThreadRuntimeModeSetPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.interaction-mode-set\"),\n    payload: ThreadInteractionModeSetPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.message-sent\"),\n    payload: ThreadMessageSentPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.turn-start-requested\"),\n    payload: ThreadTurnStartRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.turn-interrupt-requested\"),\n    payload: ThreadTurnInterruptRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.approval-response-requested\"),\n    payload: ThreadApprovalResponseRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.user-input-response-requested\"),\n    payload: ThreadUserInputResponseRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.checkpoint-revert-requested\"),\n    payload: ThreadCheckpointRevertRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.reverted\"),\n    payload: ThreadRevertedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.session-stop-requested\"),\n    payload: ThreadSessionStopRequestedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.session-set\"),\n    payload: ThreadSessionSetPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.proposed-plan-upserted\"),\n    payload: ThreadProposedPlanUpsertedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.turn-diff-completed\"),\n    payload: ThreadTurnDiffCompletedPayload,\n  }),\n  Schema.Struct({\n    ...EventBaseFields,\n    type: Schema.Literal(\"thread.activity-appended\"),\n    payload: ThreadActivityAppendedPayload,\n  }),\n]);\nexport type OrchestrationEvent = typeof OrchestrationEvent.Type;\n\nexport const OrchestrationThreadStreamItem = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"synchronized\"),\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"snapshot\"),\n    snapshot: OrchestrationThreadDetailSnapshot,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"event\"),\n    event: OrchestrationEvent,\n  }),\n]);\nexport type OrchestrationThreadStreamItem = typeof OrchestrationThreadStreamItem.Type;\n\nexport const OrchestrationCommandReceiptStatus = Schema.Literals([\"accepted\", \"rejected\"]);\nexport type OrchestrationCommandReceiptStatus = typeof OrchestrationCommandReceiptStatus.Type;\n\nexport const TurnCountRange = Schema.Struct({\n  fromTurnCount: NonNegativeInt,\n  toTurnCount: NonNegativeInt,\n}).check(\n  Schema.makeFilter(\n    (input) =>\n      input.fromTurnCount <= input.toTurnCount ||\n      new SchemaIssue.InvalidValue({\n        message: \"fromTurnCount must be less than or equal to toTurnCount\",\n      }),\n    { identifier: \"OrchestrationTurnDiffRange\" },\n  ),\n);\n\nexport const ThreadTurnDiff = TurnCountRange.mapFields(\n  Struct.assign({\n    threadId: ThreadId,\n    diff: Schema.String,\n  }),\n  { unsafePreserveChecks: true },\n);\n\nexport const ProviderSessionRuntimeStatus = Schema.Literals([\n  \"starting\",\n  \"running\",\n  \"stopped\",\n  \"error\",\n]);\nexport type ProviderSessionRuntimeStatus = typeof ProviderSessionRuntimeStatus.Type;\n\nconst ProjectionThreadTurnStatus = Schema.Literals([\n  \"running\",\n  \"completed\",\n  \"interrupted\",\n  \"error\",\n]);\nexport type ProjectionThreadTurnStatus = typeof ProjectionThreadTurnStatus.Type;\n\nconst ProjectionCheckpointRow = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.NullOr(MessageId),\n  completedAt: IsoDateTime,\n});\nexport type ProjectionCheckpointRow = typeof ProjectionCheckpointRow.Type;\n\nexport const ProjectionPendingApprovalStatus = Schema.Literals([\"pending\", \"resolved\"]);\nexport type ProjectionPendingApprovalStatus = typeof ProjectionPendingApprovalStatus.Type;\n\nexport const ProjectionPendingApprovalDecision = Schema.NullOr(ProviderApprovalDecision);\nexport type ProjectionPendingApprovalDecision = typeof ProjectionPendingApprovalDecision.Type;\n\nexport const DispatchResult = Schema.Struct({\n  sequence: NonNegativeInt,\n});\nexport type DispatchResult = typeof DispatchResult.Type;\n\nexport const OrchestrationGetTurnDiffInput = TurnCountRange.mapFields(\n  Struct.assign({\n    threadId: ThreadId,\n    ignoreWhitespace: Schema.optionalKey(Schema.Boolean),\n  }),\n  { unsafePreserveChecks: true },\n);\nexport type OrchestrationGetTurnDiffInput = typeof OrchestrationGetTurnDiffInput.Type;\n\nexport const OrchestrationGetTurnDiffResult = ThreadTurnDiff;\nexport type OrchestrationGetTurnDiffResult = typeof OrchestrationGetTurnDiffResult.Type;\n\nexport const OrchestrationGetFullThreadDiffInput = Schema.Struct({\n  threadId: ThreadId,\n  toTurnCount: NonNegativeInt,\n  ignoreWhitespace: Schema.optionalKey(Schema.Boolean),\n});\nexport type OrchestrationGetFullThreadDiffInput = typeof OrchestrationGetFullThreadDiffInput.Type;\n\nexport const OrchestrationGetFullThreadDiffResult = ThreadTurnDiff;\nexport type OrchestrationGetFullThreadDiffResult = typeof OrchestrationGetFullThreadDiffResult.Type;\n\nexport const OrchestrationThreadSearchSource = Schema.Literals([\"user\", \"assistant\"]);\nexport type OrchestrationThreadSearchSource = typeof OrchestrationThreadSearchSource.Type;\n\n// The server's SQLite client is synchronous and single-connection. Bound both\n// scan input and response size so a search cannot monopolize that connection.\nexport const OrchestrationSearchThreadsInput = Schema.Struct({\n  query: TrimmedString.check(Schema.isMinLength(2), Schema.isMaxLength(200)),\n  limit: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }))),\n});\nexport type OrchestrationSearchThreadsInput = typeof OrchestrationSearchThreadsInput.Type;\n\nexport const OrchestrationThreadSearchMatch = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  source: OrchestrationThreadSearchSource,\n  snippet: Schema.String.check(Schema.isMaxLength(240)),\n  messageCreatedAt: Schema.NullOr(IsoDateTime),\n});\nexport type OrchestrationThreadSearchMatch = typeof OrchestrationThreadSearchMatch.Type;\n\nexport const OrchestrationSearchThreadsResult = Schema.Struct({\n  matches: Schema.Array(OrchestrationThreadSearchMatch),\n});\nexport type OrchestrationSearchThreadsResult = typeof OrchestrationSearchThreadsResult.Type;\n\nexport const OrchestrationGetWorkflowScriptInput = Schema.Struct({\n  threadId: ThreadId,\n  /** Absolute path from the workflow's runHandles.scriptPath. The server\n   * re-derives containment; the client value is a hint, never trusted. */\n  scriptPath: TrimmedNonEmptyString,\n});\nexport type OrchestrationGetWorkflowScriptInput = typeof OrchestrationGetWorkflowScriptInput.Type;\n\nexport const OrchestrationGetWorkflowScriptResult = Schema.Struct({\n  scriptPath: TrimmedNonEmptyString,\n  contents: Schema.String,\n  truncated: Schema.Boolean,\n});\nexport type OrchestrationGetWorkflowScriptResult = typeof OrchestrationGetWorkflowScriptResult.Type;\n\nconst WORKFLOW_SCRIPT_ERROR_MESSAGES = {\n  \"invalid-path\": \"Workflow scripts must be absolute .js paths.\",\n  \"root-unavailable\": \"Script root unavailable.\",\n  \"not-found\": \"Script not found.\",\n  \"outside-root\": \"Script path is outside the workflow scripts root.\",\n  \"not-js\": \"Resolved script is not a .js file.\",\n  \"not-regular-file\": \"Script is not a regular file.\",\n  \"changed-during-read\": \"Script changed between resolution and open.\",\n  \"read-failed\": \"Script read failed.\",\n} as const;\n\nexport class OrchestrationGetWorkflowScriptError extends Schema.TaggedErrorClass<OrchestrationGetWorkflowScriptError>()(\n  \"OrchestrationGetWorkflowScriptError\",\n  {\n    reason: Schema.Literals([\n      \"invalid-path\",\n      \"root-unavailable\",\n      \"not-found\",\n      \"outside-root\",\n      \"not-js\",\n      \"not-regular-file\",\n      \"changed-during-read\",\n      \"read-failed\",\n    ]),\n    scriptPath: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return WORKFLOW_SCRIPT_ERROR_MESSAGES[this.reason];\n  }\n}\n\nexport const OrchestrationRpcSchemas = {\n  dispatchCommand: {\n    input: ClientOrchestrationCommand,\n    output: DispatchResult,\n  },\n  getWorkflowScript: {\n    input: OrchestrationGetWorkflowScriptInput,\n    output: OrchestrationGetWorkflowScriptResult,\n  },\n  getTurnDiff: {\n    input: OrchestrationGetTurnDiffInput,\n    output: OrchestrationGetTurnDiffResult,\n  },\n  getFullThreadDiff: {\n    input: OrchestrationGetFullThreadDiffInput,\n    output: OrchestrationGetFullThreadDiffResult,\n  },\n  searchThreads: {\n    input: OrchestrationSearchThreadsInput,\n    output: OrchestrationSearchThreadsResult,\n  },\n  getArchivedShellSnapshot: {\n    input: Schema.Struct({}),\n    output: OrchestrationShellSnapshot,\n  },\n  subscribeThread: {\n    input: OrchestrationSubscribeThreadInput,\n    output: OrchestrationThreadStreamItem,\n  },\n  subscribeShell: {\n    input: OrchestrationSubscribeShellInput,\n    output: OrchestrationShellStreamItem,\n  },\n} as const;\n\nexport class OrchestrationGetSnapshotError extends Schema.TaggedErrorClass<OrchestrationGetSnapshotError>()(\n  \"OrchestrationGetSnapshotError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n\nexport class OrchestrationDispatchCommandError extends Schema.TaggedErrorClass<OrchestrationDispatchCommandError>()(\n  \"OrchestrationDispatchCommandError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n\nexport class OrchestrationGetTurnDiffError extends Schema.TaggedErrorClass<OrchestrationGetTurnDiffError>()(\n  \"OrchestrationGetTurnDiffError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n\nexport class OrchestrationGetFullThreadDiffError extends Schema.TaggedErrorClass<OrchestrationGetFullThreadDiffError>()(\n  \"OrchestrationGetFullThreadDiffError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n\nexport class OrchestrationSearchThreadsError extends Schema.TaggedErrorClass<OrchestrationSearchThreadsError>()(\n  \"OrchestrationSearchThreadsError\",\n  {\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {}\n","import * as Context from \"effect/Context\";\nimport * as Schema from \"effect/Schema\";\nimport * as HttpApi from \"effect/unstable/httpapi/HttpApi\";\nimport * as HttpApiEndpoint from \"effect/unstable/httpapi/HttpApiEndpoint\";\nimport * as HttpApiGroup from \"effect/unstable/httpapi/HttpApiGroup\";\nimport * as HttpApiMiddleware from \"effect/unstable/httpapi/HttpApiMiddleware\";\nimport * as HttpApiSchema from \"effect/unstable/httpapi/HttpApiSchema\";\nimport * as HttpApiSecurity from \"effect/unstable/httpapi/HttpApiSecurity\";\nimport * as OpenApi from \"effect/unstable/httpapi/OpenApi\";\n\nimport { EnvironmentId, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { ExecutionEnvironmentDescriptor } from \"./environment.ts\";\n\nexport const RelayAgentAwarenessPlatform = Schema.Literal(\"ios\");\nexport type RelayAgentAwarenessPlatform = typeof RelayAgentAwarenessPlatform.Type;\n\nexport const RelayAgentAwarenessPhase = Schema.Literals([\n  \"starting\",\n  \"running\",\n  \"waiting_for_approval\",\n  \"waiting_for_input\",\n  \"completed\",\n  \"failed\",\n  \"stale\",\n]);\nexport type RelayAgentAwarenessPhase = typeof RelayAgentAwarenessPhase.Type;\n\nexport const RelayAgentAwarenessPreferences = Schema.Struct({\n  liveActivitiesEnabled: Schema.Boolean,\n  notificationsEnabled: Schema.Boolean,\n  notifyOnApproval: Schema.Boolean,\n  notifyOnInput: Schema.Boolean,\n  notifyOnCompletion: Schema.Boolean,\n  notifyOnFailure: Schema.Boolean,\n});\nexport type RelayAgentAwarenessPreferences = typeof RelayAgentAwarenessPreferences.Type;\n\nexport const RelayApnsEnvironment = Schema.Literals([\"sandbox\", \"production\"]);\nexport type RelayApnsEnvironment = typeof RelayApnsEnvironment.Type;\n\nexport const RelayDeviceRegistrationRequest = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  platform: RelayAgentAwarenessPlatform,\n  iosMajorVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(18)),\n  appVersion: Schema.optional(TrimmedNonEmptyString),\n  // APNs routing for this install: the topic must match the app's bundle id\n  // (dev/preview/prod variants differ) and development-signed builds receive\n  // sandbox tokens. Optional so older app builds keep registering; the relay\n  // falls back to its configured defaults.\n  bundleId: Schema.optional(TrimmedNonEmptyString),\n  apsEnvironment: Schema.optional(RelayApnsEnvironment),\n  pushToken: Schema.optional(TrimmedNonEmptyString),\n  pushToStartToken: Schema.optional(TrimmedNonEmptyString),\n  preferences: RelayAgentAwarenessPreferences,\n});\nexport type RelayDeviceRegistrationRequest = typeof RelayDeviceRegistrationRequest.Type;\n\nexport const RelayClientDeviceRecord = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  platform: RelayAgentAwarenessPlatform,\n  iosMajorVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(18)),\n  appVersion: Schema.NullOr(TrimmedNonEmptyString),\n  notifications: Schema.Struct({\n    enabled: Schema.Boolean,\n    notifyOnApproval: Schema.Boolean,\n    notifyOnInput: Schema.Boolean,\n    notifyOnCompletion: Schema.Boolean,\n    notifyOnFailure: Schema.Boolean,\n  }),\n  liveActivities: Schema.Struct({\n    enabled: Schema.Boolean,\n  }),\n  updatedAt: TrimmedNonEmptyString,\n});\nexport type RelayClientDeviceRecord = typeof RelayClientDeviceRecord.Type;\n\nexport const RelayListDevicesResponse = Schema.Struct({\n  devices: Schema.Array(RelayClientDeviceRecord),\n});\nexport type RelayListDevicesResponse = typeof RelayListDevicesResponse.Type;\n\nexport const RelayLiveActivityRegistrationRequest = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n  activityPushToken: TrimmedNonEmptyString,\n});\nexport type RelayLiveActivityRegistrationRequest = typeof RelayLiveActivityRegistrationRequest.Type;\n\nexport const RelayDeviceUnregistrationParams = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n});\nexport type RelayDeviceUnregistrationParams = typeof RelayDeviceUnregistrationParams.Type;\n\nexport const RelayAgentActivityState = Schema.Struct({\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n  projectTitle: TrimmedNonEmptyString,\n  threadTitle: TrimmedNonEmptyString,\n  phase: RelayAgentAwarenessPhase,\n  headline: TrimmedNonEmptyString,\n  detail: Schema.optional(TrimmedNonEmptyString),\n  modelTitle: TrimmedNonEmptyString,\n  updatedAt: TrimmedNonEmptyString,\n  deepLink: TrimmedNonEmptyString,\n});\nexport type RelayAgentActivityState = typeof RelayAgentActivityState.Type;\n\nexport const RelayAgentActivityAggregateRow = Schema.Struct({\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n  projectTitle: TrimmedNonEmptyString,\n  threadTitle: TrimmedNonEmptyString,\n  modelTitle: TrimmedNonEmptyString,\n  phase: RelayAgentAwarenessPhase,\n  status: TrimmedNonEmptyString,\n  updatedAt: TrimmedNonEmptyString,\n  deepLink: TrimmedNonEmptyString,\n});\nexport type RelayAgentActivityAggregateRow = typeof RelayAgentActivityAggregateRow.Type;\n\nexport const RelayAgentActivityAggregateState = Schema.Struct({\n  title: TrimmedNonEmptyString,\n  subtitle: TrimmedNonEmptyString,\n  activeCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n  updatedAt: TrimmedNonEmptyString,\n  activities: Schema.Array(RelayAgentActivityAggregateRow),\n});\nexport type RelayAgentActivityAggregateState = typeof RelayAgentActivityAggregateState.Type;\n\nexport const RelayManagedEndpointProviderKind = Schema.Literals([\n  \"manual\",\n  \"cloudflare_tunnel\",\n  \"t3_relay\",\n]);\nexport type RelayManagedEndpointProviderKind = typeof RelayManagedEndpointProviderKind.Type;\n\nexport const RelayManagedEndpoint = Schema.Struct({\n  httpBaseUrl: TrimmedNonEmptyString,\n  wsBaseUrl: TrimmedNonEmptyString,\n  providerKind: RelayManagedEndpointProviderKind,\n});\nexport type RelayManagedEndpoint = typeof RelayManagedEndpoint.Type;\n\nexport const RelayManagedEndpointOrigin = Schema.Struct({\n  localHttpHost: TrimmedNonEmptyString,\n  localHttpPort: Schema.Int.check(\n    Schema.isGreaterThanOrEqualTo(1),\n    Schema.isLessThanOrEqualTo(65_535),\n  ),\n});\nexport type RelayManagedEndpointOrigin = typeof RelayManagedEndpointOrigin.Type;\n\nexport const RelayManagedEndpointRuntimeConfig = Schema.Struct({\n  providerKind: RelayManagedEndpointProviderKind,\n  connectorToken: TrimmedNonEmptyString,\n  tunnelId: Schema.optional(TrimmedNonEmptyString),\n  tunnelName: Schema.optional(TrimmedNonEmptyString),\n});\nexport type RelayManagedEndpointRuntimeConfig = typeof RelayManagedEndpointRuntimeConfig.Type;\n\nexport const RelayLinkProofRequest = Schema.Struct({\n  challenge: Schema.String,\n  relayIssuer: Schema.String,\n  endpoint: RelayManagedEndpoint,\n  origin: RelayManagedEndpointOrigin,\n});\nexport type RelayLinkProofRequest = typeof RelayLinkProofRequest.Type;\n\nexport const RelayEnvironmentConfigRequest = Schema.Struct({\n  relayUrl: Schema.String,\n  relayIssuer: Schema.optional(Schema.String),\n  cloudUserId: Schema.String,\n  environmentCredential: Schema.String,\n  cloudMintPublicKey: Schema.String,\n  endpointRuntime: Schema.NullOr(RelayManagedEndpointRuntimeConfig),\n});\nexport type RelayEnvironmentConfigRequest = typeof RelayEnvironmentConfigRequest.Type;\n\nconst RelaySignedJwtRegisteredClaims = {\n  iss: TrimmedNonEmptyString,\n  aud: TrimmedNonEmptyString,\n  sub: TrimmedNonEmptyString,\n  jti: TrimmedNonEmptyString,\n  iat: Schema.Int,\n  exp: Schema.Int,\n} as const;\n\nexport const RelayAgentActivityPublishProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n  state: Schema.NullOr(RelayAgentActivityState),\n});\nexport type RelayAgentActivityPublishProofPayload =\n  typeof RelayAgentActivityPublishProofPayload.Type;\nexport type RelayAgentActivityPublishProof = string;\n\nexport const RelayAgentActivityPublishRequest = Schema.Struct({\n  state: Schema.NullOr(RelayAgentActivityState).annotate({\n    description: \"Current agent-awareness state, or null to remove the published state.\",\n  }),\n  proof: TrimmedNonEmptyString.annotate({\n    description: \"Environment-signed JWT covering this published activity state.\",\n  }),\n}).annotate({ description: \"Publishes a signed agent-awareness update from an environment.\" });\nexport type RelayAgentActivityPublishRequest = typeof RelayAgentActivityPublishRequest.Type;\n\nexport const RelayEnvironmentLinkScope = Schema.Literals([\n  \"agent_activity_notifications\",\n  \"managed_tunnels\",\n]);\nexport type RelayEnvironmentLinkScope = typeof RelayEnvironmentLinkScope.Type;\n\nexport const RelayEnvironmentLinkProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  challenge: TrimmedNonEmptyString,\n  descriptor: ExecutionEnvironmentDescriptor,\n  environmentId: EnvironmentId,\n  environmentPublicKey: TrimmedNonEmptyString,\n  endpoint: RelayManagedEndpoint,\n  origin: RelayManagedEndpointOrigin,\n  scopes: Schema.Array(RelayEnvironmentLinkScope),\n});\nexport type RelayEnvironmentLinkProofPayload = typeof RelayEnvironmentLinkProofPayload.Type;\n\nexport const RelayEnvironmentLinkProof = TrimmedNonEmptyString;\nexport type RelayEnvironmentLinkProof = typeof RelayEnvironmentLinkProof.Type;\n\nexport const RelayEnvironmentLinkChallengeRequest = Schema.Struct({\n  notificationsEnabled: Schema.Boolean.annotate({\n    description: \"Whether this link may deliver push notifications.\",\n  }),\n  liveActivitiesEnabled: Schema.Boolean.annotate({\n    description: \"Whether this link may update Live Activities.\",\n  }),\n  managedTunnelsEnabled: Schema.Boolean.annotate({\n    description: \"Whether the relay should provision a managed tunnel for this environment.\",\n  }),\n}).annotate({ description: \"Requested capabilities for a new environment-link challenge.\" });\nexport type RelayEnvironmentLinkChallengeRequest = typeof RelayEnvironmentLinkChallengeRequest.Type;\n\nexport const RelayEnvironmentLinkChallengeResponse = Schema.Struct({\n  challenge: TrimmedNonEmptyString,\n  expiresAt: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentLinkChallengeResponse =\n  typeof RelayEnvironmentLinkChallengeResponse.Type;\n\nexport const RelayEnvironmentLinkRequest = Schema.Struct({\n  deviceId: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Optional client device identifier associated with this link.\",\n    }),\n  ),\n  proof: RelayEnvironmentLinkProof.annotate({\n    description: \"Environment-signed proof bound to a previously issued link challenge.\",\n  }),\n  notificationsEnabled: Schema.Boolean,\n  liveActivitiesEnabled: Schema.Boolean,\n  managedTunnelsEnabled: Schema.Boolean,\n}).annotate({ description: \"Links an authenticated cloud user to a T3 environment.\" });\nexport type RelayEnvironmentLinkRequest = typeof RelayEnvironmentLinkRequest.Type;\n\nexport const RelayEnvironmentLinkResponse = Schema.Struct({\n  ok: Schema.Boolean,\n  cloudUserId: TrimmedNonEmptyString,\n  environmentId: EnvironmentId,\n  endpoint: RelayManagedEndpoint,\n  endpointRuntime: Schema.NullOr(RelayManagedEndpointRuntimeConfig),\n  relayIssuer: TrimmedNonEmptyString,\n  environmentCredential: TrimmedNonEmptyString,\n  cloudMintPublicKey: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentLinkResponse = typeof RelayEnvironmentLinkResponse.Type;\n\nexport const RelayEnvironmentLinkProofInvalidReason = Schema.Literals([\n  \"invalid_signature_or_scope\",\n  \"descriptor_mismatch\",\n  \"replayed_nonce\",\n  \"challenge_invalid\",\n  \"origin_not_allowed\",\n  \"endpoint_not_secure\",\n]);\nexport type RelayEnvironmentLinkProofInvalidReason =\n  typeof RelayEnvironmentLinkProofInvalidReason.Type;\n\nexport const RelayEnvironmentLinkFailedReason = Schema.Literals([\n  \"link_persistence_failed\",\n  \"credential_persistence_failed\",\n  \"replay_persistence_failed\",\n  \"internal_error\",\n]);\nexport type RelayEnvironmentLinkFailedReason = typeof RelayEnvironmentLinkFailedReason.Type;\n\nexport const RelayEnvironmentLinkUnavailableReason = Schema.Literals([\n  \"managed_endpoint_not_configured\",\n  \"managed_endpoint_provisioning_failed\",\n]);\nexport type RelayEnvironmentLinkUnavailableReason =\n  typeof RelayEnvironmentLinkUnavailableReason.Type;\n\nexport const RelayEnvironmentEndpointUnavailableReason = Schema.Literals([\n  \"endpoint_request_failed\",\n  \"endpoint_response_invalid\",\n]);\nexport type RelayEnvironmentEndpointUnavailableReason =\n  typeof RelayEnvironmentEndpointUnavailableReason.Type;\n\nexport const RelayAgentActivityPublishProofInvalidReason = Schema.Literals([\n  \"invalid_signature_or_payload\",\n  \"replayed_nonce\",\n]);\nexport type RelayAgentActivityPublishProofInvalidReason =\n  typeof RelayAgentActivityPublishProofInvalidReason.Type;\n\nexport const RelayAuthInvalidReason = Schema.Literals([\n  \"missing_bearer\",\n  \"invalid_bearer\",\n  \"invalid_dpop\",\n  \"not_authorized\",\n]);\nexport type RelayAuthInvalidReason = typeof RelayAuthInvalidReason.Type;\n\nexport const RelayInternalErrorReason = Schema.Literals([\n  \"database_unavailable\",\n  \"persistence_failed\",\n  \"upstream_unavailable\",\n  \"internal_error\",\n]);\nexport type RelayInternalErrorReason = typeof RelayInternalErrorReason.Type;\n\nexport class RelayAuthInvalidError extends Schema.TaggedErrorClass<RelayAuthInvalidError>()(\n  \"RelayAuthInvalidError\",\n  {\n    code: Schema.Literal(\"auth_invalid\"),\n    reason: RelayAuthInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  override get message(): string {\n    return `Relay authentication failed: ${this.reason}`;\n  }\n}\n\nexport class RelayEnvironmentLinkProofExpiredError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofExpiredError>()(\n  \"RelayEnvironmentLinkProofExpiredError\",\n  {\n    code: Schema.Literal(\"environment_link_proof_expired\"),\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  override get message(): string {\n    return \"Relay environment link proof expired\";\n  }\n}\n\nexport class RelayEnvironmentLinkProofInvalidError extends Schema.TaggedErrorClass<RelayEnvironmentLinkProofInvalidError>()(\n  \"RelayEnvironmentLinkProofInvalidError\",\n  {\n    code: Schema.Literal(\"environment_link_proof_invalid\"),\n    reason: RelayEnvironmentLinkProofInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 400 },\n) {\n  override get message(): string {\n    return `Relay environment link proof is invalid: ${this.reason}`;\n  }\n}\n\nexport const RelayEnvironmentConnectNotAuthorizedReason = Schema.Literals([\n  \"client_proof_key_thumbprint_missing\",\n  \"environment_link_not_found\",\n  \"endpoint_provider_not_managed\",\n  \"managed_endpoint_allocation_not_found\",\n  \"managed_endpoint_base_domain_not_configured\",\n  \"managed_endpoint_allocation_not_ready\",\n  \"managed_endpoint_hostname_invalid\",\n  \"managed_endpoint_mismatch\",\n]);\nexport type RelayEnvironmentConnectNotAuthorizedReason =\n  typeof RelayEnvironmentConnectNotAuthorizedReason.Type;\n\nexport class RelayEnvironmentConnectNotAuthorizedError extends Schema.TaggedErrorClass<RelayEnvironmentConnectNotAuthorizedError>()(\n  \"RelayEnvironmentConnectNotAuthorizedError\",\n  {\n    code: Schema.Literal(\"environment_connect_not_authorized\"),\n    // Optional so responses from relays deployed before the reason was\n    // threaded through still decode.\n    reason: Schema.optional(RelayEnvironmentConnectNotAuthorizedReason),\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 403 },\n) {\n  override get message(): string {\n    return this.reason\n      ? `Relay environment connection is not authorized: ${this.reason}`\n      : \"Relay environment connection is not authorized\";\n  }\n}\n\nexport class RelayEnvironmentEndpointUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointUnavailableError>()(\n  \"RelayEnvironmentEndpointUnavailableError\",\n  {\n    code: Schema.Literal(\"environment_endpoint_unavailable\"),\n    reason: RelayEnvironmentEndpointUnavailableReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 502 },\n) {\n  override get message(): string {\n    return `Relay environment endpoint is unavailable: ${this.reason}`;\n  }\n}\n\nexport class RelayEnvironmentEndpointTimedOutError extends Schema.TaggedErrorClass<RelayEnvironmentEndpointTimedOutError>()(\n  \"RelayEnvironmentEndpointTimedOutError\",\n  {\n    code: Schema.Literal(\"environment_endpoint_timed_out\"),\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 504 },\n) {\n  override get message(): string {\n    return \"Relay environment endpoint request timed out\";\n  }\n}\n\nexport class RelayEnvironmentLinkFailedError extends Schema.TaggedErrorClass<RelayEnvironmentLinkFailedError>()(\n  \"RelayEnvironmentLinkFailedError\",\n  {\n    code: Schema.Literal(\"environment_link_failed\"),\n    reason: RelayEnvironmentLinkFailedReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 500 },\n) {\n  override get message(): string {\n    return `Relay environment link failed: ${this.reason}`;\n  }\n}\n\nexport class RelayEnvironmentLinkUnavailableError extends Schema.TaggedErrorClass<RelayEnvironmentLinkUnavailableError>()(\n  \"RelayEnvironmentLinkUnavailableError\",\n  {\n    code: Schema.Literal(\"environment_link_unavailable\"),\n    reason: RelayEnvironmentLinkUnavailableReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 503 },\n) {\n  override get message(): string {\n    return `Relay environment link is unavailable: ${this.reason}`;\n  }\n}\n\nexport class RelayEnvironmentLinkLimitExceededError extends Schema.TaggedErrorClass<RelayEnvironmentLinkLimitExceededError>()(\n  \"RelayEnvironmentLinkLimitExceededError\",\n  {\n    code: Schema.Literal(\"environment_link_limit_exceeded\"),\n    maxTunnels: Schema.Number,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 403 },\n) {\n  override get message(): string {\n    return `Relay managed tunnel limit reached: this account allows at most ${this.maxTunnels} tunnels`;\n  }\n}\n\nexport class RelayAgentActivityPublishProofExpiredError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofExpiredError>()(\n  \"RelayAgentActivityPublishProofExpiredError\",\n  {\n    code: Schema.Literal(\"agent_activity_publish_proof_expired\"),\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  override get message(): string {\n    return \"Relay agent activity publish proof expired\";\n  }\n}\n\nexport class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErrorClass<RelayAgentActivityPublishProofInvalidError>()(\n  \"RelayAgentActivityPublishProofInvalidError\",\n  {\n    code: Schema.Literal(\"agent_activity_publish_proof_invalid\"),\n    reason: RelayAgentActivityPublishProofInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  override get message(): string {\n    return `Relay agent activity publish proof is invalid: ${this.reason}`;\n  }\n}\n\nexport class RelayInternalError extends Schema.TaggedErrorClass<RelayInternalError>()(\n  \"RelayInternalError\",\n  {\n    code: Schema.Literal(\"internal_error\"),\n    reason: RelayInternalErrorReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 500 },\n) {\n  override get message(): string {\n    return `Relay internal error: ${this.reason}`;\n  }\n}\n\nexport const RelayProtectedError = Schema.Union([\n  RelayAuthInvalidError,\n  RelayEnvironmentLinkProofExpiredError,\n  RelayEnvironmentLinkProofInvalidError,\n  RelayEnvironmentConnectNotAuthorizedError,\n  RelayEnvironmentEndpointUnavailableError,\n  RelayEnvironmentEndpointTimedOutError,\n  RelayEnvironmentLinkFailedError,\n  RelayEnvironmentLinkUnavailableError,\n  RelayEnvironmentLinkLimitExceededError,\n  RelayAgentActivityPublishProofExpiredError,\n  RelayAgentActivityPublishProofInvalidError,\n  RelayInternalError,\n]);\nexport type RelayProtectedError = typeof RelayProtectedError.Type;\n\nconst RelayAuthAndInternalErrors = [RelayAuthInvalidError, RelayInternalError] as const;\n\nconst RelayEnvironmentLinkErrors = [\n  RelayAuthInvalidError,\n  RelayEnvironmentLinkProofExpiredError,\n  RelayEnvironmentLinkProofInvalidError,\n  RelayEnvironmentLinkUnavailableError,\n  RelayEnvironmentLinkLimitExceededError,\n  RelayEnvironmentLinkFailedError,\n  RelayInternalError,\n] as const;\n\nconst RelayEnvironmentConnectErrors = [\n  RelayAuthInvalidError,\n  RelayEnvironmentConnectNotAuthorizedError,\n  RelayEnvironmentEndpointUnavailableError,\n  RelayEnvironmentEndpointTimedOutError,\n  RelayInternalError,\n] as const;\n\nconst RelayAgentActivityPublishErrors = [\n  RelayAuthInvalidError,\n  RelayAgentActivityPublishProofExpiredError,\n  RelayAgentActivityPublishProofInvalidError,\n  RelayInternalError,\n] as const;\n\nexport class RelayClientPrincipal extends Context.Service<\n  RelayClientPrincipal,\n  {\n    readonly userId: string;\n    readonly token: string;\n    readonly proofKeyThumbprint?: string;\n    readonly dpopScopes?: ReadonlyArray<RelayDpopAccessTokenScope>;\n  }\n>()(\"@t3tools/contracts/relay/RelayClientPrincipal\") {}\n\nexport class RelayEnvironmentPrincipal extends Context.Service<\n  RelayEnvironmentPrincipal,\n  {\n    readonly environmentId: string;\n    readonly environmentPublicKey: string;\n  }\n>()(\"@t3tools/contracts/relay/RelayEnvironmentPrincipal\") {}\n\nconst RelayClientBearerAuthorization = HttpApiSecurity.http({ scheme: \"bearer\" }).pipe(\n  HttpApiSecurity.annotate(\n    OpenApi.Description,\n    \"Clerk session or OAuth bearer token for the signed-in T3 Connect user.\",\n  ),\n);\n\nexport class RelayClientAuth extends HttpApiMiddleware.Service<\n  RelayClientAuth,\n  { provides: RelayClientPrincipal }\n>()(\"RelayClientAuth\", {\n  error: RelayAuthInvalidError,\n  security: { clientBearer: RelayClientBearerAuthorization },\n}) {}\n\nconst RelayEnvironmentBearerAuthorization = HttpApiSecurity.http({ scheme: \"bearer\" }).pipe(\n  HttpApiSecurity.annotate(\n    OpenApi.Description,\n    \"Relay-issued environment credential installed when the environment is linked.\",\n  ),\n);\n\nexport class RelayEnvironmentAuth extends HttpApiMiddleware.Service<\n  RelayEnvironmentAuth,\n  { provides: RelayEnvironmentPrincipal }\n>()(\"RelayEnvironmentAuth\", {\n  error: [RelayAuthInvalidError, RelayInternalError],\n  security: { environmentBearer: RelayEnvironmentBearerAuthorization },\n}) {}\n\nconst RelayDpopAuthorization = HttpApiSecurity.http({ scheme: \"DPoP\" }).pipe(\n  HttpApiSecurity.annotate(\n    OpenApi.Description,\n    \"DPoP-bound access token. Requests must also include the DPoP proof JWT header.\",\n  ),\n);\n\nexport class RelayDpopClientAuth extends HttpApiMiddleware.Service<\n  RelayDpopClientAuth,\n  { provides: RelayClientPrincipal }\n>()(\"RelayDpopClientAuth\", {\n  error: RelayAuthInvalidError,\n  security: { relayDpop: RelayDpopAuthorization },\n}) {}\n\nexport const RelayClientEnvironmentRecord = Schema.Struct({\n  environmentId: EnvironmentId,\n  label: TrimmedNonEmptyString,\n  endpoint: RelayManagedEndpoint,\n  linkedAt: TrimmedNonEmptyString,\n});\nexport type RelayClientEnvironmentRecord = typeof RelayClientEnvironmentRecord.Type;\n\nexport const RelayListEnvironmentsResponse = Schema.Struct({\n  environments: Schema.Array(RelayClientEnvironmentRecord),\n});\nexport type RelayListEnvironmentsResponse = typeof RelayListEnvironmentsResponse.Type;\n\nexport const RelayEnvironmentConnectRequest = Schema.Struct({\n  deviceId: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Optional client device identifier requesting the connection.\",\n    }),\n  ),\n  clientKeyThumbprint: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Deprecated alias for clientProofKeyThumbprint.\",\n    }),\n  ),\n  clientProofKeyThumbprint: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"JWK thumbprint that the minted environment credential must be bound to.\",\n    }),\n  ),\n}).annotate({ description: \"Requests a short-lived credential for connecting to an environment.\" });\nexport type RelayEnvironmentConnectRequest = typeof RelayEnvironmentConnectRequest.Type;\n\nexport const RelayEnvironmentConnectScope = \"environment:connect\" as const;\nexport const RelayEnvironmentStatusScope = \"environment:status\" as const;\nexport const RelayMobileRegistrationScope = \"mobile:registration\" as const;\nexport const RelayDpopAccessTokenScope = Schema.Literals([\n  RelayEnvironmentConnectScope,\n  RelayEnvironmentStatusScope,\n  RelayMobileRegistrationScope,\n]);\nexport type RelayDpopAccessTokenScope = typeof RelayDpopAccessTokenScope.Type;\n\nexport const RelayDpopTokenExchangeGrantType =\n  \"urn:ietf:params:oauth:grant-type:token-exchange\" as const;\nexport const RelayJwtSubjectTokenType = \"urn:ietf:params:oauth:token-type:jwt\" as const;\nexport const RelayAccessTokenType = \"urn:ietf:params:oauth:token-type:access_token\" as const;\nexport const RelayPublicClientId = Schema.Literals([\"t3-mobile\", \"t3-web\"]);\nexport type RelayPublicClientId = typeof RelayPublicClientId.Type;\nexport const RelayMobileClientId = \"t3-mobile\" as const;\nexport const RelayWebClientId = \"t3-web\" as const;\n\nexport const RelayDpopAccessTokenRequest = Schema.Struct({\n  grant_type: Schema.Literal(RelayDpopTokenExchangeGrantType),\n  subject_token: TrimmedNonEmptyString.annotate({\n    description: \"Clerk bearer token for the signed-in cloud user.\",\n  }),\n  subject_token_type: Schema.Literal(RelayJwtSubjectTokenType),\n  requested_token_type: Schema.Literal(RelayAccessTokenType),\n  resource: TrimmedNonEmptyString.annotate({\n    description: \"Relay issuer URL that will receive the DPoP-bound access token.\",\n  }),\n  scope: TrimmedNonEmptyString.annotate({\n    description: \"Space-separated relay scopes requested by the client.\",\n  }),\n  client_id: RelayPublicClientId,\n})\n  .annotate({ description: \"OAuth token exchange request for a DPoP-bound relay access token.\" })\n  .pipe(HttpApiSchema.asFormUrlEncoded());\nexport type RelayDpopAccessTokenRequest = typeof RelayDpopAccessTokenRequest.Type;\n\nexport const RelayDpopAccessTokenResponse = Schema.Struct({\n  access_token: TrimmedNonEmptyString,\n  issued_token_type: Schema.Literal(RelayAccessTokenType),\n  token_type: Schema.Literal(\"DPoP\"),\n  expires_in: Schema.Int.check(Schema.isGreaterThan(0)),\n  scope: TrimmedNonEmptyString,\n});\nexport type RelayDpopAccessTokenResponse = typeof RelayDpopAccessTokenResponse.Type;\n\nexport const RelayBearerRequestHeaders = Schema.Struct({\n  authorization: TrimmedNonEmptyString,\n});\n\nexport const RelayDpopProofRequestHeaders = Schema.Struct({\n  dpop: TrimmedNonEmptyString,\n});\n\nexport const RelayDpopRequestHeaders = Schema.Struct({\n  authorization: TrimmedNonEmptyString,\n  dpop: TrimmedNonEmptyString,\n});\n\nexport const RelayAuthorizationServerMetadata = Schema.Struct({\n  issuer: TrimmedNonEmptyString,\n  token_endpoint: TrimmedNonEmptyString,\n  grant_types_supported: Schema.Array(Schema.Literal(RelayDpopTokenExchangeGrantType)),\n  token_endpoint_auth_methods_supported: Schema.Array(Schema.Literal(\"none\")),\n  dpop_signing_alg_values_supported: Schema.Array(Schema.Literal(\"ES256\")),\n  scopes_supported: Schema.Array(RelayDpopAccessTokenScope),\n});\n\nexport const RelayProtectedResourceMetadata = Schema.Struct({\n  resource: TrimmedNonEmptyString,\n  authorization_servers: Schema.Array(TrimmedNonEmptyString),\n  scopes_supported: Schema.Array(RelayDpopAccessTokenScope),\n  dpop_bound_access_tokens_required: Schema.Boolean,\n  dpop_signing_alg_values_supported: Schema.Array(Schema.Literal(\"ES256\")),\n});\n\nexport const RelayEnvironmentUnlinkParams = Schema.Struct({\n  environmentId: EnvironmentId,\n});\nexport type RelayEnvironmentUnlinkParams = typeof RelayEnvironmentUnlinkParams.Type;\n\nexport const RelayEnvironmentConnectResponse = Schema.Struct({\n  environmentId: EnvironmentId,\n  endpoint: RelayManagedEndpoint,\n  credential: TrimmedNonEmptyString,\n  expiresAt: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentConnectResponse = typeof RelayEnvironmentConnectResponse.Type;\n\nexport const RelayEnvironmentStatusValue = Schema.Literals([\"online\", \"offline\"]);\nexport type RelayEnvironmentStatusValue = typeof RelayEnvironmentStatusValue.Type;\n\nexport const RelayEnvironmentStatusResponse = Schema.Struct({\n  environmentId: EnvironmentId,\n  endpoint: RelayManagedEndpoint,\n  status: RelayEnvironmentStatusValue,\n  checkedAt: TrimmedNonEmptyString,\n  descriptor: Schema.optional(ExecutionEnvironmentDescriptor),\n  error: Schema.optional(TrimmedNonEmptyString),\n  traceId: Schema.optional(TrimmedNonEmptyString),\n});\nexport type RelayEnvironmentStatusResponse = typeof RelayEnvironmentStatusResponse.Type;\n\nexport const RelayCloudMintCredentialProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  clientProofKeyThumbprint: TrimmedNonEmptyString,\n  cnf: Schema.Struct({\n    jkt: TrimmedNonEmptyString,\n  }),\n  deviceId: Schema.optional(TrimmedNonEmptyString),\n  nonce: TrimmedNonEmptyString,\n  scope: Schema.Array(Schema.Literal(\"environment:connect\")),\n});\nexport type RelayCloudMintCredentialProofPayload = typeof RelayCloudMintCredentialProofPayload.Type;\n\nexport const RelayCloudMintCredentialProof = TrimmedNonEmptyString;\nexport type RelayCloudMintCredentialProof = typeof RelayCloudMintCredentialProof.Type;\n\nexport const RelayCloudMintCredentialRequest = Schema.Struct({\n  proof: RelayCloudMintCredentialProof,\n});\nexport type RelayCloudMintCredentialRequest = typeof RelayCloudMintCredentialRequest.Type;\n\nexport const RelayCloudEnvironmentHealthProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  nonce: TrimmedNonEmptyString,\n  scope: Schema.Array(Schema.Literal(\"environment:status\")),\n});\nexport type RelayCloudEnvironmentHealthProofPayload =\n  typeof RelayCloudEnvironmentHealthProofPayload.Type;\n\nexport const RelayCloudEnvironmentHealthProof = TrimmedNonEmptyString;\nexport type RelayCloudEnvironmentHealthProof = typeof RelayCloudEnvironmentHealthProof.Type;\n\nexport const RelayCloudEnvironmentHealthRequest = Schema.Struct({\n  proof: RelayCloudEnvironmentHealthProof,\n});\nexport type RelayCloudEnvironmentHealthRequest = typeof RelayCloudEnvironmentHealthRequest.Type;\n\nexport const RelayEnvironmentHealthResponseProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  requestNonce: TrimmedNonEmptyString,\n  status: Schema.Literal(\"online\"),\n  descriptor: ExecutionEnvironmentDescriptor,\n  checkedAt: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentHealthResponseProofPayload =\n  typeof RelayEnvironmentHealthResponseProofPayload.Type;\n\nexport const RelayEnvironmentHealthResponse = Schema.Struct({\n  environmentId: EnvironmentId,\n  status: Schema.Literal(\"online\"),\n  descriptor: ExecutionEnvironmentDescriptor,\n  checkedAt: TrimmedNonEmptyString,\n  proof: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentHealthResponse = typeof RelayEnvironmentHealthResponse.Type;\n\nexport const RelayEnvironmentMintResponseProofPayload = Schema.Struct({\n  ...RelaySignedJwtRegisteredClaims,\n  environmentId: EnvironmentId,\n  clientProofKeyThumbprint: TrimmedNonEmptyString,\n  requestNonce: TrimmedNonEmptyString,\n  credential: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentMintResponseProofPayload =\n  typeof RelayEnvironmentMintResponseProofPayload.Type;\n\nexport const RelayEnvironmentMintResponse = Schema.Struct({\n  credential: TrimmedNonEmptyString,\n  expiresAt: TrimmedNonEmptyString,\n  proof: TrimmedNonEmptyString,\n});\nexport type RelayEnvironmentMintResponse = typeof RelayEnvironmentMintResponse.Type;\n\nexport const RelayDeliveryKind = Schema.Literals([\n  \"live_activity_start\",\n  \"live_activity_update\",\n  \"live_activity_end\",\n  \"push_notification\",\n]);\nexport type RelayDeliveryKind = typeof RelayDeliveryKind.Type;\n\nexport const RelayDeliveryResult = Schema.Struct({\n  deviceId: TrimmedNonEmptyString,\n  kind: RelayDeliveryKind,\n  ok: Schema.Boolean,\n  queued: Schema.optional(Schema.Boolean),\n  apnsStatus: Schema.NullOr(Schema.Number),\n  apnsReason: Schema.NullOr(Schema.String),\n  apnsId: Schema.NullOr(Schema.String),\n});\nexport type RelayDeliveryResult = typeof RelayDeliveryResult.Type;\n\nexport const RelayOkResponse = Schema.Struct({\n  ok: Schema.Boolean,\n});\nexport type RelayOkResponse = typeof RelayOkResponse.Type;\n\nexport const RelayPublishResponse = Schema.Struct({\n  ok: Schema.Boolean,\n  deliveries: Schema.Array(RelayDeliveryResult),\n});\nexport type RelayPublishResponse = typeof RelayPublishResponse.Type;\n\nexport const RelayHealthResponse = Schema.Struct({\n  ok: Schema.Boolean,\n  service: Schema.Literal(\"relay\"),\n});\nexport type RelayHealthResponse = typeof RelayHealthResponse.Type;\n\nexport const RelayHealthGroup = HttpApiGroup.make(\"health\")\n  .add(\n    HttpApiEndpoint.get(\"health\", \"/health\", {\n      success: RelayHealthResponse,\n      error: RelayInternalError,\n    }).annotate(OpenApi.Summary, \"Check relay health\"),\n  )\n  .annotate(OpenApi.Description, \"Service health and readiness.\");\n\nexport const RelayMetadataGroup = HttpApiGroup.make(\"metadata\")\n  .add(\n    HttpApiEndpoint.get(\"authorizationServer\", \"/.well-known/oauth-authorization-server\", {\n      success: RelayAuthorizationServerMetadata,\n    }).annotate(OpenApi.Summary, \"Read OAuth authorization-server metadata\"),\n    HttpApiEndpoint.get(\"protectedResource\", \"/.well-known/oauth-protected-resource\", {\n      success: RelayProtectedResourceMetadata,\n    }).annotate(OpenApi.Summary, \"Read OAuth protected-resource metadata\"),\n  )\n  .annotate(OpenApi.Description, \"OAuth and DPoP discovery metadata.\");\n\nexport const RelayRegisterDeviceEndpoint = HttpApiEndpoint.post(\n  \"registerDevice\",\n  \"/v1/mobile/devices\",\n  {\n    headers: RelayDpopRequestHeaders,\n    payload: RelayDeviceRegistrationRequest,\n    success: RelayOkResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n).annotate(OpenApi.Summary, \"Register or update a mobile device\");\n\nexport const RelayRegisterLiveActivityEndpoint = HttpApiEndpoint.post(\n  \"registerLiveActivity\",\n  \"/v1/mobile/live-activities\",\n  {\n    headers: RelayDpopRequestHeaders,\n    payload: RelayLiveActivityRegistrationRequest,\n    success: RelayOkResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n).annotate(OpenApi.Summary, \"Register a Live Activity push token\");\n\nexport const RelayAgentActivitySnapshotResponse = Schema.Struct({\n  aggregate: Schema.NullOr(RelayAgentActivityAggregateState),\n});\nexport type RelayAgentActivitySnapshotResponse = typeof RelayAgentActivitySnapshotResponse.Type;\n\n// Lets the app decide whether arming a Live Activity is worthwhile before\n// creating one (no empty lock-screen card when nothing is running) and seed\n// the card with the real aggregate instead of a placeholder.\nexport const RelayAgentActivitySnapshotEndpoint = HttpApiEndpoint.get(\n  \"getAgentActivitySnapshot\",\n  \"/v1/mobile/agent-activity\",\n  {\n    headers: RelayDpopRequestHeaders,\n    success: RelayAgentActivitySnapshotResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n).annotate(OpenApi.Summary, \"Read the current Live Activity aggregate\");\n\nexport const RelayUnregisterDeviceEndpoint = HttpApiEndpoint.delete(\n  \"unregisterDevice\",\n  \"/v1/mobile/devices/:deviceId\",\n  {\n    headers: RelayDpopRequestHeaders,\n    params: RelayDeviceUnregistrationParams,\n    success: RelayOkResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n).annotate(OpenApi.Summary, \"Unregister a mobile device\");\n\nexport const RelayMobileGroup = HttpApiGroup.make(\"mobile\")\n  .add(\n    RelayRegisterDeviceEndpoint,\n    RelayRegisterLiveActivityEndpoint,\n    RelayAgentActivitySnapshotEndpoint,\n    RelayUnregisterDeviceEndpoint,\n  )\n  .annotate(OpenApi.Description, \"Mobile push-notification and Live Activity registration.\")\n  .middleware(RelayDpopClientAuth);\n\nexport const RelayClientGroup = HttpApiGroup.make(\"client\")\n  .add(\n    HttpApiEndpoint.get(\"listEnvironments\", \"/v1/environments\", {\n      headers: RelayBearerRequestHeaders,\n      success: RelayListEnvironmentsResponse,\n      error: RelayAuthAndInternalErrors,\n    }).annotate(OpenApi.Summary, \"List linked environments\"),\n    HttpApiEndpoint.get(\"listDevices\", \"/v1/client/devices\", {\n      headers: RelayBearerRequestHeaders,\n      success: RelayListDevicesResponse,\n      error: RelayAuthAndInternalErrors,\n    }).annotate(OpenApi.Summary, \"List registered mobile devices\"),\n    HttpApiEndpoint.post(\"linkEnvironment\", \"/v1/client/environment-links\", {\n      headers: RelayBearerRequestHeaders,\n      payload: RelayEnvironmentLinkRequest,\n      success: RelayEnvironmentLinkResponse,\n      error: RelayEnvironmentLinkErrors,\n    }).annotate(OpenApi.Summary, \"Link an environment\"),\n    HttpApiEndpoint.post(\n      \"createEnvironmentLinkChallenge\",\n      \"/v1/client/environment-link-challenges\",\n      {\n        headers: RelayBearerRequestHeaders,\n        payload: RelayEnvironmentLinkChallengeRequest,\n        success: RelayEnvironmentLinkChallengeResponse,\n        error: RelayAuthAndInternalErrors,\n      },\n    ).annotate(OpenApi.Summary, \"Create an environment-link challenge\"),\n    HttpApiEndpoint.delete(\"unlinkEnvironment\", \"/v1/client/environment-links/:environmentId\", {\n      headers: RelayBearerRequestHeaders,\n      params: RelayEnvironmentUnlinkParams,\n      success: RelayOkResponse,\n      error: RelayAuthAndInternalErrors,\n    }).annotate(OpenApi.Summary, \"Unlink an environment\"),\n    HttpApiEndpoint.delete(\n      \"releaseEnvironmentTunnel\",\n      \"/v1/client/environment-links/:environmentId/tunnel\",\n      {\n        headers: RelayBearerRequestHeaders,\n        params: RelayEnvironmentUnlinkParams,\n        success: RelayOkResponse,\n        error: RelayAuthAndInternalErrors,\n      },\n    )\n      .annotate(OpenApi.Summary, \"Release an environment's managed tunnel\")\n      .annotate(\n        OpenApi.Description,\n        \"Deletes the provisioned Cloudflare tunnel while keeping the environment link and its hostname reservation, so a later link re-provisions the tunnel under the same URL. Environments call this when they shut down; Cloudflare bills per provisioned tunnel, so idle tunnels should not outlive their environment.\",\n      ),\n  )\n  .annotate(OpenApi.Description, \"Cloud-user environment links and registered devices.\")\n  .middleware(RelayClientAuth);\n\nexport const RelayExchangeDpopAccessTokenEndpoint = HttpApiEndpoint.post(\n  \"exchangeDpopAccessToken\",\n  \"/v1/client/dpop-token\",\n  {\n    headers: RelayDpopProofRequestHeaders,\n    payload: RelayDpopAccessTokenRequest,\n    success: RelayDpopAccessTokenResponse,\n    error: RelayAuthAndInternalErrors,\n  },\n)\n  .annotate(OpenApi.Summary, \"Exchange a Clerk token for a DPoP access token\")\n  .annotate(\n    OpenApi.Description,\n    \"Bootstrap endpoint. Send the DPoP proof JWT in the dpop header and the Clerk token in subject_token. The returned access token is bound to the proof key.\",\n  );\n\nexport const RelayTokenGroup = HttpApiGroup.make(\"token\")\n  .add(RelayExchangeDpopAccessTokenEndpoint)\n  .annotate(OpenApi.Description, \"OAuth token exchange for DPoP-bound client access.\");\n\nexport const RelayConnectEnvironmentEndpoint = HttpApiEndpoint.post(\n  \"connectEnvironment\",\n  \"/v1/environments/:environmentId/connect\",\n  {\n    headers: RelayDpopRequestHeaders,\n    params: Schema.Struct({\n      environmentId: EnvironmentId,\n    }),\n    payload: RelayEnvironmentConnectRequest,\n    success: RelayEnvironmentConnectResponse,\n    error: RelayEnvironmentConnectErrors,\n  },\n).annotate(OpenApi.Summary, \"Connect to an environment\");\n\nexport const RelayGetEnvironmentStatusEndpoint = HttpApiEndpoint.post(\n  \"getEnvironmentStatus\",\n  \"/v1/environments/:environmentId/status\",\n  {\n    headers: RelayDpopRequestHeaders,\n    params: Schema.Struct({\n      environmentId: EnvironmentId,\n    }),\n    success: RelayEnvironmentStatusResponse,\n    error: RelayEnvironmentConnectErrors,\n  },\n).annotate(OpenApi.Summary, \"Check environment status\");\n\nexport const RelayDpopClientGroup = HttpApiGroup.make(\"dpopClient\")\n  .add(RelayConnectEnvironmentEndpoint, RelayGetEnvironmentStatusEndpoint)\n  .annotate(OpenApi.Description, \"DPoP-authenticated client access to linked environments.\")\n  .middleware(RelayDpopClientAuth);\n\nexport const RelayServerGroup = HttpApiGroup.make(\"server\")\n  .add(\n    HttpApiEndpoint.post(\n      \"publishAgentActivity\",\n      \"/v1/environments/:environmentId/threads/:threadId/agent-activity\",\n      {\n        params: Schema.Struct({\n          environmentId: EnvironmentId,\n          threadId: ThreadId,\n        }),\n        payload: RelayAgentActivityPublishRequest,\n        success: RelayPublishResponse,\n        error: RelayAgentActivityPublishErrors,\n      },\n    ).annotate(OpenApi.Summary, \"Publish agent activity\"),\n  )\n  .annotate(OpenApi.Description, \"Environment-authenticated activity publication.\")\n  .middleware(RelayEnvironmentAuth);\n\nexport const RelayApi = HttpApi.make(\"RelayApi\")\n  .add(\n    RelayHealthGroup,\n    RelayMetadataGroup,\n    RelayMobileGroup,\n    RelayClientGroup,\n    RelayTokenGroup,\n    RelayDpopClientGroup,\n    RelayServerGroup,\n  )\n  .annotate(OpenApi.Title, \"Synaptic Code Relay API\")\n  .annotate(OpenApi.Version, \"1.0.0\")\n  .annotate(\n    OpenApi.Description,\n    \"Control-plane API for linking T3 environments, connecting authorized clients, and publishing agent activity.\",\n  );\nexport type RelayApi = typeof RelayApi;\n","import * as Context from \"effect/Context\";\nimport type * as DateTime from \"effect/DateTime\";\nimport * as Schema from \"effect/Schema\";\nimport * as HttpApi from \"effect/unstable/httpapi/HttpApi\";\nimport * as HttpApiEndpoint from \"effect/unstable/httpapi/HttpApiEndpoint\";\nimport * as HttpApiGroup from \"effect/unstable/httpapi/HttpApiGroup\";\nimport * as HttpApiMiddleware from \"effect/unstable/httpapi/HttpApiMiddleware\";\nimport * as HttpServerRespondable from \"effect/unstable/http/HttpServerRespondable\";\nimport * as HttpServerResponse from \"effect/unstable/http/HttpServerResponse\";\n\nimport {\n  AuthAccessTokenResult,\n  AuthBrowserSessionRequest,\n  AuthBrowserSessionResult,\n  AuthClientSession,\n  AuthCreatePairingCredentialInput,\n  AuthPairingCredentialResult,\n  AuthPairingLink,\n  AuthRevokeClientSessionInput,\n  AuthRevokePairingLinkInput,\n  AuthEnvironmentScope,\n  AuthTokenExchangeRequest,\n  AuthSessionState,\n  AuthWebSocketTicketResult,\n  ServerAuthSessionMethod,\n} from \"./auth.ts\";\nimport { AuthSessionId, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { ExecutionEnvironmentDescriptor } from \"./environment.ts\";\nimport {\n  ClientOrchestrationCommand,\n  DispatchResult,\n  OrchestrationReadModel,\n  OrchestrationShellSnapshot,\n  OrchestrationThreadDetailSnapshot,\n} from \"./orchestration.ts\";\nimport {\n  RelayCloudEnvironmentHealthRequest,\n  RelayCloudMintCredentialRequest,\n  RelayEnvironmentConfigRequest,\n  RelayEnvironmentHealthResponse,\n  RelayEnvironmentLinkProof,\n  RelayEnvironmentMintResponse,\n  RelayLinkProofRequest,\n} from \"./relay.ts\";\n\nconst OptionalBearerHeaders = Schema.Struct({\n  authorization: Schema.optionalKey(Schema.String),\n  dpop: Schema.optionalKey(Schema.String),\n});\n\nconst OptionalDpopProofHeaders = Schema.Struct({\n  dpop: Schema.optionalKey(Schema.String),\n});\n\nexport const EnvironmentRequestInvalidReason = Schema.Literals([\n  \"invalid_scope\",\n  \"scope_not_granted\",\n  \"invalid_command\",\n]);\nexport type EnvironmentRequestInvalidReason = typeof EnvironmentRequestInvalidReason.Type;\n\nexport const EnvironmentAuthInvalidReason = Schema.Literals([\n  \"missing_credential\",\n  \"invalid_credential\",\n]);\nexport type EnvironmentAuthInvalidReason = typeof EnvironmentAuthInvalidReason.Type;\n\nexport const EnvironmentOperationForbiddenReason = Schema.Literals([\n  \"current_session_revoke_not_allowed\",\n]);\nexport type EnvironmentOperationForbiddenReason = typeof EnvironmentOperationForbiddenReason.Type;\n\nexport const EnvironmentInternalErrorReason = Schema.Literals([\n  \"bootstrap_validation_failed\",\n  \"browser_session_issuance_failed\",\n  \"browser_session_cookie_failed\",\n  \"access_token_issuance_failed\",\n  \"websocket_ticket_issuance_failed\",\n  \"pairing_credential_issuance_failed\",\n  \"pairing_links_load_failed\",\n  \"pairing_link_revoke_failed\",\n  \"client_sessions_load_failed\",\n  \"client_session_revoke_failed\",\n  \"orchestration_snapshot_failed\",\n  \"orchestration_thread_snapshot_failed\",\n  \"orchestration_dispatch_failed\",\n  \"internal_error\",\n]);\nexport type EnvironmentInternalErrorReason = typeof EnvironmentInternalErrorReason.Type;\n\nexport class EnvironmentRequestInvalidError extends Schema.TaggedErrorClass<EnvironmentRequestInvalidError>()(\n  \"EnvironmentRequestInvalidError\",\n  {\n    code: Schema.Literal(\"invalid_request\"),\n    reason: EnvironmentRequestInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 400 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentRequestInvalidError)(this, { status: 400 });\n  }\n}\n\nexport class EnvironmentAuthInvalidError extends Schema.TaggedErrorClass<EnvironmentAuthInvalidError>()(\n  \"EnvironmentAuthInvalidError\",\n  {\n    code: Schema.Literal(\"auth_invalid\"),\n    reason: EnvironmentAuthInvalidReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 401 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentAuthInvalidError)(this, { status: 401 });\n  }\n}\n\nexport class EnvironmentScopeRequiredError extends Schema.TaggedErrorClass<EnvironmentScopeRequiredError>()(\n  \"EnvironmentScopeRequiredError\",\n  {\n    code: Schema.Literal(\"insufficient_scope\"),\n    requiredScope: AuthEnvironmentScope,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 403 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentScopeRequiredError)(this, { status: 403 });\n  }\n}\n\nexport class EnvironmentOperationForbiddenError extends Schema.TaggedErrorClass<EnvironmentOperationForbiddenError>()(\n  \"EnvironmentOperationForbiddenError\",\n  {\n    code: Schema.Literal(\"operation_forbidden\"),\n    reason: EnvironmentOperationForbiddenReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 403 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentOperationForbiddenError)(this, { status: 403 });\n  }\n}\n\nexport class EnvironmentInternalError extends Schema.TaggedErrorClass<EnvironmentInternalError>()(\n  \"EnvironmentInternalError\",\n  {\n    code: Schema.Literal(\"internal_error\"),\n    reason: EnvironmentInternalErrorReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 500 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentInternalError)(this, { status: 500 });\n  }\n}\n\nexport const EnvironmentResourceNotFoundReason = Schema.Literals([\"thread_not_found\"]);\nexport type EnvironmentResourceNotFoundReason = typeof EnvironmentResourceNotFoundReason.Type;\n\nexport class EnvironmentResourceNotFoundError extends Schema.TaggedErrorClass<EnvironmentResourceNotFoundError>()(\n  \"EnvironmentResourceNotFoundError\",\n  {\n    code: Schema.Literal(\"not_found\"),\n    reason: EnvironmentResourceNotFoundReason,\n    traceId: TrimmedNonEmptyString,\n  },\n  { httpApiStatus: 404 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentResourceNotFoundError)(this, { status: 404 });\n  }\n}\n\nexport const EnvironmentHttpCommonError = Schema.Union([\n  EnvironmentRequestInvalidError,\n  EnvironmentAuthInvalidError,\n  EnvironmentScopeRequiredError,\n  EnvironmentOperationForbiddenError,\n  EnvironmentResourceNotFoundError,\n  EnvironmentInternalError,\n]);\nexport type EnvironmentHttpCommonError = typeof EnvironmentHttpCommonError.Type;\n\nconst EnvironmentAuthenticationErrors = [\n  EnvironmentAuthInvalidError,\n  EnvironmentInternalError,\n] as const;\n\nexport class EnvironmentHttpBadRequestError extends Schema.TaggedErrorClass<EnvironmentHttpBadRequestError>()(\n  \"EnvironmentHttpBadRequestError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 400 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpBadRequestError)(this, { status: 400 });\n  }\n}\n\nexport class EnvironmentHttpUnauthorizedError extends Schema.TaggedErrorClass<EnvironmentHttpUnauthorizedError>()(\n  \"EnvironmentHttpUnauthorizedError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 401 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpUnauthorizedError)(this, { status: 401 });\n  }\n}\n\nexport class EnvironmentHttpForbiddenError extends Schema.TaggedErrorClass<EnvironmentHttpForbiddenError>()(\n  \"EnvironmentHttpForbiddenError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 403 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpForbiddenError)(this, { status: 403 });\n  }\n}\n\nexport class EnvironmentHttpInternalServerError extends Schema.TaggedErrorClass<EnvironmentHttpInternalServerError>()(\n  \"EnvironmentHttpInternalServerError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 500 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpInternalServerError)(this, { status: 500 });\n  }\n}\n\nexport class EnvironmentHttpConflictError extends Schema.TaggedErrorClass<EnvironmentHttpConflictError>()(\n  \"EnvironmentHttpConflictError\",\n  {\n    message: Schema.String,\n  },\n  { httpApiStatus: 409 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentHttpConflictError)(this, { status: 409 });\n  }\n}\n\nexport class EnvironmentCloudEndpointUnavailableError extends Schema.TaggedErrorClass<EnvironmentCloudEndpointUnavailableError>()(\n  \"EnvironmentCloudEndpointUnavailableError\",\n  {\n    message: Schema.String,\n    endpointRuntimeStatus: Schema.Unknown,\n  },\n  { httpApiStatus: 503 },\n) {\n  [HttpServerRespondable.symbol]() {\n    return HttpServerResponse.schemaJson(EnvironmentCloudEndpointUnavailableError)(this, {\n      status: 503,\n    });\n  }\n}\nconst EnvironmentSessionCreationErrors = [\n  EnvironmentAuthInvalidError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentTokenExchangeErrors = [\n  EnvironmentRequestInvalidError,\n  EnvironmentAuthInvalidError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentScopedOperationErrors = [\n  EnvironmentScopeRequiredError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentPairingCredentialErrors = [\n  EnvironmentRequestInvalidError,\n  ...EnvironmentScopedOperationErrors,\n] as const;\nconst EnvironmentSessionRevokeErrors = [\n  EnvironmentScopeRequiredError,\n  EnvironmentOperationForbiddenError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentOrchestrationSnapshotErrors = [\n  EnvironmentScopeRequiredError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentOrchestrationThreadSnapshotErrors = [\n  EnvironmentScopeRequiredError,\n  EnvironmentResourceNotFoundError,\n  EnvironmentInternalError,\n] as const;\nconst EnvironmentOrchestrationDispatchErrors = [\n  EnvironmentRequestInvalidError,\n  EnvironmentScopeRequiredError,\n  EnvironmentInternalError,\n] as const;\n\nexport interface EnvironmentSessionPrincipalShape {\n  readonly sessionId: AuthSessionId;\n  readonly subject: string;\n  readonly method: ServerAuthSessionMethod;\n  readonly scopes: ReadonlySet<AuthEnvironmentScope>;\n  readonly proofKeyThumbprint?: string;\n  readonly expiresAt?: DateTime.DateTime;\n}\n\nexport class EnvironmentAuthenticatedPrincipal extends Context.Service<\n  EnvironmentAuthenticatedPrincipal,\n  EnvironmentSessionPrincipalShape\n>()(\"@t3tools/contracts/environmentHttp/EnvironmentAuthenticatedPrincipal\") {}\n\nexport class EnvironmentAuthenticatedAuth extends HttpApiMiddleware.Service<\n  EnvironmentAuthenticatedAuth,\n  { provides: EnvironmentAuthenticatedPrincipal }\n>()(\"EnvironmentAuthenticatedAuth\", {\n  error: EnvironmentAuthenticationErrors,\n}) {}\n\nconst EnvironmentHttpCloudErrors = [\n  EnvironmentHttpBadRequestError,\n  EnvironmentHttpUnauthorizedError,\n  EnvironmentHttpForbiddenError,\n  EnvironmentHttpConflictError,\n  EnvironmentHttpInternalServerError,\n  EnvironmentScopeRequiredError,\n] as const;\n\nexport const EnvironmentCloudRelayConfigResult = Schema.Struct({\n  ok: Schema.Boolean,\n  endpointRuntimeStatus: Schema.Unknown,\n});\nexport type EnvironmentCloudRelayConfigResult = typeof EnvironmentCloudRelayConfigResult.Type;\n\nexport const EnvironmentCloudLinkStateResult = Schema.Struct({\n  linked: Schema.Boolean,\n  cloudUserId: Schema.NullOr(Schema.String),\n  relayUrl: Schema.NullOr(Schema.String),\n  relayIssuer: Schema.NullOr(Schema.String),\n  // A managed Cloudflare tunnel is provisioned for this link. False for a\n  // publish-only link (activity publishing without a relay-managed tunnel), so\n  // clients can present the two capabilities as independent settings.\n  // Optional so newer clients tolerate older environment servers.\n  managedTunnelActive: Schema.optional(Schema.Boolean),\n  publishAgentActivity: Schema.Boolean,\n});\nexport type EnvironmentCloudLinkStateResult = typeof EnvironmentCloudLinkStateResult.Type;\n\nexport const EnvironmentCloudPreferencesRequest = Schema.Struct({\n  publishAgentActivity: Schema.Boolean,\n});\nexport type EnvironmentCloudPreferencesRequest = typeof EnvironmentCloudPreferencesRequest.Type;\n\nexport const AuthPairingLinkRevokeResult = Schema.Struct({\n  revoked: Schema.Boolean,\n});\nexport type AuthPairingLinkRevokeResult = typeof AuthPairingLinkRevokeResult.Type;\n\nexport const AuthClientSessionRevokeResult = Schema.Struct({\n  revoked: Schema.Boolean,\n});\nexport type AuthClientSessionRevokeResult = typeof AuthClientSessionRevokeResult.Type;\n\nexport const AuthOtherClientSessionsRevokeResult = Schema.Struct({\n  revokedCount: Schema.Number,\n});\nexport type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;\n\nexport class EnvironmentMetadataHttpApi extends HttpApiGroup.make(\"metadata\").add(\n  HttpApiEndpoint.get(\"descriptor\", \"/.well-known/t3/environment\", {\n    success: ExecutionEnvironmentDescriptor,\n  }),\n) {}\n\nexport class EnvironmentAuthHttpApi extends HttpApiGroup.make(\"auth\")\n  .add(\n    HttpApiEndpoint.get(\"session\", \"/api/auth/session\", {\n      headers: OptionalBearerHeaders,\n      success: AuthSessionState,\n      error: [EnvironmentInternalError],\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"browserSession\", \"/api/auth/browser-session\", {\n      payload: AuthBrowserSessionRequest,\n      success: AuthBrowserSessionResult,\n      error: EnvironmentSessionCreationErrors,\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"token\", \"/oauth/token\", {\n      headers: OptionalDpopProofHeaders,\n      payload: AuthTokenExchangeRequest,\n      success: AuthAccessTokenResult,\n      error: EnvironmentTokenExchangeErrors,\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"webSocketTicket\", \"/api/auth/websocket-ticket\", {\n      headers: OptionalBearerHeaders,\n      success: AuthWebSocketTicketResult,\n      error: [EnvironmentInternalError],\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"pairingCredential\", \"/api/auth/pairing-token\", {\n      headers: OptionalBearerHeaders,\n      payload: AuthCreatePairingCredentialInput,\n      success: AuthPairingCredentialResult,\n      error: EnvironmentPairingCredentialErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"pairingLinks\", \"/api/auth/pairing-links\", {\n      headers: OptionalBearerHeaders,\n      success: Schema.Array(AuthPairingLink),\n      error: EnvironmentScopedOperationErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"revokePairingLink\", \"/api/auth/pairing-links/revoke\", {\n      headers: OptionalBearerHeaders,\n      payload: AuthRevokePairingLinkInput,\n      success: AuthPairingLinkRevokeResult,\n      error: EnvironmentScopedOperationErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"clients\", \"/api/auth/clients\", {\n      headers: OptionalBearerHeaders,\n      success: Schema.Array(AuthClientSession),\n      error: EnvironmentScopedOperationErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"revokeClient\", \"/api/auth/clients/revoke\", {\n      headers: OptionalBearerHeaders,\n      payload: AuthRevokeClientSessionInput,\n      success: AuthClientSessionRevokeResult,\n      error: EnvironmentSessionRevokeErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"revokeOtherClients\", \"/api/auth/clients/revoke-others\", {\n      headers: OptionalBearerHeaders,\n      success: AuthOtherClientSessionsRevokeResult,\n      error: EnvironmentScopedOperationErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  ) {}\n\nconst EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({\n  threadId: ThreadId,\n});\n\n// Query-string window for windowed thread snapshots (GET payloads must encode\n// to strings). Both fields optional: omitting them keeps the full-snapshot\n// behavior, so pagination stays opt-in per request.\nconst EnvironmentOrchestrationThreadSnapshotQuery = {\n  turnLimit: Schema.optional(\n    Schema.FiniteFromString.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1)),\n  ),\n  beforeCursor: Schema.optional(TrimmedNonEmptyString),\n};\n\nexport class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make(\"orchestration\")\n  .add(\n    HttpApiEndpoint.get(\"snapshot\", \"/api/orchestration/snapshot\", {\n      headers: OptionalBearerHeaders,\n      success: OrchestrationReadModel,\n      error: EnvironmentOrchestrationSnapshotErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"shellSnapshot\", \"/api/orchestration/shell\", {\n      headers: OptionalBearerHeaders,\n      success: OrchestrationShellSnapshot,\n      error: EnvironmentOrchestrationSnapshotErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"threadSnapshot\", \"/api/orchestration/threads/:threadId\", {\n      headers: OptionalBearerHeaders,\n      params: EnvironmentOrchestrationThreadSnapshotParams,\n      payload: EnvironmentOrchestrationThreadSnapshotQuery,\n      success: OrchestrationThreadDetailSnapshot,\n      error: EnvironmentOrchestrationThreadSnapshotErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"dispatch\", \"/api/orchestration/dispatch\", {\n      headers: OptionalBearerHeaders,\n      payload: ClientOrchestrationCommand,\n      success: DispatchResult,\n      error: EnvironmentOrchestrationDispatchErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  ) {}\n\nexport class EnvironmentConnectHttpApi extends HttpApiGroup.make(\"connect\")\n  .add(\n    HttpApiEndpoint.post(\"linkProof\", \"/api/connect/link-proof\", {\n      headers: OptionalBearerHeaders,\n      payload: RelayLinkProofRequest,\n      success: RelayEnvironmentLinkProof,\n      error: EnvironmentHttpCloudErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"relayConfig\", \"/api/connect/relay-config\", {\n      headers: OptionalBearerHeaders,\n      payload: RelayEnvironmentConfigRequest,\n      success: EnvironmentCloudRelayConfigResult,\n      error: [...EnvironmentHttpCloudErrors, EnvironmentCloudEndpointUnavailableError],\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.get(\"linkState\", \"/api/connect/link-state\", {\n      headers: OptionalBearerHeaders,\n      success: EnvironmentCloudLinkStateResult,\n      error: EnvironmentHttpCloudErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"unlink\", \"/api/connect/unlink\", {\n      headers: OptionalBearerHeaders,\n      success: EnvironmentCloudRelayConfigResult,\n      error: EnvironmentHttpCloudErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"preferences\", \"/api/connect/preferences\", {\n      headers: OptionalBearerHeaders,\n      payload: EnvironmentCloudPreferencesRequest,\n      success: EnvironmentCloudLinkStateResult,\n      error: EnvironmentHttpCloudErrors,\n    }).middleware(EnvironmentAuthenticatedAuth),\n  )\n  .add(\n    HttpApiEndpoint.post(\"health\", \"/api/t3-connect/health\", {\n      payload: RelayCloudEnvironmentHealthRequest,\n      success: RelayEnvironmentHealthResponse,\n      error: EnvironmentHttpCloudErrors,\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"mintCredential\", \"/api/connect/mint-credential\", {\n      payload: RelayCloudMintCredentialRequest,\n      success: RelayEnvironmentMintResponse,\n      error: EnvironmentHttpCloudErrors,\n    }),\n  )\n  .add(\n    HttpApiEndpoint.post(\"t3MintCredential\", \"/api/t3-connect/mint-credential\", {\n      payload: RelayCloudMintCredentialRequest,\n      success: RelayEnvironmentMintResponse,\n      error: EnvironmentHttpCloudErrors,\n    }),\n  ) {}\n\nexport class EnvironmentHttpApi extends HttpApi.make(\"environment\")\n  .add(EnvironmentMetadataHttpApi)\n  .add(EnvironmentAuthHttpApi)\n  .add(EnvironmentOrchestrationHttpApi)\n  .add(EnvironmentConnectHttpApi) {}\n","import * as Schema from \"effect/Schema\";\n\nexport const RelayClientStatusSchema = Schema.Union([\n  Schema.Struct({\n    status: Schema.Literal(\"available\"),\n    executablePath: Schema.String,\n    source: Schema.Literals([\"override\", \"managed\", \"path\"]),\n    version: Schema.String,\n  }),\n  Schema.Struct({\n    status: Schema.Literal(\"missing\"),\n    version: Schema.String,\n  }),\n  Schema.Struct({\n    status: Schema.Literal(\"unsupported\"),\n    platform: Schema.String,\n    arch: Schema.String,\n    version: Schema.String,\n  }),\n]);\nexport type RelayClientStatus = typeof RelayClientStatusSchema.Type;\n\nexport const RelayClientInstallProgressStageSchema = Schema.Literals([\n  \"checking\",\n  \"waiting_for_lock\",\n  \"downloading\",\n  \"verifying\",\n  \"installing\",\n  \"validating\",\n  \"activating\",\n]);\nexport type RelayClientInstallProgressStage = typeof RelayClientInstallProgressStageSchema.Type;\n\nexport const RelayClientInstallProgressEventSchema = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"progress\"),\n    stage: RelayClientInstallProgressStageSchema,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"complete\"),\n    status: RelayClientStatusSchema,\n  }),\n]);\nexport type RelayClientInstallProgressEvent = typeof RelayClientInstallProgressEventSchema.Type;\n\nexport const RelayClientInstallFailureReasonSchema = Schema.Literals([\n  \"download_failed\",\n  \"invalid_checksum\",\n  \"install_locked\",\n  \"override_missing\",\n  \"unsupported_platform\",\n  \"validation_failed\",\n  \"write_failed\",\n]);\nexport type RelayClientInstallFailureReason = typeof RelayClientInstallFailureReasonSchema.Type;\n\nexport class RelayClientInstallFailedError extends Schema.TaggedErrorClass<RelayClientInstallFailedError>()(\n  \"RelayClientInstallFailedError\",\n  {\n    reason: RelayClientInstallFailureReasonSchema,\n    message: Schema.String,\n  },\n) {}\n","import * as Schema from \"effect/Schema\";\n\nimport { PortSchema, PositiveInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const DesktopBackendBootstrap = Schema.Struct({\n  mode: Schema.Literal(\"desktop\"),\n  noBrowser: Schema.Boolean,\n  port: PortSchema,\n  // Omitted when the desktop launches the backend inside WSL, since the\n  // Windows-side baseDir maps to /mnt/c/... and the Linux side should use its\n  // own home directory instead.\n  t3Home: Schema.optional(Schema.String),\n  host: Schema.String,\n  desktopBootstrapToken: Schema.String,\n  tailscaleServeEnabled: Schema.Boolean,\n  tailscaleServePort: PortSchema,\n  otlpTracesUrl: Schema.optional(Schema.String),\n  otlpMetricsUrl: Schema.optional(Schema.String),\n  desktopTelemetryFd: Schema.optionalKey(PositiveInt),\n  desktopTelemetryControlFd: Schema.optionalKey(PositiveInt),\n  resourceMonitorPath: Schema.optionalKey(TrimmedNonEmptyString),\n});\n\nexport type DesktopBackendBootstrap = typeof DesktopBackendBootstrap.Type;\n","import * as Schema from \"effect/Schema\";\n\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const AdvertisedEndpointProviderKind = Schema.Literals([\n  \"core\",\n  \"private-network\",\n  \"tunnel\",\n  \"manual\",\n]);\nexport type AdvertisedEndpointProviderKind = typeof AdvertisedEndpointProviderKind.Type;\n\nexport const AdvertisedEndpointReachability = Schema.Literals([\n  \"loopback\",\n  \"lan\",\n  \"private-network\",\n  \"public\",\n]);\nexport type AdvertisedEndpointReachability = typeof AdvertisedEndpointReachability.Type;\n\nexport const AdvertisedEndpointHostedHttpsCompatibility = Schema.Literals([\n  \"compatible\",\n  \"mixed-content-blocked\",\n  \"requires-configuration\",\n  \"unknown\",\n]);\nexport type AdvertisedEndpointHostedHttpsCompatibility =\n  typeof AdvertisedEndpointHostedHttpsCompatibility.Type;\n\nexport const AdvertisedEndpointStatus = Schema.Literals([\"available\", \"unavailable\", \"unknown\"]);\nexport type AdvertisedEndpointStatus = typeof AdvertisedEndpointStatus.Type;\n\nexport const AdvertisedEndpointSource = Schema.Literals([\n  \"desktop-core\",\n  \"desktop-addon\",\n  \"server\",\n  \"user\",\n]);\nexport type AdvertisedEndpointSource = typeof AdvertisedEndpointSource.Type;\n\nexport const AdvertisedEndpointProvider = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  kind: AdvertisedEndpointProviderKind,\n  isAddon: Schema.Boolean,\n});\nexport type AdvertisedEndpointProvider = typeof AdvertisedEndpointProvider.Type;\n\nexport const AdvertisedEndpointCompatibility = Schema.Struct({\n  hostedHttpsApp: AdvertisedEndpointHostedHttpsCompatibility,\n  desktopApp: Schema.Literals([\"compatible\", \"unknown\"]),\n});\nexport type AdvertisedEndpointCompatibility = typeof AdvertisedEndpointCompatibility.Type;\n\nexport const AdvertisedEndpoint = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  label: TrimmedNonEmptyString,\n  provider: AdvertisedEndpointProvider,\n  httpBaseUrl: TrimmedNonEmptyString,\n  wsBaseUrl: TrimmedNonEmptyString,\n  reachability: AdvertisedEndpointReachability,\n  compatibility: AdvertisedEndpointCompatibility,\n  source: AdvertisedEndpointSource,\n  status: AdvertisedEndpointStatus,\n  isDefault: Schema.optional(Schema.Boolean),\n  description: Schema.optional(TrimmedNonEmptyString),\n});\nexport type AdvertisedEndpoint = typeof AdvertisedEndpoint.Type;\n","/**\n * Preview - Schemas for the in-app browser preview surface.\n *\n * The preview is desktop-only (Chromium <webview>); the server tracks per-thread\n * tab metadata so it survives client reconnects and multi-window. The desktop\n * renderer mediates: it owns the actual <webview> and reports navigation back to\n * the server via these RPCs, the server fans events to all subscribers.\n *\n * @module Preview\n */\nimport { Schema } from \"effect\";\nimport { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nconst Url = TrimmedNonEmptyString.check(Schema.isMaxLength(2048));\nconst Title = Schema.String.check(Schema.isMaxLength(512));\n\nexport const PreviewTabId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));\nexport type PreviewTabId = typeof PreviewTabId.Type;\n\nexport const PREVIEW_VIEWPORT_MIN_DIMENSION = 240;\nexport const PREVIEW_VIEWPORT_MAX_DIMENSION = 3840;\nexport const PREVIEW_VIEWPORT_MAX_AREA = 3840 * 2160;\n\nconst PreviewViewportDimension = Schema.Int.check(\n  Schema.isBetween({\n    minimum: PREVIEW_VIEWPORT_MIN_DIMENSION,\n    maximum: PREVIEW_VIEWPORT_MAX_DIMENSION,\n  }),\n);\n\nconst viewportAreaFilter = Schema.makeFilter(\n  ({ width, height }: { readonly width: number; readonly height: number }) =>\n    width * height <= PREVIEW_VIEWPORT_MAX_AREA ||\n    `Viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`,\n);\n\nexport const PreviewViewportSize = Schema.Struct({\n  width: PreviewViewportDimension,\n  height: PreviewViewportDimension,\n}).check(viewportAreaFilter);\nexport type PreviewViewportSize = typeof PreviewViewportSize.Type;\n\n/**\n * The page's measured viewport can be smaller than the minimum selectable\n * fixed size while fill mode follows a narrow panel. Keep measurement\n * validation separate from the stricter user-selectable size constraints.\n */\nexport const PreviewRenderedViewportSize = Schema.Struct({\n  width: Schema.Int.check(Schema.isGreaterThan(0)),\n  height: Schema.Int.check(Schema.isGreaterThan(0)),\n});\nexport type PreviewRenderedViewportSize = typeof PreviewRenderedViewportSize.Type;\n\nexport const PREVIEW_VIEWPORT_PRESET_IDS = [\n  \"iphone-se\",\n  \"iphone-xr\",\n  \"iphone-12-pro\",\n  \"iphone-14-pro-max\",\n  \"pixel-7\",\n  \"samsung-galaxy-s8-plus\",\n  \"samsung-galaxy-s20-ultra\",\n  \"ipad-mini\",\n  \"ipad-air\",\n  \"ipad-pro\",\n  \"surface-pro-7\",\n  \"surface-duo\",\n  \"galaxy-z-fold-5\",\n  \"asus-zenbook-fold\",\n  \"samsung-galaxy-a51-71\",\n  \"nest-hub\",\n  \"nest-hub-max\",\n] as const;\n\nexport const PreviewViewportPresetId = Schema.Literals(PREVIEW_VIEWPORT_PRESET_IDS);\nexport type PreviewViewportPresetId = typeof PreviewViewportPresetId.Type;\n\n/**\n * Preset IDs shipped before the Chrome-compatible catalog. Existing sessions\n * can still reconnect with these values, but new resize requests only expose\n * PREVIEW_VIEWPORT_PRESET_IDS.\n */\nconst LEGACY_PREVIEW_VIEWPORT_PRESET_IDS = [\n  \"desktop-1920x1080\",\n  \"desktop-1440x900\",\n  \"laptop-1366x768\",\n  \"laptop-1280x800\",\n  \"ipad-pro-11\",\n  \"iphone-15-pro\",\n  \"pixel-8\",\n  \"galaxy-s24\",\n] as const;\n\nconst StoredPreviewViewportPresetId = Schema.Literals([\n  ...PREVIEW_VIEWPORT_PRESET_IDS,\n  ...LEGACY_PREVIEW_VIEWPORT_PRESET_IDS,\n]);\n\nexport const PreviewViewportSetting = Schema.Union([\n  Schema.TaggedStruct(\"fill\", {}),\n  Schema.TaggedStruct(\"freeform\", {\n    ...PreviewViewportSize.fields,\n  }).check(viewportAreaFilter),\n  Schema.TaggedStruct(\"preset\", {\n    ...PreviewViewportSize.fields,\n    presetId: StoredPreviewViewportPresetId,\n  }).check(viewportAreaFilter),\n]);\nexport type PreviewViewportSetting = typeof PreviewViewportSetting.Type;\n\nexport const FILL_PREVIEW_VIEWPORT = {\n  _tag: \"fill\",\n} as const satisfies PreviewViewportSetting;\n\nexport const PreviewNavStatus = Schema.Union([\n  Schema.TaggedStruct(\"Idle\", {}),\n  Schema.TaggedStruct(\"Loading\", {\n    url: Url,\n    title: Title,\n  }),\n  Schema.TaggedStruct(\"Success\", {\n    url: Url,\n    title: Title,\n  }),\n  Schema.TaggedStruct(\"LoadFailed\", {\n    url: Url,\n    title: Title,\n    code: Schema.Int,\n    description: Schema.String,\n  }),\n]);\nexport type PreviewNavStatus = typeof PreviewNavStatus.Type;\n\nexport const PreviewSessionSnapshot = Schema.Struct({\n  threadId: TrimmedNonEmptyString,\n  tabId: PreviewTabId,\n  navStatus: PreviewNavStatus,\n  canGoBack: Schema.Boolean,\n  canGoForward: Schema.Boolean,\n  /** Missing snapshots from older servers are treated as fill-panel mode. */\n  viewport: Schema.optional(PreviewViewportSetting),\n  updatedAt: Schema.String,\n});\nexport type PreviewSessionSnapshot = typeof PreviewSessionSnapshot.Type;\n\nexport const PreviewOpenInput = Schema.Struct({\n  threadId: ThreadId,\n  /** Omit to create an empty (Idle) tab the user can type into. */\n  url: Schema.optional(Url),\n});\nexport type PreviewOpenInput = typeof PreviewOpenInput.Type;\n\nexport const PreviewNavigateInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: PreviewTabId,\n  url: Url,\n  resolvedTitle: Schema.optional(Title),\n});\nexport type PreviewNavigateInput = typeof PreviewNavigateInput.Type;\n\nexport const PreviewReportStatusInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: PreviewTabId,\n  navStatus: PreviewNavStatus,\n  canGoBack: Schema.Boolean,\n  canGoForward: Schema.Boolean,\n});\nexport type PreviewReportStatusInput = typeof PreviewReportStatusInput.Type;\n\nexport const PreviewRefreshInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: PreviewTabId,\n});\nexport type PreviewRefreshInput = typeof PreviewRefreshInput.Type;\n\nexport const PreviewResizeInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: PreviewTabId,\n  viewport: PreviewViewportSetting,\n});\nexport type PreviewResizeInput = typeof PreviewResizeInput.Type;\n\nexport const PreviewCloseInput = Schema.Struct({\n  threadId: ThreadId,\n  tabId: Schema.optional(PreviewTabId),\n});\nexport type PreviewCloseInput = typeof PreviewCloseInput.Type;\n\nexport const PreviewListInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type PreviewListInput = typeof PreviewListInput.Type;\n\nexport const PreviewListResult = Schema.Struct({\n  sessions: Schema.Array(PreviewSessionSnapshot),\n  /** Identifies the current server process so revision resets are safe. */\n  serverEpoch: TrimmedNonEmptyString,\n  /** Monotonic server state revision used to reject stale list responses. */\n  revision: NonNegativeInt,\n});\nexport type PreviewListResult = typeof PreviewListResult.Type;\n\nconst PreviewEventBaseSchema = Schema.Struct({\n  threadId: TrimmedNonEmptyString,\n  tabId: PreviewTabId,\n  createdAt: Schema.String,\n  /** Identifies the server process that emitted this event. */\n  serverEpoch: TrimmedNonEmptyString,\n  /** Monotonic server state revision shared with PreviewListResult. */\n  revision: PositiveInt,\n});\n\nconst PreviewOpenedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"opened\"),\n  snapshot: PreviewSessionSnapshot,\n});\n\nconst PreviewNavigatedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"navigated\"),\n  snapshot: PreviewSessionSnapshot,\n});\n\nconst PreviewResizedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"resized\"),\n  snapshot: PreviewSessionSnapshot,\n});\n\nconst PreviewFailedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"failed\"),\n  url: Url,\n  title: Title,\n  code: Schema.Int,\n  description: Schema.String,\n});\n\nconst PreviewClosedEvent = Schema.Struct({\n  ...PreviewEventBaseSchema.fields,\n  type: Schema.Literal(\"closed\"),\n});\n\nexport const PreviewEvent = Schema.Union([\n  PreviewOpenedEvent,\n  PreviewNavigatedEvent,\n  PreviewResizedEvent,\n  PreviewFailedEvent,\n  PreviewClosedEvent,\n]);\nexport type PreviewEvent = typeof PreviewEvent.Type;\n\n/**\n * A localhost server detected by the port scanner. Used to populate the\n * \"Local\" recommendations in the empty-state of the preview panel.\n */\nexport const DiscoveredLocalServer = Schema.Struct({\n  host: TrimmedNonEmptyString,\n  port: Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThan(65536)),\n  url: Url,\n  processName: Schema.NullOr(TrimmedNonEmptyString),\n  pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),\n  terminal: Schema.NullOr(\n    Schema.Struct({\n      threadId: ThreadId,\n      terminalId: TrimmedNonEmptyString,\n    }),\n  ),\n});\nexport type DiscoveredLocalServer = typeof DiscoveredLocalServer.Type;\n\nexport const DiscoveredLocalServerList = Schema.Struct({\n  servers: Schema.Array(DiscoveredLocalServer),\n  scannedAt: Schema.String,\n});\nexport type DiscoveredLocalServerList = typeof DiscoveredLocalServerList.Type;\n\nexport class PreviewSessionLookupError extends Schema.TaggedErrorClass<PreviewSessionLookupError>()(\n  \"PreviewSessionLookupError\",\n  {\n    threadId: Schema.String,\n    tabId: Schema.String,\n  },\n) {\n  override get message() {\n    return `Unknown preview session: thread=${this.threadId}, tab=${this.tabId}`;\n  }\n}\n\nexport class PreviewInvalidUrlError extends Schema.TaggedErrorClass<PreviewInvalidUrlError>()(\n  \"PreviewInvalidUrlError\",\n  {\n    inputLength: Schema.Number,\n    reason: Schema.Literals([\"empty\", \"parse\", \"unsupported-protocol\", \"unexpected\"]),\n    protocol: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    const protocol = this.protocol === undefined ? \"\" : `: ${this.protocol}`;\n    return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;\n  }\n}\n\nexport const PreviewError = Schema.Union([PreviewSessionLookupError, PreviewInvalidUrlError]);\nexport type PreviewError = typeof PreviewError.Type;\n","import { Schema } from \"effect\";\n\nimport { EnvironmentId, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport {\n  PREVIEW_VIEWPORT_MAX_AREA,\n  PreviewRenderedViewportSize,\n  PreviewTabId,\n  PreviewViewportPresetId,\n  PreviewViewportSetting,\n  PreviewViewportSize,\n} from \"./preview.ts\";\nimport { ProviderInstanceId } from \"./providerInstance.ts\";\n\nconst BoundedUrl = Schema.String.check(Schema.isTrimmed())\n  .check(Schema.isNonEmpty())\n  .check(Schema.isMaxLength(2048));\nconst URL_GUIDANCE =\n  \"Absolute http(s) URL or a schemeless host such as t3.chat or localhost:5173. Schemeless public hosts use https; loopback hosts use http.\";\nconst OptionalTimeoutMs = Schema.optional(\n  Schema.Int.check(Schema.isGreaterThan(0))\n    .check(Schema.isLessThanOrEqualTo(60_000))\n    .annotate({ description: \"Maximum wait in milliseconds. Defaults to 15000; maximum 60000.\" }),\n).annotate({ description: \"Maximum wait in milliseconds. Defaults to 15000; maximum 60000.\" });\n\n/** Operations understood by desktop hosts predating viewport resizing. */\nexport const PREVIEW_AUTOMATION_V1_OPERATIONS = [\n  \"status\",\n  \"open\",\n  \"navigate\",\n  \"snapshot\",\n  \"click\",\n  \"type\",\n  \"press\",\n  \"scroll\",\n  \"evaluate\",\n  \"waitFor\",\n  \"recordingStart\",\n  \"recordingStop\",\n] as const;\n\n/** Advertised by current desktop hosts for mixed-version routing. */\nexport const PREVIEW_AUTOMATION_OPERATIONS = [\n  ...PREVIEW_AUTOMATION_V1_OPERATIONS,\n  \"resize\",\n  \"setColorScheme\",\n] as const;\n\nexport const PreviewAutomationOperation = Schema.Literals(PREVIEW_AUTOMATION_OPERATIONS);\nexport type PreviewAutomationOperation = typeof PreviewAutomationOperation.Type;\n\nconst PreviewAutomationTabTargetFields = {\n  tabId: Schema.optional(\n    PreviewTabId.annotate({\n      description:\n        \"Exact collaborative browser tab to target. Omit to use this agent session's current tab.\",\n    }),\n  ).annotate({\n    description:\n      \"Exact collaborative browser tab to target. Omit to use this agent session's current tab.\",\n  }),\n};\n\nexport const PreviewAutomationTabTargetInput = Schema.Struct(PreviewAutomationTabTargetFields);\nexport type PreviewAutomationTabTargetInput = typeof PreviewAutomationTabTargetInput.Type;\n\nexport const PreviewAutomationStatus = Schema.Struct({\n  available: Schema.Boolean,\n  visible: Schema.Boolean,\n  tabId: Schema.NullOr(PreviewTabId),\n  url: Schema.NullOr(Schema.String),\n  title: Schema.NullOr(Schema.String),\n  loading: Schema.Boolean,\n  /** Optional for compatibility with desktop hosts predating viewport sizing. */\n  viewportSetting: Schema.optional(PreviewViewportSetting),\n  /** Measured guest-page viewport in CSS pixels when a webview is ready. */\n  viewport: Schema.optional(PreviewRenderedViewportSize),\n});\nexport type PreviewAutomationStatus = typeof PreviewAutomationStatus.Type;\n\nexport const PreviewAutomationOpenInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  url: Schema.optional(BoundedUrl).annotate({\n    description: `Optional initial page URL. ${URL_GUIDANCE} Omit to open a blank tab.`,\n  }),\n  open: Schema.optional(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether to open the thread-bound inline preview for the human. Defaults to true; set false for background-only automation.\",\n    }),\n  ),\n  show: Schema.optional(\n    Schema.Boolean.annotate({\n      description:\n        \"Deprecated alias for open. Whether to reveal the thread-bound inline preview to the human.\",\n    }),\n  ),\n  reuseExistingTab: Schema.optional(\n    Schema.Boolean.annotate({\n      description:\n        \"Reuse tabId when supplied, otherwise this agent session's current tab. Defaults to true; set false to create a new tab.\",\n    }),\n  ),\n})\n  .check(\n    Schema.makeFilter(\n      (input) =>\n        !(input.tabId !== undefined && input.reuseExistingTab === false) ||\n        \"tabId cannot be combined with reuseExistingTab=false.\",\n    ),\n  )\n  .annotate({\n    description:\n      \"Opens the collaborative browser for the current thread. Use preview_navigate afterward when readiness waiting matters.\",\n  });\nexport type PreviewAutomationOpenInput = typeof PreviewAutomationOpenInput.Type;\n\nexport const BrowserNavigationTarget = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"url\").annotate({\n      description: \"Selects direct URL navigation.\",\n    }),\n    url: BoundedUrl.annotate({\n      description: `Direct website URL. ${URL_GUIDANCE}`,\n    }),\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"environment-port\").annotate({\n      description: \"Selects a dev-server port relative to the current execution environment.\",\n    }),\n    port: Schema.Int.check(Schema.isGreaterThan(0))\n      .check(Schema.isLessThan(65_536))\n      .annotate({ description: \"Dev-server TCP port inside the current environment.\" }),\n    protocol: Schema.optional(\n      Schema.Literals([\"http\", \"https\"]).annotate({\n        description: \"Dev-server protocol. Defaults to http.\",\n      }),\n    ),\n    path: Schema.optional(\n      Schema.String.annotate({\n        description: \"Optional path, query, and fragment, for example /settings?tab=account.\",\n      }),\n    ),\n  }),\n]);\nexport type BrowserNavigationTarget = typeof BrowserNavigationTarget.Type;\n\nexport const PreviewAutomationNavigateInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  url: Schema.optional(BoundedUrl).annotate({\n    description: `Website URL. ${URL_GUIDANCE} Use this for public pages and directly reachable URLs.`,\n  }),\n  target: Schema.optional(\n    BrowserNavigationTarget.annotate({\n      description:\n        \"Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.\",\n    }),\n  ).annotate({\n    description:\n      \"Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.\",\n  }),\n  readiness: Schema.optional(\n    Schema.Literals([\"load\", \"domContentLoaded\", \"none\"]).annotate({\n      description:\n        \"Readiness milestone before returning. 'load' waits for loading to stop (default), 'domContentLoaded' waits for an interactive document, and 'none' returns immediately.\",\n    }),\n  ).annotate({\n    description:\n      \"Readiness milestone before returning. 'load' is the default; use 'none' only when a later wait call will verify the page.\",\n  }),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter(\n      (input) =>\n        Number(input.url !== undefined) + Number(input.target !== undefined) === 1 ||\n        \"Provide exactly one of url or target.\",\n    ),\n  )\n  .annotate({\n    description:\n      \"Navigates the active browser tab. Provide exactly one of url or target; for most public pages use url.\",\n  });\nexport type PreviewAutomationNavigateInput = typeof PreviewAutomationNavigateInput.Type;\n\nexport const PreviewAutomationResizeInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  mode: Schema.Literals([\"fill\", \"freeform\", \"preset\"]).annotate({\n    description:\n      \"Viewport mode: fill follows the preview panel, freeform uses exact independently resizable dimensions, and preset uses a named device size.\",\n  }),\n  preset: Schema.optional(\n    PreviewViewportPresetId.annotate({\n      description: \"Named viewport from Chrome DevTools' standard device catalog.\",\n    }),\n  ).annotate({\n    description: \"Named device size. Required only when mode is preset.\",\n  }),\n  width: Schema.optional(\n    PreviewViewportSize.fields.width.annotate({\n      description: \"Freeform viewport width in CSS pixels. Required only in freeform mode.\",\n    }),\n  ).annotate({\n    description: \"Freeform viewport width in CSS pixels. Required only in freeform mode.\",\n  }),\n  height: Schema.optional(\n    PreviewViewportSize.fields.height.annotate({\n      description: \"Freeform viewport height in CSS pixels. Required only in freeform mode.\",\n    }),\n  ).annotate({\n    description: \"Freeform viewport height in CSS pixels. Required only in freeform mode.\",\n  }),\n  orientation: Schema.optional(\n    Schema.Literals([\"portrait\", \"landscape\"]).annotate({\n      description:\n        \"Orientation for a fixed device preset. Defaults to the preset's native orientation.\",\n    }),\n  ).annotate({\n    description:\n      \"Orientation for a named device preset. It is not accepted in fill or freeform mode.\",\n  }),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter((input) => {\n      const hasPreset = input.preset !== undefined;\n      const hasWidth = input.width !== undefined;\n      const hasHeight = input.height !== undefined;\n      if (hasWidth !== hasHeight) return \"Custom dimensions require both width and height.\";\n      if (input.mode === \"fill\") {\n        return !hasPreset && !hasWidth && input.orientation === undefined\n          ? true\n          : \"Fill mode does not accept a preset, dimensions, or orientation.\";\n      }\n      if (input.mode === \"freeform\") {\n        if (!hasWidth || !hasHeight || hasPreset || input.orientation !== undefined) {\n          return \"Freeform mode requires width and height and does not accept a preset or orientation.\";\n        }\n      } else if (!hasPreset || hasWidth || hasHeight) {\n        return \"Preset mode requires a preset and does not accept custom dimensions.\";\n      }\n      if (hasWidth && hasHeight && input.width! * input.height! > PREVIEW_VIEWPORT_MAX_AREA) {\n        return `Custom viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`;\n      }\n      return true;\n    }),\n  )\n  .annotate({\n    description:\n      \"Sets the active browser tab to fill-panel, independently resizable freeform, or named device-preset sizing.\",\n  });\nexport type PreviewAutomationResizeInput = typeof PreviewAutomationResizeInput.Type;\n\nexport const PreviewAutomationResizeResult = Schema.Struct({\n  tabId: PreviewTabId,\n  setting: PreviewViewportSetting,\n  viewport: PreviewRenderedViewportSize,\n});\nexport type PreviewAutomationResizeResult = typeof PreviewAutomationResizeResult.Type;\n\n/** Mirrors DesktopPreviewColorScheme; declared here to keep this module free of ipc.ts imports. */\nexport const PreviewAutomationColorScheme = Schema.Literals([\"system\", \"light\", \"dark\"]);\nexport type PreviewAutomationColorScheme = typeof PreviewAutomationColorScheme.Type;\n\nexport const PreviewAutomationSetColorSchemeInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  colorScheme: PreviewAutomationColorScheme.annotate({\n    description:\n      \"Emulated prefers-color-scheme for the page: light, dark, or system to follow the OS appearance.\",\n  }),\n}).annotate({\n  description:\n    \"Emulates prefers-color-scheme in the active browser tab without changing the OS or app theme.\",\n});\nexport type PreviewAutomationSetColorSchemeInput = typeof PreviewAutomationSetColorSchemeInput.Type;\n\nexport const PreviewAutomationSetColorSchemeResult = Schema.Struct({\n  tabId: PreviewTabId,\n  colorScheme: PreviewAutomationColorScheme,\n});\nexport type PreviewAutomationSetColorSchemeResult =\n  typeof PreviewAutomationSetColorSchemeResult.Type;\n\nconst Locator = TrimmedNonEmptyString.annotate({\n  description:\n    \"Playwright selector, preferably role/text based, for example role=button[name='Send'] or text=Continue. Use snapshot first to inspect the page.\",\n});\n\nconst LegacySelector = TrimmedNonEmptyString.annotate({\n  description:\n    \"Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.\",\n});\n\nexport const PreviewAutomationClickInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  selector: Schema.optional(LegacySelector).annotate({\n    description:\n      \"Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.\",\n  }),\n  locator: Schema.optional(Locator).annotate({\n    description:\n      \"Playwright selector, preferably role/text based, for example role=button[name='Send'] or text=Continue. Use snapshot first to inspect the page.\",\n  }),\n  x: Schema.optional(\n    Schema.Finite.annotate({\n      description: \"Viewport-relative X coordinate in CSS pixels. Must be paired with y.\",\n    }),\n  ),\n  y: Schema.optional(\n    Schema.Finite.annotate({\n      description: \"Viewport-relative Y coordinate in CSS pixels. Must be paired with x.\",\n    }),\n  ),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter((input) => {\n      const selectorModes =\n        Number(input.selector !== undefined) + Number(input.locator !== undefined);\n      const hasX = input.x !== undefined;\n      const hasY = input.y !== undefined;\n      if (hasX !== hasY) return \"Coordinates require both x and y.\";\n      const coordinateModes = hasX && hasY ? 1 : 0;\n      return selectorModes + coordinateModes === 1 || \"Provide exactly one click target.\";\n    }),\n  )\n  .annotate({\n    description:\n      \"Clicks one target. Provide exactly one of locator, selector, or the x/y coordinate pair.\",\n  });\nexport type PreviewAutomationClickInput = typeof PreviewAutomationClickInput.Type;\n\nexport const PreviewAutomationTypeInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  text: Schema.String.annotate({ description: \"Literal text to insert.\" }),\n  selector: Schema.optional(LegacySelector).annotate({\n    description: \"Legacy CSS selector for the input. Prefer locator.\",\n  }),\n  locator: Schema.optional(Locator).annotate({\n    description:\n      \"Playwright selector for the input, for example role=textbox[name='Message'] or textarea[placeholder*='Message'].\",\n  }),\n  clear: Schema.optional(\n    Schema.Boolean.annotate({\n      description: \"Clear the existing input value before inserting text. Defaults to false.\",\n    }),\n  ),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter(\n      (input) =>\n        !(input.selector !== undefined && input.locator !== undefined) ||\n        \"Provide at most one of selector or locator.\",\n    ),\n  )\n  .annotate({\n    description:\n      \"Types into locator/selector, or into the currently focused element when neither target is provided.\",\n  });\nexport type PreviewAutomationTypeInput = typeof PreviewAutomationTypeInput.Type;\n\nexport const PreviewAutomationPressInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  key: Schema.String.check(Schema.isTrimmed())\n    .check(\n      Schema.isNonEmpty({\n        description:\n          \"Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.\",\n      }),\n    )\n    .annotateKey({\n      description:\n        \"Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.\",\n    }),\n  modifiers: Schema.optional(\n    Schema.Array(Schema.Literals([\"Alt\", \"Control\", \"Meta\", \"Shift\"])).annotate({\n      description: \"Modifier keys held while pressing key.\",\n    }),\n  ),\n}).annotate({ description: \"Presses one keyboard key in the active browser tab.\" });\nexport type PreviewAutomationPressInput = typeof PreviewAutomationPressInput.Type;\n\nexport const PreviewAutomationScrollInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  deltaX: Schema.optional(\n    Schema.Finite.annotate({\n      description: \"Horizontal scroll delta in CSS pixels. Positive scrolls right. Defaults to 0.\",\n    }),\n  ),\n  deltaY: Schema.optional(\n    Schema.Finite.annotate({\n      description: \"Vertical scroll delta in CSS pixels. Positive scrolls down. Defaults to 0.\",\n    }),\n  ),\n  selector: Schema.optional(LegacySelector).annotate({\n    description: \"Legacy CSS selector for a scrollable container. Omit to scroll the viewport.\",\n  }),\n  locator: Schema.optional(Locator).annotate({\n    description: \"Playwright selector for a scrollable container. Omit to scroll the viewport.\",\n  }),\n})\n  .check(\n    Schema.makeFilter((input) => {\n      if (input.selector !== undefined && input.locator !== undefined) {\n        return \"Provide at most one of selector or locator.\";\n      }\n      return (\n        input.deltaX !== undefined || input.deltaY !== undefined || \"Provide deltaX or deltaY.\"\n      );\n    }),\n  )\n  .annotate({\n    description:\n      \"Scrolls the viewport, or a locator/selector container. Provide deltaX, deltaY, or both.\",\n  });\nexport type PreviewAutomationScrollInput = typeof PreviewAutomationScrollInput.Type;\n\nexport const PreviewAutomationEvaluateInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  expression: Schema.String.check(Schema.isTrimmed())\n    .check(\n      Schema.isNonEmpty({\n        description:\n          \"JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().\",\n      }),\n    )\n    .check(Schema.isMaxLength(64_000))\n    .annotateKey({\n      description:\n        \"JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().\",\n    }),\n  awaitPromise: Schema.optional(\n    Schema.Boolean.annotate({ description: \"Await a returned Promise. Defaults to true.\" }),\n  ),\n  returnByValue: Schema.optional(\n    Schema.Boolean.annotate({\n      description:\n        \"Serialize and return the value instead of a remote object reference. Defaults to true.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Evaluates JavaScript in the page. Prefer snapshot and semantic actions; use evaluate for inspection or unsupported interactions.\",\n});\nexport type PreviewAutomationEvaluateInput = typeof PreviewAutomationEvaluateInput.Type;\n\nexport const PreviewAutomationWaitForInput = Schema.Struct({\n  ...PreviewAutomationTabTargetFields,\n  selector: Schema.optional(LegacySelector).annotate({\n    description: \"Legacy CSS selector that must match an element. Prefer locator.\",\n  }),\n  locator: Schema.optional(Locator).annotate({\n    description:\n      \"Playwright selector that must match an element, for example role=button[name='Send'].\",\n  }),\n  text: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Case-sensitive substring that must appear in visible document text.\",\n    }),\n  ).annotate({\n    description: \"Case-sensitive substring that must appear in visible document text.\",\n  }),\n  urlIncludes: Schema.optional(\n    TrimmedNonEmptyString.annotate({\n      description: \"Substring that must appear in the current absolute URL.\",\n    }),\n  ).annotate({ description: \"Substring that must appear in the current absolute URL.\" }),\n  timeoutMs: OptionalTimeoutMs,\n})\n  .check(\n    Schema.makeFilter((input) => {\n      if (input.selector !== undefined && input.locator !== undefined) {\n        return \"Provide at most one of selector or locator.\";\n      }\n      return (\n        input.selector !== undefined ||\n        input.locator !== undefined ||\n        input.text !== undefined ||\n        input.urlIncludes !== undefined ||\n        \"Provide at least one wait condition.\"\n      );\n    }),\n  )\n  .annotate({\n    description:\n      \"Waits until all provided conditions match. Use after click/type when the page changes asynchronously.\",\n  });\nexport type PreviewAutomationWaitForInput = typeof PreviewAutomationWaitForInput.Type;\n\nexport const PreviewAutomationElement = Schema.Struct({\n  tag: Schema.String,\n  role: Schema.NullOr(Schema.String),\n  name: Schema.String,\n  selector: Schema.String,\n  x: Schema.Number,\n  y: Schema.Number,\n  width: Schema.Number,\n  height: Schema.Number,\n});\nexport type PreviewAutomationElement = typeof PreviewAutomationElement.Type;\n\nexport const PreviewAutomationConsoleEntry = Schema.Struct({\n  level: Schema.String,\n  text: Schema.String,\n  timestamp: Schema.String,\n  source: Schema.optional(Schema.String),\n});\nexport type PreviewAutomationConsoleEntry = typeof PreviewAutomationConsoleEntry.Type;\n\nexport const PreviewAutomationNetworkEntry = Schema.Struct({\n  url: Schema.String,\n  method: Schema.String,\n  status: Schema.NullOr(Schema.Number),\n  failed: Schema.Boolean,\n  errorText: Schema.optional(Schema.String),\n  timestamp: Schema.String,\n});\nexport type PreviewAutomationNetworkEntry = typeof PreviewAutomationNetworkEntry.Type;\n\nexport const PreviewAutomationActionEvent = Schema.Struct({\n  id: Schema.String,\n  action: Schema.String,\n  status: Schema.Literals([\"running\", \"succeeded\", \"failed\", \"interrupted\"]),\n  startedAt: Schema.String,\n  completedAt: Schema.optional(Schema.String),\n  error: Schema.optional(Schema.String),\n});\nexport type PreviewAutomationActionEvent = typeof PreviewAutomationActionEvent.Type;\n\nexport const PreviewAutomationSnapshot = Schema.Struct({\n  url: Schema.String,\n  title: Schema.String,\n  loading: Schema.Boolean,\n  visibleText: Schema.String,\n  interactiveElements: Schema.Array(PreviewAutomationElement),\n  accessibilityTree: Schema.Unknown,\n  consoleEntries: Schema.Array(PreviewAutomationConsoleEntry),\n  networkEntries: Schema.Array(PreviewAutomationNetworkEntry),\n  actionTimeline: Schema.Array(PreviewAutomationActionEvent),\n  screenshot: Schema.Struct({\n    mimeType: Schema.Literal(\"image/png\"),\n    data: Schema.String,\n    width: Schema.Int,\n    height: Schema.Int,\n  }),\n});\nexport type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;\n\nexport const PreviewAutomationRecordingStatus = Schema.Struct({\n  tabId: PreviewTabId,\n  recording: Schema.Boolean,\n  startedAt: Schema.NullOr(Schema.String),\n});\nexport type PreviewAutomationRecordingStatus = typeof PreviewAutomationRecordingStatus.Type;\n\nexport const PreviewAutomationRecordingArtifact = Schema.Struct({\n  id: Schema.String,\n  tabId: PreviewTabId,\n  path: Schema.String,\n  mimeType: Schema.String,\n  sizeBytes: Schema.Int,\n  createdAt: Schema.String,\n});\nexport type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;\n\nexport const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));\nexport type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;\nexport const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));\nexport type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;\n\nexport const PreviewAutomationHostIdentity = Schema.Struct({\n  clientId: PreviewAutomationClientId,\n  environmentId: EnvironmentId,\n});\nexport type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;\n\nexport const PreviewAutomationHost = Schema.Struct({\n  ...PreviewAutomationHostIdentity.fields,\n  /**\n   * Missing means the pre-capability-negotiation V1 operation set. This lets\n   * a newer server safely coexist with an older desktop during rollout.\n   */\n  supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),\n});\nexport type PreviewAutomationHost = typeof PreviewAutomationHost.Type;\n\nexport const PreviewAutomationHostFocus = Schema.Struct({\n  ...PreviewAutomationHostIdentity.fields,\n  connectionId: PreviewAutomationConnectionId,\n  focused: Schema.Boolean,\n});\nexport type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;\n\nexport const PreviewAutomationRequest = Schema.Struct({\n  requestId: TrimmedNonEmptyString,\n  threadId: ThreadId,\n  tabId: Schema.optional(PreviewTabId),\n  tabIdExplicit: Schema.optional(Schema.Boolean),\n  operation: PreviewAutomationOperation,\n  input: Schema.Unknown,\n  timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),\n});\nexport type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;\n\nexport const PreviewAutomationStreamEvent = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"connected\"),\n    connectionId: PreviewAutomationConnectionId,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"request\"),\n    connectionId: PreviewAutomationConnectionId,\n    request: PreviewAutomationRequest,\n  }),\n]);\nexport type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;\n\nexport const PreviewAutomationResponse = Schema.Struct({\n  clientId: PreviewAutomationClientId,\n  connectionId: PreviewAutomationConnectionId,\n  requestId: TrimmedNonEmptyString,\n  ok: Schema.Boolean,\n  result: Schema.optional(Schema.Unknown),\n  error: Schema.optional(\n    Schema.Struct({\n      _tag: TrimmedNonEmptyString,\n      message: Schema.String,\n      detail: Schema.optional(Schema.Unknown),\n    }),\n  ),\n});\nexport type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;\n\nexport class PreviewAutomationUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationUnavailableError>()(\n  \"PreviewAutomationUnavailableError\",\n  {\n    capability: Schema.Literal(\"preview\"),\n    environmentId: EnvironmentId,\n    threadId: ThreadId,\n    providerSessionId: TrimmedNonEmptyString,\n    providerInstanceId: ProviderInstanceId,\n  },\n) {\n  override get message(): string {\n    return `MCP credential does not grant the ${this.capability} capability.`;\n  }\n}\n\nconst PreviewAutomationScopeErrorFields = {\n  operation: PreviewAutomationOperation,\n  environmentId: EnvironmentId,\n  threadId: ThreadId,\n  providerSessionId: TrimmedNonEmptyString,\n  providerInstanceId: ProviderInstanceId,\n};\n\nconst PreviewAutomationRequestErrorFields = {\n  ...PreviewAutomationScopeErrorFields,\n  clientId: TrimmedNonEmptyString,\n  connectionId: PreviewAutomationConnectionId,\n  requestId: TrimmedNonEmptyString,\n  tabId: Schema.optional(PreviewTabId),\n  timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),\n};\n\nconst PreviewAutomationRemoteDiagnosticFields = {\n  remoteTag: TrimmedNonEmptyString,\n  remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n  remoteDetailKind: Schema.optional(\n    Schema.Literals([\"null\", \"array\", \"object\", \"string\", \"number\", \"boolean\"]),\n  ),\n  cause: Schema.Defect(),\n};\n\nconst PreviewAutomationOptionalRemoteDiagnosticFields = {\n  remoteTag: Schema.optional(TrimmedNonEmptyString),\n  remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n  remoteDetailKind: Schema.optional(\n    Schema.Literals([\"null\", \"array\", \"object\", \"string\", \"number\", \"boolean\"]),\n  ),\n  cause: Schema.optional(Schema.Defect()),\n};\n\nexport class PreviewAutomationNoAvailableHostError extends Schema.TaggedErrorClass<PreviewAutomationNoAvailableHostError>()(\n  \"PreviewAutomationNoAvailableHostError\",\n  {\n    ...PreviewAutomationScopeErrorFields,\n    clientId: Schema.optional(TrimmedNonEmptyString),\n    connectionId: Schema.optional(PreviewAutomationConnectionId),\n    requestId: Schema.optional(TrimmedNonEmptyString),\n    tabId: Schema.optional(PreviewTabId),\n    timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),\n    ...PreviewAutomationOptionalRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    const summary = `No preview automation host is available for ${this.operation} in environment ${this.environmentId}.`;\n    return summary;\n  }\n}\n\nexport class PreviewAutomationUnsupportedClientError extends Schema.TaggedErrorClass<PreviewAutomationUnsupportedClientError>()(\n  \"PreviewAutomationUnsupportedClientError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    return `Preview automation client ${this.clientId} does not support ${this.operation}.`;\n  }\n}\n\nexport class PreviewAutomationTabNotFoundError extends Schema.TaggedErrorClass<PreviewAutomationTabNotFoundError>()(\n  \"PreviewAutomationTabNotFoundError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    const summary = this.tabId\n      ? `Preview tab ${this.tabId} was not found for ${this.operation}.`\n      : `No active preview tab was found for ${this.operation}.`;\n    return summary;\n  }\n}\n\nexport class PreviewAutomationTimeoutError extends Schema.TaggedErrorClass<PreviewAutomationTimeoutError>()(\n  \"PreviewAutomationTimeoutError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationOptionalRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;\n    return summary;\n  }\n}\n\nexport class PreviewAutomationControlInterruptedError extends Schema.TaggedErrorClass<PreviewAutomationControlInterruptedError>()(\n  \"PreviewAutomationControlInterruptedError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;\n  }\n}\n\nexport class PreviewAutomationExecutionError extends Schema.TaggedErrorClass<PreviewAutomationExecutionError>()(\n  \"PreviewAutomationExecutionError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    return `Preview automation ${this.operation} failed on client ${this.clientId}.`;\n  }\n}\n\nexport class PreviewAutomationInvalidSelectorError extends Schema.TaggedErrorClass<PreviewAutomationInvalidSelectorError>()(\n  \"PreviewAutomationInvalidSelectorError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n    selectorKind: Schema.optional(Schema.Literals([\"locator\", \"selector\"])),\n    selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n  },\n) {\n  override get message(): string {\n    if (this.selectorKind !== undefined && this.selectorLength !== undefined) {\n      return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters).`;\n    }\n    return `Preview automation ${this.operation} received an invalid selector.`;\n  }\n}\n\nexport class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(\n  \"PreviewAutomationTargetNotEditableError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n    selectorKind: Schema.optional(Schema.Literals([\"focused-element\", \"locator\", \"selector\"])),\n    selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n  },\n) {\n  override get message(): string {\n    if (this.selectorKind === \"focused-element\") {\n      return `Preview automation ${this.operation} requires an editable focused element.`;\n    }\n    if (this.selectorKind !== undefined && this.selectorLength !== undefined) {\n      return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;\n    }\n    return `Preview automation ${this.operation} requires an editable target.`;\n  }\n}\n\nexport class PreviewAutomationResultTooLargeError extends Schema.TaggedErrorClass<PreviewAutomationResultTooLargeError>()(\n  \"PreviewAutomationResultTooLargeError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n    maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),\n  },\n) {\n  override get message(): string {\n    const summary =\n      this.maximumBytes === undefined\n        ? `Preview automation ${this.operation} produced a result that is too large.`\n        : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;\n    return summary;\n  }\n}\n\nexport class PreviewAutomationClientDisconnectedError extends Schema.TaggedErrorClass<PreviewAutomationClientDisconnectedError>()(\n  \"PreviewAutomationClientDisconnectedError\",\n  PreviewAutomationRequestErrorFields,\n) {\n  override get message(): string {\n    return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;\n  }\n}\n\nexport class PreviewAutomationRequestQueueClosedError extends Schema.TaggedErrorClass<PreviewAutomationRequestQueueClosedError>()(\n  \"PreviewAutomationRequestQueueClosedError\",\n  PreviewAutomationRequestErrorFields,\n) {\n  override get message(): string {\n    return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;\n  }\n}\n\nexport class PreviewAutomationRemoteUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationRemoteUnavailableError>()(\n  \"PreviewAutomationRemoteUnavailableError\",\n  {\n    ...PreviewAutomationRequestErrorFields,\n    ...PreviewAutomationRemoteDiagnosticFields,\n  },\n) {\n  override get message(): string {\n    return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;\n  }\n}\n\nexport class PreviewAutomationMalformedResponseError extends Schema.TaggedErrorClass<PreviewAutomationMalformedResponseError>()(\n  \"PreviewAutomationMalformedResponseError\",\n  PreviewAutomationRequestErrorFields,\n) {\n  override get message(): string {\n    return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;\n  }\n}\n\nexport const PreviewAutomationError = Schema.Union([\n  PreviewAutomationUnavailableError,\n  PreviewAutomationNoAvailableHostError,\n  PreviewAutomationUnsupportedClientError,\n  PreviewAutomationTabNotFoundError,\n  PreviewAutomationTimeoutError,\n  PreviewAutomationControlInterruptedError,\n  PreviewAutomationExecutionError,\n  PreviewAutomationInvalidSelectorError,\n  PreviewAutomationTargetNotEditableError,\n  PreviewAutomationResultTooLargeError,\n  PreviewAutomationClientDisconnectedError,\n  PreviewAutomationRequestQueueClosedError,\n  PreviewAutomationRemoteUnavailableError,\n  PreviewAutomationMalformedResponseError,\n]);\nexport type PreviewAutomationError = typeof PreviewAutomationError.Type;\n\nexport const PreviewUrlResolution = Schema.Struct({\n  requestedUrl: Schema.String,\n  resolvedUrl: Schema.String,\n  resolutionKind: Schema.Literals([\"direct\", \"direct-private-network\"]),\n  environmentId: EnvironmentId,\n});\nexport type PreviewUrlResolution = typeof PreviewUrlResolution.Type;\n","import type {\n  VcsCreateRefInput,\n  VcsCreateRefResult,\n  VcsCreateWorktreeInput,\n  VcsCreateWorktreeResult,\n  VcsInitInput,\n  VcsListRefsInput,\n  VcsListRefsResult,\n  VcsPullInput,\n  VcsPullResult,\n  VcsRemoveWorktreeInput,\n  VcsSwitchRefInput,\n  VcsSwitchRefResult,\n  GitPreparePullRequestThreadInput,\n  GitPreparePullRequestThreadResult,\n  GitPullRequestRefInput,\n  GitResolvePullRequestResult,\n  VcsStatusInput,\n  VcsStatusResult,\n} from \"./git.ts\";\nimport type {\n  ReviewDiffFileContentsInput,\n  ReviewDiffFileContentsResult,\n  ReviewDiffPreviewInput,\n  ReviewDiffPreviewResult,\n} from \"./review.ts\";\nimport type { FilesystemBrowseInput, FilesystemBrowseResult } from \"./filesystem.ts\";\nimport type { AssetCreateUrlInput, AssetCreateUrlResult } from \"./assets.ts\";\nimport type {\n  ProjectListEntriesInput,\n  ProjectListEntriesResult,\n  ProjectReadFileInput,\n  ProjectReadFileResult,\n  ProjectSearchEntriesInput,\n  ProjectSearchEntriesResult,\n  ProjectWriteFileInput,\n  ProjectWriteFileResult,\n} from \"./project.ts\";\nimport type {\n  TerminalAttachInput,\n  TerminalAttachStreamEvent,\n  TerminalClearInput,\n  TerminalCloseInput,\n  TerminalMetadataStreamEvent,\n  TerminalOpenInput,\n  TerminalResizeInput,\n  TerminalRestartInput,\n  TerminalSessionSnapshot,\n  TerminalWriteInput,\n} from \"./terminal.ts\";\nimport * as Schema from \"effect/Schema\";\nimport type {\n  DiscoveredLocalServerList,\n  PreviewCloseInput,\n  PreviewEvent,\n  PreviewListInput,\n  PreviewListResult,\n  PreviewNavigateInput,\n  PreviewOpenInput,\n  PreviewRefreshInput,\n  PreviewReportStatusInput,\n  PreviewResizeInput,\n  PreviewSessionSnapshot,\n} from \"./preview.ts\";\nimport {\n  PreviewAutomationClickInput,\n  PreviewAutomationEvaluateInput,\n  PreviewAutomationHost,\n  PreviewAutomationHostFocus,\n  PreviewAutomationPressInput,\n  PreviewAutomationResponse,\n  PreviewAutomationScrollInput,\n  PreviewAutomationSnapshot,\n  PreviewAutomationStatus,\n  PreviewAutomationStreamEvent,\n  PreviewAutomationTypeInput,\n  PreviewAutomationWaitForInput,\n} from \"./previewAutomation.ts\";\nimport type {\n  ClientOrchestrationCommand,\n  OrchestrationGetFullThreadDiffInput,\n  OrchestrationGetFullThreadDiffResult,\n  OrchestrationGetTurnDiffInput,\n  OrchestrationGetTurnDiffResult,\n  OrchestrationShellSnapshot,\n  OrchestrationShellStreamItem,\n  OrchestrationSubscribeThreadInput,\n  OrchestrationThreadStreamItem,\n} from \"./orchestration.ts\";\nimport { EnvironmentId } from \"./baseSchemas.ts\";\nimport { AuthAccessTokenResult, AuthSessionState, AuthWebSocketTicketResult } from \"./auth.ts\";\nimport { AdvertisedEndpoint } from \"./remoteAccess.ts\";\nimport { ExecutionEnvironmentDescriptor } from \"./environment.ts\";\nimport type { ClientSettings } from \"./settings.ts\";\nimport type {\n  SourceControlCloneRepositoryInput,\n  SourceControlCloneRepositoryResult,\n  SourceControlPublishRepositoryInput,\n  SourceControlPublishRepositoryResult,\n  SourceControlRepositoryInfo,\n  SourceControlRepositoryLookupInput,\n} from \"./sourceControl.ts\";\n\nexport interface ContextMenuItem<T extends string = string> {\n  id: T;\n  label: string;\n  destructive?: boolean;\n  disabled?: boolean;\n  /** Renders as a non-interactive section header label. Web fallback only — stripped on desktop native menus. */\n  header?: boolean;\n  /** Icon keyword resolved by the web fallback. Stripped on desktop native menus. */\n  icon?: string;\n  children?: readonly ContextMenuItem<T>[];\n}\n\nexport interface ContextMenuItemSchemaType {\n  readonly id: string;\n  readonly label: string;\n  readonly destructive?: boolean;\n  readonly disabled?: boolean;\n  readonly header?: boolean;\n  readonly icon?: string;\n  readonly children?: readonly ContextMenuItemSchemaType[];\n}\n\nexport const ContextMenuItemSchema: Schema.Codec<ContextMenuItemSchemaType> = Schema.Struct({\n  id: Schema.String,\n  label: Schema.String,\n  destructive: Schema.optionalKey(Schema.Boolean),\n  disabled: Schema.optionalKey(Schema.Boolean),\n  header: Schema.optionalKey(Schema.Boolean),\n  icon: Schema.optionalKey(Schema.String),\n  children: Schema.optionalKey(\n    Schema.Array(\n      Schema.suspend((): Schema.Codec<ContextMenuItemSchemaType> => ContextMenuItemSchema),\n    ),\n  ),\n});\n\nexport type DesktopUpdateStatus =\n  | \"disabled\"\n  | \"idle\"\n  | \"checking\"\n  | \"up-to-date\"\n  | \"available\"\n  | \"downloading\"\n  | \"downloaded\"\n  | \"error\";\n\nexport type DesktopRuntimeArch = \"arm64\" | \"x64\" | \"other\";\nexport type DesktopTheme = \"light\" | \"dark\" | \"system\";\nexport type DesktopUpdateChannel = \"latest\" | \"nightly\";\nexport type DesktopAppStageLabel = \"Alpha\" | \"Dev\" | \"Nightly\";\n\nexport const DesktopUpdateStatusSchema = Schema.Literals([\n  \"disabled\",\n  \"idle\",\n  \"checking\",\n  \"up-to-date\",\n  \"available\",\n  \"downloading\",\n  \"downloaded\",\n  \"error\",\n]);\nexport const DesktopRuntimeArchSchema = Schema.Literals([\"arm64\", \"x64\", \"other\"]);\nexport const DesktopThemeSchema = Schema.Literals([\"light\", \"dark\", \"system\"]);\nexport const DesktopUpdateChannelSchema = Schema.Literals([\"latest\", \"nightly\"]);\nexport const DesktopAppStageLabelSchema = Schema.Literals([\"Alpha\", \"Dev\", \"Nightly\"]);\n\nexport interface DesktopAppBranding {\n  baseName: string;\n  stageLabel: DesktopAppStageLabel;\n  displayName: string;\n}\n\nexport const DesktopAppBrandingSchema = Schema.Struct({\n  baseName: Schema.String,\n  stageLabel: DesktopAppStageLabelSchema,\n  displayName: Schema.String,\n});\n\nexport interface DesktopRuntimeInfo {\n  hostArch: DesktopRuntimeArch;\n  appArch: DesktopRuntimeArch;\n  runningUnderArm64Translation: boolean;\n}\n\nexport const DesktopRuntimeInfoSchema = Schema.Struct({\n  hostArch: DesktopRuntimeArchSchema,\n  appArch: DesktopRuntimeArchSchema,\n  runningUnderArm64Translation: Schema.Boolean,\n});\n\nexport interface DesktopUpdateState {\n  enabled: boolean;\n  status: DesktopUpdateStatus;\n  channel: DesktopUpdateChannel;\n  currentVersion: string;\n  hostArch: DesktopRuntimeArch;\n  appArch: DesktopRuntimeArch;\n  runningUnderArm64Translation: boolean;\n  availableVersion: string | null;\n  downloadedVersion: string | null;\n  releaseNotes: ReadonlyArray<DesktopUpdateReleaseNote>;\n  downloadPercent: number | null;\n  checkedAt: string | null;\n  message: string | null;\n  errorContext: \"check\" | \"download\" | \"install\" | null;\n  canRetry: boolean;\n}\n\nexport interface DesktopUpdateReleaseNote {\n  version: string;\n  items: ReadonlyArray<string>;\n}\n\nexport const DesktopUpdateReleaseNoteSchema = Schema.Struct({\n  version: Schema.String,\n  items: Schema.Array(Schema.String),\n});\n\nexport const DesktopUpdateStateSchema = Schema.Struct({\n  enabled: Schema.Boolean,\n  status: DesktopUpdateStatusSchema,\n  channel: DesktopUpdateChannelSchema,\n  currentVersion: Schema.String,\n  hostArch: DesktopRuntimeArchSchema,\n  appArch: DesktopRuntimeArchSchema,\n  runningUnderArm64Translation: Schema.Boolean,\n  availableVersion: Schema.NullOr(Schema.String),\n  downloadedVersion: Schema.NullOr(Schema.String),\n  releaseNotes: Schema.Array(DesktopUpdateReleaseNoteSchema),\n  downloadPercent: Schema.NullOr(Schema.Number),\n  checkedAt: Schema.NullOr(Schema.String),\n  message: Schema.NullOr(Schema.String),\n  errorContext: Schema.NullOr(Schema.Literals([\"check\", \"download\", \"install\"])),\n  canRetry: Schema.Boolean,\n});\n\nexport interface DesktopUpdateActionResult {\n  accepted: boolean;\n  completed: boolean;\n  state: DesktopUpdateState;\n}\n\nexport const DesktopUpdateActionResultSchema = Schema.Struct({\n  accepted: Schema.Boolean,\n  completed: Schema.Boolean,\n  state: DesktopUpdateStateSchema,\n});\n\nexport interface DesktopUpdateCheckResult {\n  checked: boolean;\n  state: DesktopUpdateState;\n}\n\nexport const DesktopUpdateCheckResultSchema = Schema.Struct({\n  checked: Schema.Boolean,\n  state: DesktopUpdateStateSchema,\n});\n\n// Stable id for the Windows-native primary backend. Desktop side wraps\n// this with a brand inside DesktopBackendManager; web side keeps it as\n// a plain string so the env-runtime can compare against it without\n// importing brand machinery from the desktop package.\nexport const PRIMARY_LOCAL_ENVIRONMENT_ID = \"primary\";\n\nexport interface DesktopEnvironmentBootstrap {\n  // Stable backend instance id (e.g. \"primary\" or \"wsl:ubuntu\"). The\n  // web env runtime keys local environments off this so projects\n  // routed to a specific backend reopen against the same one.\n  id: string;\n  label: string;\n  // Concrete WSL distro used by the current backend run. This stays separate\n  // from id because a default-tracking instance keeps the stable\n  // \"wsl:default\" IPC target while each run launches a specific distro.\n  runningDistro?: string | null;\n  httpBaseUrl: string | null;\n  wsBaseUrl: string | null;\n  bootstrapToken?: string;\n}\n\nexport const DesktopEnvironmentBootstrapSchema = Schema.Struct({\n  id: Schema.String,\n  label: Schema.String,\n  runningDistro: Schema.optionalKey(Schema.NullOr(Schema.String)),\n  httpBaseUrl: Schema.NullOr(Schema.String),\n  wsBaseUrl: Schema.NullOr(Schema.String),\n  bootstrapToken: Schema.optionalKey(Schema.String),\n});\n\nexport const DesktopSshEnvironmentTargetSchema = Schema.Struct({\n  alias: Schema.String,\n  hostname: Schema.String,\n  username: Schema.NullOr(Schema.String),\n  port: Schema.NullOr(Schema.Number),\n});\nexport type DesktopSshEnvironmentTarget = typeof DesktopSshEnvironmentTargetSchema.Type;\n\nexport type DesktopSshHostSource = \"ssh-config\" | \"known-hosts\";\nexport const DesktopSshHostSourceSchema = Schema.Literals([\"ssh-config\", \"known-hosts\"]);\n\nexport interface DesktopDiscoveredSshHost extends DesktopSshEnvironmentTarget {\n  source: DesktopSshHostSource;\n}\n\nexport const DesktopDiscoveredSshHostSchema = Schema.Struct({\n  alias: Schema.String,\n  hostname: Schema.String,\n  username: Schema.NullOr(Schema.String),\n  port: Schema.NullOr(Schema.Number),\n  source: DesktopSshHostSourceSchema,\n});\n\nexport interface DesktopSshEnvironmentBootstrap {\n  target: DesktopSshEnvironmentTarget;\n  httpBaseUrl: string;\n  wsBaseUrl: string;\n  pairingToken: string | null;\n  remotePort?: number;\n  remoteServerKind?: \"external\" | \"managed\";\n}\n\nexport const DesktopSshEnvironmentBootstrapSchema = Schema.Struct({\n  target: DesktopSshEnvironmentTargetSchema,\n  httpBaseUrl: Schema.String,\n  wsBaseUrl: Schema.String,\n  pairingToken: Schema.NullOr(Schema.String),\n  remotePort: Schema.optionalKey(Schema.Number),\n  remoteServerKind: Schema.optionalKey(Schema.Literals([\"external\", \"managed\"])),\n});\n\nexport interface DesktopSshPasswordPromptRequest {\n  requestId: string;\n  destination: string;\n  username: string | null;\n  prompt: string;\n  expiresAt: string;\n}\n\nexport const DesktopSshPasswordPromptRequestSchema = Schema.Struct({\n  requestId: Schema.String,\n  destination: Schema.String,\n  username: Schema.NullOr(Schema.String),\n  prompt: Schema.String,\n  expiresAt: Schema.String,\n});\n\nexport const DesktopSshPasswordPromptCancelledType = \"ssh-password-prompt-cancelled\" as const;\n\nexport const DesktopSshPasswordPromptCancelledResultSchema = Schema.Struct({\n  type: Schema.Literal(DesktopSshPasswordPromptCancelledType),\n  message: Schema.String,\n});\n\nexport const DesktopSshEnvironmentEnsureOptionsSchema = Schema.Struct({\n  issuePairingToken: Schema.optionalKey(Schema.Boolean),\n});\n\nexport const DesktopSshEnvironmentEnsureInputSchema = Schema.Struct({\n  target: DesktopSshEnvironmentTargetSchema,\n  options: Schema.optionalKey(DesktopSshEnvironmentEnsureOptionsSchema),\n});\n\nexport const DesktopSshEnvironmentEnsureResultSchema = Schema.Union([\n  DesktopSshEnvironmentBootstrapSchema,\n  DesktopSshPasswordPromptCancelledResultSchema,\n]);\n\nexport const DesktopSshHttpBaseUrlInputSchema = Schema.Struct({\n  httpBaseUrl: Schema.String,\n});\n\nexport const DesktopSshBearerRequestInputSchema = Schema.Struct({\n  httpBaseUrl: Schema.String,\n  bearerToken: Schema.String,\n});\n\nexport const DesktopSshBearerBootstrapInputSchema = Schema.Struct({\n  httpBaseUrl: Schema.String,\n  credential: Schema.String,\n});\n\nexport const DesktopSshPasswordPromptResolutionInputSchema = Schema.Struct({\n  requestId: Schema.String,\n  password: Schema.NullOr(Schema.String),\n});\n\nexport const PersistedSavedEnvironmentRecordSchema = Schema.Struct({\n  environmentId: EnvironmentId,\n  label: Schema.String,\n  wsBaseUrl: Schema.String,\n  httpBaseUrl: Schema.String,\n  createdAt: Schema.String,\n  lastConnectedAt: Schema.NullOr(Schema.String),\n  desktopSsh: Schema.optionalKey(DesktopSshEnvironmentTargetSchema),\n  relayManaged: Schema.optionalKey(\n    Schema.Struct({\n      relayUrl: Schema.String,\n    }),\n  ),\n});\nexport type PersistedSavedEnvironmentRecord = typeof PersistedSavedEnvironmentRecordSchema.Type;\n\nexport type DesktopServerExposureMode = \"local-only\" | \"network-accessible\";\n\nexport const DesktopServerExposureModeSchema = Schema.Literals([\n  \"local-only\",\n  \"network-accessible\",\n]);\n\nexport interface DesktopServerExposureState {\n  mode: DesktopServerExposureMode;\n  endpointUrl: string | null;\n  advertisedHost: string | null;\n  tailscaleServeEnabled: boolean;\n  tailscaleServePort: number;\n}\n\nexport const DesktopServerExposureStateSchema = Schema.Struct({\n  mode: DesktopServerExposureModeSchema,\n  endpointUrl: Schema.NullOr(Schema.String),\n  advertisedHost: Schema.NullOr(Schema.String),\n  tailscaleServeEnabled: Schema.Boolean,\n  tailscaleServePort: Schema.Number,\n});\n\nexport interface PickFolderOptions {\n  initialPath?: string | null;\n  // When set, the desktop dialog opens against the named backend's\n  // filesystem instead of the primary's. Used by callers that already\n  // know which local environment they're targeting (e.g. opening a\n  // project that lives inside WSL). Omitting it keeps the historical\n  // behavior so non-WSL users never see a different picker.\n  targetEnvironmentId?: string;\n}\n\nexport const PickFolderOptionsSchema = Schema.Struct({\n  initialPath: Schema.optionalKey(Schema.NullOr(Schema.String)),\n  targetEnvironmentId: Schema.optionalKey(Schema.String),\n});\n\n/**\n * A file returned by the desktop theme-file picker. Oversized files carry an\n * empty text so the renderer can reject them by size without the main\n * process ever holding their contents.\n */\nexport interface PickedThemeFile {\n  name: string;\n  size: number;\n  text: string;\n}\n\nexport const PickedThemeFileSchema = Schema.Struct({\n  name: Schema.String,\n  size: Schema.Number,\n  text: Schema.String,\n});\n\nexport interface DesktopWslDistro {\n  name: string;\n  isDefault: boolean;\n  version: 1 | 2;\n}\n\nexport const DesktopWslDistroSchema = Schema.Struct({\n  name: Schema.String,\n  isDefault: Schema.Boolean,\n  version: Schema.Literals([1, 2]),\n});\n\nexport interface DesktopWslState {\n  // True when the user has opted the WSL backend in; the actual backend\n  // process is registered with the desktop pool independently of this\n  // flag and may take a moment to come up after the user enables it.\n  enabled: boolean;\n  // null means \"track the current WSL default distro\".\n  distro: string | null;\n  available: boolean;\n  // When true (and `enabled` is also true) the desktop runs only the\n  // WSL backend as the primary; the Windows-side Node backend is not\n  // started. Toggling this requires an app restart because the\n  // primary backend's spec is captured once at layer init.\n  wslOnly: boolean;\n  distros: readonly DesktopWslDistro[];\n  // Reason the dual-mode WSL backend last failed preflight (no node, wrong\n  // version, missing build tools), or null. Surfaced inline in Connections\n  // settings. Always null in wsl-only mode — that path shows a dialog and\n  // falls back to Windows instead.\n  preflightError: string | null;\n}\n\nexport const DesktopWslStateSchema = Schema.Struct({\n  enabled: Schema.Boolean,\n  distro: Schema.NullOr(Schema.String),\n  available: Schema.Boolean,\n  wslOnly: Schema.Boolean,\n  distros: Schema.Array(DesktopWslDistroSchema),\n  preflightError: Schema.NullOr(Schema.String),\n});\n\n/**\n * Renderer-facing snapshot of a desktop preview tab. Mirrors the main-process\n * PreviewTabState shape but uses serialisable primitives only.\n */\nexport type DesktopPreviewNavStatus =\n  | { kind: \"Idle\" }\n  | { kind: \"Loading\"; url: string; title: string }\n  | { kind: \"Success\"; url: string; title: string }\n  | {\n      kind: \"LoadFailed\";\n      url: string;\n      title: string;\n      code: number;\n      description: string;\n    };\n\n/**\n * Emulated `prefers-color-scheme` for the guest page. \"system\" clears the\n * override so the page follows the OS appearance.\n */\nexport type DesktopPreviewColorScheme = \"system\" | \"light\" | \"dark\";\n\nexport const DesktopPreviewColorSchemeSchema: Schema.Codec<DesktopPreviewColorScheme> =\n  Schema.Literals([\"system\", \"light\", \"dark\"]);\n\nexport interface DesktopPreviewTabState {\n  tabId: string;\n  webContentsId: number | null;\n  navStatus: DesktopPreviewNavStatus;\n  canGoBack: boolean;\n  canGoForward: boolean;\n  /** Current zoom factor (1.0 = 100%). */\n  zoomFactor: number;\n  /** Whether this tab is currently mirrored into a desktop picture-in-picture window. */\n  pictureInPicture: boolean;\n  colorScheme: DesktopPreviewColorScheme;\n  controller: \"human\" | \"agent\" | \"none\";\n  updatedAt: string;\n}\n\nexport const DesktopPreviewTabIdSchema = Schema.String.check(Schema.isTrimmed()).check(\n  Schema.isNonEmpty(),\n);\n\nexport const DesktopPreviewNavStatusSchema = Schema.Union([\n  Schema.Struct({ kind: Schema.Literal(\"Idle\") }),\n  Schema.Struct({\n    kind: Schema.Literal(\"Loading\"),\n    url: Schema.String,\n    title: Schema.String,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"Success\"),\n    url: Schema.String,\n    title: Schema.String,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"LoadFailed\"),\n    url: Schema.String,\n    title: Schema.String,\n    code: Schema.Number,\n    description: Schema.String,\n  }),\n]);\n\nexport const DesktopPreviewTabStateSchema: Schema.Codec<DesktopPreviewTabState> = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  webContentsId: Schema.NullOr(Schema.Int),\n  navStatus: DesktopPreviewNavStatusSchema,\n  canGoBack: Schema.Boolean,\n  canGoForward: Schema.Boolean,\n  zoomFactor: Schema.Number,\n  pictureInPicture: Schema.Boolean,\n  colorScheme: DesktopPreviewColorSchemeSchema,\n  controller: Schema.Literals([\"human\", \"agent\", \"none\"]),\n  updatedAt: Schema.String,\n});\n\nexport interface DesktopPreviewPointerEvent {\n  tabId: string;\n  phase: \"move\" | \"click\";\n  x: number;\n  y: number;\n  sequence: number;\n  createdAt: string;\n}\n\nexport const DesktopPreviewPointerEventSchema: Schema.Codec<DesktopPreviewPointerEvent> =\n  Schema.Struct({\n    tabId: DesktopPreviewTabIdSchema,\n    phase: Schema.Literals([\"move\", \"click\"]),\n    x: Schema.Number,\n    y: Schema.Number,\n    sequence: Schema.Int,\n    createdAt: Schema.String,\n  });\n\n/**\n * Static config a renderer needs to mount a preview `<webview>`. Returned\n * atomically by `DesktopPreviewBridge.getPreviewConfig()` so the renderer\n * doesn't have to wait on three separate IPC round-trips before the webview\n * can attach.\n */\nexport interface DesktopPreviewWebviewConfig {\n  /** `persist:t3code-preview` (or whatever the desktop chose). */\n  partition: string;\n  /**\n   * Canonical `<webview webpreferences=\"...\">` string. Encodes the security\n   * posture (sandboxed but contextIsolation off so the picker preload can\n   * read the page's React DevTools hook). Always present.\n   */\n  webPreferences: string;\n  /**\n   * Absolute `file://`-style URL to the picker preload bundle. Set to null\n   * when the bundle isn't present (older builds, broken install) — the\n   * renderer must then disable element-pick affordances.\n   */\n  preloadUrl: string | null;\n}\n\nexport const DesktopPreviewWebviewConfigSchema: Schema.Codec<DesktopPreviewWebviewConfig> =\n  Schema.Struct({\n    partition: Schema.String,\n    webPreferences: Schema.String,\n    preloadUrl: Schema.NullOr(Schema.String),\n  });\n\nexport interface DesktopPreviewAnnotationTheme {\n  colorScheme: \"light\" | \"dark\";\n  radius: string;\n  background: string;\n  foreground: string;\n  popover: string;\n  popoverForeground: string;\n  primary: string;\n  primaryForeground: string;\n  muted: string;\n  mutedForeground: string;\n  accent: string;\n  accentForeground: string;\n  border: string;\n  input: string;\n  ring: string;\n  fontSans: string;\n  fontMono: string;\n}\n\nexport const DesktopPreviewAnnotationThemeSchema: Schema.Codec<DesktopPreviewAnnotationTheme> =\n  Schema.Struct({\n    colorScheme: Schema.Literals([\"light\", \"dark\"]),\n    radius: Schema.String,\n    background: Schema.String,\n    foreground: Schema.String,\n    popover: Schema.String,\n    popoverForeground: Schema.String,\n    primary: Schema.String,\n    primaryForeground: Schema.String,\n    muted: Schema.String,\n    mutedForeground: Schema.String,\n    accent: Schema.String,\n    accentForeground: Schema.String,\n    border: Schema.String,\n    input: Schema.String,\n    ring: Schema.String,\n    fontSans: Schema.String,\n    fontMono: Schema.String,\n  });\n\nexport interface DesktopPreviewRecordingFrame {\n  tabId: string;\n  data: string;\n  width: number;\n  height: number;\n  receivedAt: string;\n}\n\nexport const DesktopPreviewRecordingFrameSchema: Schema.Codec<DesktopPreviewRecordingFrame> =\n  Schema.Struct({\n    tabId: DesktopPreviewTabIdSchema,\n    data: Schema.String,\n    width: Schema.Number,\n    height: Schema.Number,\n    receivedAt: Schema.String,\n  });\n\nexport interface DesktopPreviewRecordingArtifact {\n  id: string;\n  tabId: string;\n  path: string;\n  mimeType: string;\n  sizeBytes: number;\n  createdAt: string;\n}\n\nexport const DesktopPreviewRecordingArtifactSchema: Schema.Codec<DesktopPreviewRecordingArtifact> =\n  Schema.Struct({\n    id: Schema.String,\n    tabId: DesktopPreviewTabIdSchema,\n    path: Schema.String,\n    mimeType: Schema.String,\n    sizeBytes: Schema.Int,\n    createdAt: Schema.String,\n  });\n\nexport interface DesktopPreviewScreenshotArtifact {\n  id: string;\n  tabId: string;\n  path: string;\n  mimeType: \"image/png\";\n  sizeBytes: number;\n  createdAt: string;\n}\n\nexport const DesktopPreviewScreenshotArtifactSchema: Schema.Codec<DesktopPreviewScreenshotArtifact> =\n  Schema.Struct({\n    id: Schema.String,\n    tabId: DesktopPreviewTabIdSchema,\n    path: Schema.String,\n    mimeType: Schema.Literal(\"image/png\"),\n    sizeBytes: Schema.Int,\n    createdAt: Schema.String,\n  });\n\n/**\n * Single stack frame captured by react-grab's `getElementContext`. We surface\n * the source file/line so coding agents can jump straight to the JSX that\n * produced the picked DOM node.\n */\nexport interface PickedElementStackFrame {\n  functionName: string | null;\n  fileName: string | null;\n  lineNumber: number | null;\n  columnNumber: number | null;\n}\n\nexport const PickedElementStackFrameSchema: Schema.Codec<PickedElementStackFrame> = Schema.Struct({\n  functionName: Schema.NullOr(Schema.String),\n  fileName: Schema.NullOr(Schema.String),\n  lineNumber: Schema.NullOr(Schema.Number),\n  columnNumber: Schema.NullOr(Schema.Number),\n});\n\n/**\n * A successful element pick from the preview webview. All fields are\n * best-effort — pages that don't ship a React fiber tree (or aren't running\n * in dev) will still produce a usable payload (selector + html preview),\n * just without component / source attribution.\n */\nexport interface PickedElementPayload {\n  /** URL of the page the element was picked on. */\n  pageUrl: string;\n  /** Optional `<title>` of that page (best-effort). */\n  pageTitle: string | null;\n  /** Lowercase tag name, e.g. `\"button\"`. */\n  tagName: string;\n  /** CSS selector resolving back to the element on a re-render. */\n  selector: string | null;\n  /** Truncated outer-HTML preview (matches react-grab's `htmlPreview`). */\n  htmlPreview: string;\n  /** Nearest React component display name, or null when unavailable. */\n  componentName: string | null;\n  /** First source-mapped stack frame (file + line of the JSX source). */\n  source: PickedElementStackFrame | null;\n  /** Full owner-stack frames; can be empty. Useful for richer context. */\n  stack: ReadonlyArray<PickedElementStackFrame>;\n  /** Author CSS only (UA defaults stripped) — react-grab's `styles`. */\n  styles: string;\n  /** Wall-clock pick time as ISO-8601 string. */\n  pickedAt: string;\n}\n\nexport const PickedElementPayloadSchema: Schema.Codec<PickedElementPayload> = Schema.Struct({\n  pageUrl: Schema.String,\n  pageTitle: Schema.NullOr(Schema.String),\n  tagName: Schema.String,\n  selector: Schema.NullOr(Schema.String),\n  htmlPreview: Schema.String,\n  componentName: Schema.NullOr(Schema.String),\n  source: Schema.NullOr(PickedElementStackFrameSchema),\n  stack: Schema.Array(PickedElementStackFrameSchema),\n  styles: Schema.String,\n  pickedAt: Schema.String,\n});\n\nexport interface PreviewAnnotationRect {\n  x: number;\n  y: number;\n  width: number;\n  height: number;\n}\n\nexport const PreviewAnnotationRectSchema: Schema.Codec<PreviewAnnotationRect> = Schema.Struct({\n  x: Schema.Number,\n  y: Schema.Number,\n  width: Schema.Number,\n  height: Schema.Number,\n});\n\nexport interface PreviewAnnotationPoint {\n  x: number;\n  y: number;\n}\n\nexport const PreviewAnnotationPointSchema: Schema.Codec<PreviewAnnotationPoint> = Schema.Struct({\n  x: Schema.Number,\n  y: Schema.Number,\n});\n\nexport interface PreviewAnnotationElementTarget {\n  id: string;\n  element: PickedElementPayload;\n  rect: PreviewAnnotationRect;\n}\n\nexport const PreviewAnnotationElementTargetSchema: Schema.Codec<PreviewAnnotationElementTarget> =\n  Schema.Struct({\n    id: Schema.String,\n    element: PickedElementPayloadSchema,\n    rect: PreviewAnnotationRectSchema,\n  });\n\nexport interface PreviewAnnotationRegionTarget {\n  id: string;\n  rect: PreviewAnnotationRect;\n}\n\nexport const PreviewAnnotationRegionTargetSchema: Schema.Codec<PreviewAnnotationRegionTarget> =\n  Schema.Struct({\n    id: Schema.String,\n    rect: PreviewAnnotationRectSchema,\n  });\n\nexport interface PreviewAnnotationStrokeTarget {\n  id: string;\n  color: string;\n  width: number;\n  points: ReadonlyArray<PreviewAnnotationPoint>;\n  bounds: PreviewAnnotationRect;\n}\n\nexport const PreviewAnnotationStrokeTargetSchema: Schema.Codec<PreviewAnnotationStrokeTarget> =\n  Schema.Struct({\n    id: Schema.String,\n    color: Schema.String,\n    width: Schema.Number,\n    points: Schema.Array(PreviewAnnotationPointSchema),\n    bounds: PreviewAnnotationRectSchema,\n  });\n\nexport interface PreviewAnnotationStyleChange {\n  targetId: string;\n  selector: string | null;\n  property: string;\n  previousValue: string;\n  value: string;\n}\n\nexport const PreviewAnnotationStyleChangeSchema: Schema.Codec<PreviewAnnotationStyleChange> =\n  Schema.Struct({\n    targetId: Schema.String,\n    selector: Schema.NullOr(Schema.String),\n    property: Schema.String,\n    previousValue: Schema.String,\n    value: Schema.String,\n  });\n\nexport interface PreviewAnnotationScreenshot {\n  dataUrl: string;\n  width: number;\n  height: number;\n  cropRect: PreviewAnnotationRect;\n}\n\nexport const PreviewAnnotationScreenshotSchema: Schema.Codec<PreviewAnnotationScreenshot> =\n  Schema.Struct({\n    dataUrl: Schema.String,\n    width: Schema.Number,\n    height: Schema.Number,\n    cropRect: PreviewAnnotationRectSchema,\n  });\n\n/**\n * A submitted preview annotation. One annotation may reference multiple DOM\n * elements, freeform regions, and ink strokes. The desktop main process adds\n * the screenshot after the guest preload submits the structured draft.\n */\nexport interface PreviewAnnotationPayload {\n  id: string;\n  pageUrl: string;\n  pageTitle: string | null;\n  comment: string;\n  elements: ReadonlyArray<PreviewAnnotationElementTarget>;\n  regions: ReadonlyArray<PreviewAnnotationRegionTarget>;\n  strokes: ReadonlyArray<PreviewAnnotationStrokeTarget>;\n  styleChanges: ReadonlyArray<PreviewAnnotationStyleChange>;\n  screenshot: PreviewAnnotationScreenshot | null;\n  createdAt: string;\n}\n\nexport const PreviewAnnotationPayloadSchema: Schema.Codec<PreviewAnnotationPayload> = Schema.Struct(\n  {\n    id: Schema.String,\n    pageUrl: Schema.String,\n    pageTitle: Schema.NullOr(Schema.String),\n    comment: Schema.String,\n    elements: Schema.Array(PreviewAnnotationElementTargetSchema),\n    regions: Schema.Array(PreviewAnnotationRegionTargetSchema),\n    strokes: Schema.Array(PreviewAnnotationStrokeTargetSchema),\n    styleChanges: Schema.Array(PreviewAnnotationStyleChangeSchema),\n    screenshot: Schema.NullOr(PreviewAnnotationScreenshotSchema),\n    createdAt: Schema.String,\n  },\n);\n\nexport type PreviewAnnotationSubmission = \"attach\" | \"send\";\nexport const PreviewAnnotationSubmissionSchema: Schema.Codec<PreviewAnnotationSubmission> =\n  Schema.Literals([\"attach\", \"send\"]);\n\nexport interface PreviewAnnotationSubmissionResult {\n  annotation: PreviewAnnotationPayload;\n  submission: PreviewAnnotationSubmission;\n}\nexport const PreviewAnnotationSubmissionResultSchema: Schema.Codec<PreviewAnnotationSubmissionResult> =\n  Schema.Struct({\n    annotation: PreviewAnnotationPayloadSchema,\n    submission: PreviewAnnotationSubmissionSchema,\n  });\n\nexport const DesktopPreviewTabInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n});\n\nexport const DesktopPreviewRegisterWebviewInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  webContentsId: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nexport const DesktopPreviewNavigateInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  url: Schema.String,\n});\n\nexport const DesktopPreviewConfigInputSchema = Schema.Struct({\n  environmentId: EnvironmentId,\n});\n\nexport const DesktopPreviewSetColorSchemeInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  colorScheme: DesktopPreviewColorSchemeSchema,\n});\n\nexport const DesktopPreviewAnnotationThemeInputSchema = Schema.Struct({\n  theme: DesktopPreviewAnnotationThemeSchema,\n});\n\nexport const DesktopPreviewArtifactInputSchema = Schema.Struct({\n  path: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),\n});\n\nexport const DesktopPreviewRecordingSaveInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  mimeType: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),\n  data: Schema.Uint8Array,\n});\n\nexport const DesktopPreviewAutomationClickInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationClickInput,\n});\n\nexport const DesktopPreviewAutomationTypeInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationTypeInput,\n});\n\nexport const DesktopPreviewAutomationPressInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationPressInput,\n});\n\nexport const DesktopPreviewAutomationScrollInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationScrollInput,\n});\n\nexport const DesktopPreviewAutomationEvaluateInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationEvaluateInput,\n});\n\nexport const DesktopPreviewAutomationWaitForInputSchema = Schema.Struct({\n  tabId: DesktopPreviewTabIdSchema,\n  input: PreviewAutomationWaitForInput,\n});\n\nexport interface DesktopBridge {\n  getAppBranding: () => DesktopAppBranding | null;\n  // One bootstrap per pool instance currently registered with bootstrap\n  // info (omits instances whose backend hasn't produced a config yet).\n  // The primary backend is identified by id === PRIMARY_LOCAL_ENVIRONMENT_ID.\n  getLocalEnvironmentBootstraps: () => readonly DesktopEnvironmentBootstrap[];\n  getLocalEnvironmentBearerToken: () => Promise<string>;\n  getClientSettings: () => Promise<ClientSettings | null>;\n  setClientSettings: (settings: ClientSettings) => Promise<void>;\n  getConnectionCatalog?: () => Promise<string | null>;\n  setConnectionCatalog?: (catalog: string) => Promise<boolean>;\n  clearConnectionCatalog?: () => Promise<void>;\n  discoverSshHosts: () => Promise<readonly DesktopDiscoveredSshHost[]>;\n  ensureSshEnvironment: (\n    target: DesktopSshEnvironmentTarget,\n    options?: { issuePairingToken?: boolean },\n  ) => Promise<DesktopSshEnvironmentBootstrap>;\n  disconnectSshEnvironment: (target: DesktopSshEnvironmentTarget) => Promise<void>;\n  fetchSshEnvironmentDescriptor: (httpBaseUrl: string) => Promise<ExecutionEnvironmentDescriptor>;\n  bootstrapSshBearerSession: (\n    httpBaseUrl: string,\n    credential: string,\n  ) => Promise<AuthAccessTokenResult>;\n  fetchSshSessionState: (httpBaseUrl: string, bearerToken: string) => Promise<AuthSessionState>;\n  issueSshWebSocketTicket: (\n    httpBaseUrl: string,\n    bearerToken: string,\n  ) => Promise<AuthWebSocketTicketResult>;\n  onSshPasswordPrompt: (listener: (request: DesktopSshPasswordPromptRequest) => void) => () => void;\n  resolveSshPasswordPrompt: (requestId: string, password: string | null) => Promise<void>;\n  getServerExposureState: () => Promise<DesktopServerExposureState>;\n  setServerExposureMode: (mode: DesktopServerExposureMode) => Promise<DesktopServerExposureState>;\n  setTailscaleServeEnabled: (input: {\n    readonly enabled: boolean;\n    readonly port?: number;\n  }) => Promise<DesktopServerExposureState>;\n  getAdvertisedEndpoints: () => Promise<readonly AdvertisedEndpoint[]>;\n  getWslState: () => Promise<DesktopWslState>;\n  setWslBackendEnabled: (enabled: boolean) => Promise<DesktopWslState>;\n  setWslDistro: (distro: string | null) => Promise<DesktopWslState>;\n  setWslOnly: (enabled: boolean) => Promise<DesktopWslState>;\n  pickFolder: (options?: PickFolderOptions) => Promise<string | null>;\n  /**\n   * Multi-select JSON file picker that opens in the VS Code extensions\n   * directory when one exists. Optional: older desktop builds lack it, and\n   * web callers fall back to a plain file input.\n   */\n  pickThemeFiles?: () => Promise<readonly PickedThemeFile[] | null>;\n  confirm: (message: string) => Promise<boolean>;\n  setTheme: (theme: DesktopTheme) => Promise<void>;\n  showContextMenu: <T extends string>(\n    items: readonly ContextMenuItem<T>[],\n    position?: { x: number; y: number },\n  ) => Promise<T | null>;\n  openExternal: (url: string) => Promise<boolean>;\n  onMenuAction: (listener: (action: string) => void) => () => void;\n  getWindowFullscreenState: () => boolean;\n  onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void;\n  getUpdateState: () => Promise<DesktopUpdateState>;\n  setUpdateChannel: (channel: DesktopUpdateChannel) => Promise<DesktopUpdateState>;\n  checkForUpdate: () => Promise<DesktopUpdateCheckResult>;\n  downloadUpdate: () => Promise<DesktopUpdateActionResult>;\n  installUpdate: () => Promise<DesktopUpdateActionResult>;\n  onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void;\n  /**\n   * Desktop-only preview surface. Present iff the renderer is hosted by the\n   * Electron desktop build; web builds have `preview === undefined`.\n   */\n  preview?: DesktopPreviewBridge;\n}\n\nexport interface DesktopPreviewBridge {\n  createTab: (tabId: string) => Promise<void>;\n  closeTab: (tabId: string) => Promise<void>;\n  registerWebview: (tabId: string, webContentsId: number) => Promise<void>;\n  navigate: (tabId: string, url: string) => Promise<void>;\n  goBack: (tabId: string) => Promise<void>;\n  goForward: (tabId: string) => Promise<void>;\n  refresh: (tabId: string) => Promise<void>;\n  zoomIn: (tabId: string) => Promise<void>;\n  zoomOut: (tabId: string) => Promise<void>;\n  resetZoom: (tabId: string) => Promise<void>;\n  /** Reload bypassing the HTTP cache. */\n  hardReload: (tabId: string) => Promise<void>;\n  /**\n   * Emulate `prefers-color-scheme` on the guest page (\"system\" clears the\n   * override). Persists per tab and is re-applied across webview swaps.\n   */\n  setColorScheme: (tabId: string, colorScheme: DesktopPreviewColorScheme) => Promise<void>;\n  /** Open the guest webview's DevTools (detached). */\n  openDevTools: (tabId: string) => Promise<void>;\n  /** Drop cookies + storage data for the preview partition (all tabs). */\n  clearCookies: () => Promise<void>;\n  /** Drop the HTTP cache for the preview partition (all tabs). */\n  clearCache: () => Promise<void>;\n  /**\n   * One-shot config for mounting a preview `<webview>`. Replaces three\n   * earlier round-trip calls (`getBrowserPartition`, `getWebviewPreferences`,\n   * `getPickPreloadPath`) so adding a new field here only requires touching\n   * the contract + main, not the renderer's mount logic.\n   */\n  getPreviewConfig: (environmentId: EnvironmentId) => Promise<DesktopPreviewWebviewConfig>;\n  setAnnotationTheme: (theme: DesktopPreviewAnnotationTheme) => Promise<void>;\n  /**\n   * Activate the in-page element picker for the given tab. Resolves with\n   * the picked annotation and its attach/send intent, or `null` when the\n   * user cancels (Escape / nav). The promise rejects if the picker can't be\n   * activated (no webview, etc.).\n   */\n  pickElement: (tabId: string) => Promise<PreviewAnnotationSubmissionResult | null>;\n  /** Cancel an in-flight preview annotation session. */\n  cancelPickElement: (tabId: string) => Promise<void>;\n  captureScreenshot: (tabId: string) => Promise<DesktopPreviewScreenshotArtifact>;\n  revealArtifact: (path: string) => Promise<void>;\n  copyArtifactToClipboard: (path: string) => Promise<void>;\n  pictureInPicture: {\n    open: (tabId: string) => Promise<void>;\n    close: (tabId: string) => Promise<void>;\n  };\n  recording: {\n    startScreencast: (tabId: string) => Promise<void>;\n    stopScreencast: (tabId: string) => Promise<void>;\n    save: (\n      tabId: string,\n      mimeType: string,\n      data: Uint8Array,\n    ) => Promise<DesktopPreviewRecordingArtifact>;\n    onFrame: (listener: (frame: DesktopPreviewRecordingFrame) => void) => () => void;\n  };\n  automation: {\n    status: (tabId: string) => Promise<PreviewAutomationStatus>;\n    snapshot: (tabId: string) => Promise<PreviewAutomationSnapshot>;\n    click: (tabId: string, input: PreviewAutomationClickInput) => Promise<void>;\n    type: (tabId: string, input: PreviewAutomationTypeInput) => Promise<void>;\n    press: (tabId: string, input: PreviewAutomationPressInput) => Promise<void>;\n    scroll: (tabId: string, input: PreviewAutomationScrollInput) => Promise<void>;\n    evaluate: (tabId: string, input: PreviewAutomationEvaluateInput) => Promise<unknown>;\n    waitFor: (tabId: string, input: PreviewAutomationWaitForInput) => Promise<void>;\n  };\n  onStateChange: (listener: (tabId: string, state: DesktopPreviewTabState) => void) => () => void;\n  onPointerEvent: (listener: (event: DesktopPreviewPointerEvent) => void) => () => void;\n}\n\n/**\n * APIs bound to the local app shell, not to any particular backend environment.\n *\n * These capabilities describe the desktop/browser host that the user is\n * currently running: dialogs, external-link opening, context menus, and\n * app-level settings/config access. They must not be used as a proxy for\n * \"whatever environment the user is targeting\", because in a multi-environment\n * world the local shell and a selected backend environment are distinct\n * concepts.\n */\nexport interface LocalApi {\n  dialogs: {\n    pickFolder: (options?: PickFolderOptions) => Promise<string | null>;\n    confirm: (message: string) => Promise<boolean>;\n  };\n  shell: {\n    openExternal: (url: string) => Promise<void>;\n  };\n  contextMenu: {\n    show: <T extends string>(\n      items: readonly ContextMenuItem<T>[],\n      position?: { x: number; y: number },\n    ) => Promise<T | null>;\n  };\n  persistence: {\n    getClientSettings: () => Promise<ClientSettings | null>;\n    setClientSettings: (settings: ClientSettings) => Promise<void>;\n  };\n}\n\n/**\n * APIs bound to a specific backend environment connection.\n *\n * These operations must always be routed with explicit environment context.\n * They represent remote stateful capabilities such as orchestration, terminal,\n * project, VCS, and provider operations. In multi-environment mode, each environment gets\n * its own instance of this surface, and callers should resolve it by\n * `environmentId` rather than reaching through the local desktop bridge.\n */\nexport interface EnvironmentApi {\n  terminal: {\n    open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;\n    attach: (\n      input: typeof TerminalAttachInput.Encoded,\n      callback: (event: TerminalAttachStreamEvent) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n    write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;\n    resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;\n    clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;\n    restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;\n    close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;\n    onMetadata: (\n      callback: (event: TerminalMetadataStreamEvent) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n  };\n  projects: {\n    listEntries: (input: ProjectListEntriesInput) => Promise<ProjectListEntriesResult>;\n    readFile: (input: ProjectReadFileInput) => Promise<ProjectReadFileResult>;\n    searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;\n    writeFile: (input: ProjectWriteFileInput) => Promise<ProjectWriteFileResult>;\n  };\n  filesystem: {\n    browse: (input: FilesystemBrowseInput) => Promise<FilesystemBrowseResult>;\n  };\n  assets: {\n    createUrl: (input: AssetCreateUrlInput) => Promise<AssetCreateUrlResult>;\n  };\n  sourceControl: {\n    lookupRepository: (\n      input: SourceControlRepositoryLookupInput,\n    ) => Promise<SourceControlRepositoryInfo>;\n    cloneRepository: (\n      input: SourceControlCloneRepositoryInput,\n    ) => Promise<SourceControlCloneRepositoryResult>;\n    publishRepository: (\n      input: SourceControlPublishRepositoryInput,\n    ) => Promise<SourceControlPublishRepositoryResult>;\n  };\n  vcs: {\n    listRefs: (input: VcsListRefsInput) => Promise<VcsListRefsResult>;\n    createWorktree: (input: VcsCreateWorktreeInput) => Promise<VcsCreateWorktreeResult>;\n    removeWorktree: (input: VcsRemoveWorktreeInput) => Promise<void>;\n    createRef: (input: VcsCreateRefInput) => Promise<VcsCreateRefResult>;\n    switchRef: (input: VcsSwitchRefInput) => Promise<VcsSwitchRefResult>;\n    init: (input: VcsInitInput) => Promise<void>;\n    pull: (input: VcsPullInput) => Promise<VcsPullResult>;\n    refreshStatus: (input: VcsStatusInput) => Promise<VcsStatusResult>;\n    onStatus: (\n      input: VcsStatusInput,\n      callback: (status: VcsStatusResult) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n  };\n  git: {\n    resolvePullRequest: (input: GitPullRequestRefInput) => Promise<GitResolvePullRequestResult>;\n    preparePullRequestThread: (\n      input: GitPreparePullRequestThreadInput,\n    ) => Promise<GitPreparePullRequestThreadResult>;\n  };\n  review: {\n    getDiffPreview: (input: ReviewDiffPreviewInput) => Promise<ReviewDiffPreviewResult>;\n    getDiffFileContents: (\n      input: ReviewDiffFileContentsInput,\n    ) => Promise<ReviewDiffFileContentsResult>;\n  };\n  orchestration: {\n    dispatchCommand: (command: ClientOrchestrationCommand) => Promise<{ sequence: number }>;\n    getTurnDiff: (input: OrchestrationGetTurnDiffInput) => Promise<OrchestrationGetTurnDiffResult>;\n    getFullThreadDiff: (\n      input: OrchestrationGetFullThreadDiffInput,\n    ) => Promise<OrchestrationGetFullThreadDiffResult>;\n    getArchivedShellSnapshot: () => Promise<OrchestrationShellSnapshot>;\n    subscribeShell: (\n      callback: (event: OrchestrationShellStreamItem) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n    subscribeThread: (\n      input: OrchestrationSubscribeThreadInput,\n      callback: (event: OrchestrationThreadStreamItem) => void,\n      options?: {\n        onResubscribe?: () => void;\n      },\n    ) => () => void;\n  };\n  preview: {\n    open: (input: typeof PreviewOpenInput.Encoded) => Promise<PreviewSessionSnapshot>;\n    navigate: (input: typeof PreviewNavigateInput.Encoded) => Promise<PreviewSessionSnapshot>;\n    resize: (input: typeof PreviewResizeInput.Encoded) => Promise<PreviewSessionSnapshot>;\n    refresh: (input: typeof PreviewRefreshInput.Encoded) => Promise<void>;\n    close: (input: typeof PreviewCloseInput.Encoded) => Promise<void>;\n    list: (input: typeof PreviewListInput.Encoded) => Promise<PreviewListResult>;\n    reportStatus: (input: typeof PreviewReportStatusInput.Encoded) => Promise<void>;\n    automation: {\n      connect: (\n        input: PreviewAutomationHost,\n        callback: (event: PreviewAutomationStreamEvent) => void,\n        options?: { onResubscribe?: () => void },\n      ) => () => void;\n      respond: (response: PreviewAutomationResponse) => Promise<void>;\n      focusHost: (input: PreviewAutomationHostFocus) => Promise<void>;\n    };\n    onEvent: (\n      callback: (event: PreviewEvent) => void,\n      options?: { onResubscribe?: () => void },\n    ) => () => void;\n    subscribePorts: (\n      callback: (servers: DiscoveredLocalServerList) => void,\n      options?: { onResubscribe?: () => void },\n    ) => () => void;\n  };\n}\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\n/**\n * Client-side id for the first shell opened on a thread. Ids are uniformly\n * `term-N`; there's no \"default\" intrinsic. Kept as a named constant so callers\n * that want \"the primary shell\" don't hardcode `\"term-1\"`.\n */\nexport const DEFAULT_TERMINAL_ID = \"term-1\";\n\nconst TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;\nconst TerminalColsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check(\n  Schema.isLessThanOrEqualTo(1000),\n);\nconst TerminalRowsSchema = Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)).check(\n  Schema.isLessThanOrEqualTo(500),\n);\nconst TerminalIdSchema = TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(128));\nconst TerminalEnvKeySchema = Schema.String.check(\n  Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/),\n).check(Schema.isMaxLength(128));\nconst TerminalEnvValueSchema = Schema.String.check(Schema.isMaxLength(8_192));\nconst TerminalEnvSchema = Schema.Record(TerminalEnvKeySchema, TerminalEnvValueSchema).check(\n  Schema.isMaxProperties(128),\n);\n\nexport const TerminalThreadInput = Schema.Struct({\n  threadId: TrimmedNonEmptyStringSchema,\n});\nexport type TerminalThreadInput = typeof TerminalThreadInput.Type;\n\n/** Terminal ids are ALWAYS chosen by the client and sent explicitly — no server-side allocation. */\nconst TerminalSessionInput = Schema.Struct({\n  ...TerminalThreadInput.fields,\n  terminalId: TerminalIdSchema,\n});\nexport type TerminalSessionInput = Schema.Codec.Encoded<typeof TerminalSessionInput>;\n\nexport const TerminalOpenInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  cwd: TrimmedNonEmptyStringSchema,\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  cols: Schema.optional(TerminalColsSchema),\n  rows: Schema.optional(TerminalRowsSchema),\n  env: Schema.optional(TerminalEnvSchema),\n});\nexport type TerminalOpenInput = Schema.Codec.Encoded<typeof TerminalOpenInput>;\n\nexport const TerminalAttachInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  cwd: Schema.optional(TrimmedNonEmptyStringSchema),\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  cols: Schema.optional(TerminalColsSchema),\n  rows: Schema.optional(TerminalRowsSchema),\n  env: Schema.optional(TerminalEnvSchema),\n  restartIfNotRunning: Schema.optional(Schema.Boolean),\n});\nexport type TerminalAttachInput = Schema.Codec.Encoded<typeof TerminalAttachInput>;\n\nexport const TerminalWriteInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  data: Schema.String.check(Schema.isNonEmpty()).check(Schema.isMaxLength(65_536)),\n});\nexport type TerminalWriteInput = Schema.Codec.Encoded<typeof TerminalWriteInput>;\n\nexport const TerminalResizeInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  cols: TerminalColsSchema,\n  rows: TerminalRowsSchema,\n});\nexport type TerminalResizeInput = Schema.Codec.Encoded<typeof TerminalResizeInput>;\n\nexport const TerminalClearInput = TerminalSessionInput;\nexport type TerminalClearInput = Schema.Codec.Encoded<typeof TerminalClearInput>;\n\nexport const TerminalRestartInput = Schema.Struct({\n  ...TerminalSessionInput.fields,\n  cwd: TrimmedNonEmptyStringSchema,\n  worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  cols: TerminalColsSchema,\n  rows: TerminalRowsSchema,\n  env: Schema.optional(TerminalEnvSchema),\n});\nexport type TerminalRestartInput = Schema.Codec.Encoded<typeof TerminalRestartInput>;\n\nexport const TerminalCloseInput = Schema.Struct({\n  ...TerminalThreadInput.fields,\n  terminalId: Schema.optional(TerminalIdSchema),\n  deleteHistory: Schema.optional(Schema.Boolean),\n});\nexport type TerminalCloseInput = typeof TerminalCloseInput.Type;\n\nexport const TerminalSessionStatus = Schema.Literals([\"starting\", \"running\", \"exited\", \"error\"]);\nexport type TerminalSessionStatus = typeof TerminalSessionStatus.Type;\n\nexport const TerminalSessionSnapshot = Schema.Struct({\n  threadId: Schema.String.check(Schema.isNonEmpty()),\n  terminalId: Schema.String.check(Schema.isNonEmpty()),\n  cwd: Schema.String.check(Schema.isNonEmpty()),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),\n  status: TerminalSessionStatus,\n  pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),\n  history: Schema.String,\n  exitCode: Schema.NullOr(Schema.Int),\n  exitSignal: Schema.NullOr(Schema.Int),\n  /** Server-computed display title (idle shell vs subprocess command). */\n  label: Schema.String.check(Schema.isMaxLength(128)),\n  updatedAt: Schema.String,\n  sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n});\nexport type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type;\n\nexport const TerminalSummary = Schema.Struct({\n  threadId: Schema.String.check(Schema.isNonEmpty()),\n  terminalId: Schema.String.check(Schema.isNonEmpty()),\n  cwd: Schema.String.check(Schema.isNonEmpty()),\n  worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),\n  status: TerminalSessionStatus,\n  pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),\n  exitCode: Schema.NullOr(Schema.Int),\n  exitSignal: Schema.NullOr(Schema.Int),\n  hasRunningSubprocess: Schema.Boolean,\n  /** Server-computed display title (idle shell vs subprocess command). */\n  label: Schema.String.check(Schema.isMaxLength(128)),\n  updatedAt: Schema.String,\n});\nexport type TerminalSummary = typeof TerminalSummary.Type;\n\nconst TerminalMetadataSnapshotEvent = Schema.Struct({\n  type: Schema.Literal(\"snapshot\"),\n  terminals: Schema.Array(TerminalSummary),\n});\n\nconst TerminalMetadataUpsertEvent = Schema.Struct({\n  type: Schema.Literal(\"upsert\"),\n  terminal: TerminalSummary,\n});\n\nconst TerminalMetadataRemoveEvent = Schema.Struct({\n  type: Schema.Literal(\"remove\"),\n  threadId: Schema.String.check(Schema.isNonEmpty()),\n  terminalId: Schema.String.check(Schema.isNonEmpty()),\n});\n\nexport const TerminalMetadataStreamEvent = Schema.Union([\n  TerminalMetadataSnapshotEvent,\n  TerminalMetadataUpsertEvent,\n  TerminalMetadataRemoveEvent,\n]);\nexport type TerminalMetadataStreamEvent = typeof TerminalMetadataStreamEvent.Type;\n\nconst TerminalEventBaseSchema = Schema.Struct({\n  threadId: Schema.String.check(Schema.isNonEmpty()),\n  terminalId: Schema.String.check(Schema.isNonEmpty()),\n  sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n});\n\nconst TerminalStartedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"started\"),\n  snapshot: TerminalSessionSnapshot,\n});\n\nconst TerminalOutputEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"output\"),\n  data: Schema.String,\n});\n\nconst TerminalExitedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"exited\"),\n  exitCode: Schema.NullOr(Schema.Int),\n  exitSignal: Schema.NullOr(Schema.Int),\n});\n\nconst TerminalClosedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"closed\"),\n});\n\nconst TerminalErrorEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"error\"),\n  message: Schema.String.check(Schema.isNonEmpty()),\n});\n\nconst TerminalClearedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"cleared\"),\n});\n\nconst TerminalRestartedEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"restarted\"),\n  snapshot: TerminalSessionSnapshot,\n});\n\nconst TerminalActivityEvent = Schema.Struct({\n  ...TerminalEventBaseSchema.fields,\n  type: Schema.Literal(\"activity\"),\n  hasRunningSubprocess: Schema.Boolean,\n  label: Schema.String.check(Schema.isMaxLength(128)),\n});\n\nexport const TerminalEvent = Schema.Union([\n  TerminalStartedEvent,\n  TerminalOutputEvent,\n  TerminalExitedEvent,\n  TerminalClosedEvent,\n  TerminalErrorEvent,\n  TerminalClearedEvent,\n  TerminalRestartedEvent,\n  TerminalActivityEvent,\n]);\nexport type TerminalEvent = typeof TerminalEvent.Type;\n\nconst TerminalAttachSnapshotEvent = Schema.Struct({\n  type: Schema.Literal(\"snapshot\"),\n  snapshot: TerminalSessionSnapshot,\n});\n\nexport const TerminalAttachStreamEvent = Schema.Union([\n  TerminalAttachSnapshotEvent,\n  TerminalOutputEvent,\n  TerminalExitedEvent,\n  TerminalClosedEvent,\n  TerminalErrorEvent,\n  TerminalClearedEvent,\n  TerminalRestartedEvent,\n  TerminalActivityEvent,\n]);\nexport type TerminalAttachStreamEvent = typeof TerminalAttachStreamEvent.Type;\n\nexport class TerminalCwdNotFoundError extends Schema.TaggedErrorClass<TerminalCwdNotFoundError>()(\n  \"TerminalCwdNotFoundError\",\n  {\n    cwd: Schema.String,\n  },\n) {\n  override get message() {\n    return `Terminal cwd does not exist: ${this.cwd}`;\n  }\n}\n\nexport class TerminalCwdNotDirectoryError extends Schema.TaggedErrorClass<TerminalCwdNotDirectoryError>()(\n  \"TerminalCwdNotDirectoryError\",\n  {\n    cwd: Schema.String,\n  },\n) {\n  override get message() {\n    return `Terminal cwd is not a directory: ${this.cwd}`;\n  }\n}\n\nexport class TerminalCwdStatError extends Schema.TaggedErrorClass<TerminalCwdStatError>()(\n  \"TerminalCwdStatError\",\n  {\n    cwd: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Failed to access terminal cwd: ${this.cwd}`;\n  }\n}\n\nexport const TerminalCwdError = Schema.Union([\n  TerminalCwdNotFoundError,\n  TerminalCwdNotDirectoryError,\n  TerminalCwdStatError,\n]);\nexport type TerminalCwdError = typeof TerminalCwdError.Type;\n\nexport class TerminalHistoryError extends Schema.TaggedErrorClass<TerminalHistoryError>()(\n  \"TerminalHistoryError\",\n  {\n    operation: Schema.Literals([\"read\", \"truncate\", \"migrate\"]),\n    threadId: Schema.String,\n    terminalId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message() {\n    return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;\n  }\n}\n\nexport class TerminalSessionLookupError extends Schema.TaggedErrorClass<TerminalSessionLookupError>()(\n  \"TerminalSessionLookupError\",\n  {\n    threadId: Schema.String,\n    terminalId: Schema.String,\n  },\n) {\n  override get message() {\n    return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;\n  }\n}\n\nexport class TerminalNotRunningError extends Schema.TaggedErrorClass<TerminalNotRunningError>()(\n  \"TerminalNotRunningError\",\n  {\n    threadId: Schema.String,\n    terminalId: Schema.String,\n  },\n) {\n  override get message() {\n    return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;\n  }\n}\n\nexport class TerminalWriteError extends Schema.TaggedErrorClass<TerminalWriteError>()(\n  \"TerminalWriteError\",\n  {\n    threadId: Schema.String,\n    terminalId: Schema.String,\n    terminalPid: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Failed to write to terminal for thread: ${this.threadId}, terminal: ${this.terminalId}, PID: ${this.terminalPid}`;\n  }\n}\n\nexport class TerminalResizeError extends Schema.TaggedErrorClass<TerminalResizeError>()(\n  \"TerminalResizeError\",\n  {\n    threadId: Schema.String,\n    terminalId: Schema.String,\n    terminalPid: Schema.Number,\n    cols: TerminalColsSchema,\n    rows: TerminalRowsSchema,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Failed to resize terminal for thread: ${this.threadId}, terminal: ${this.terminalId}, PID: ${this.terminalPid} to ${this.cols}x${this.rows}`;\n  }\n}\n\nexport const TerminalError = Schema.Union([\n  TerminalCwdError,\n  TerminalHistoryError,\n  TerminalSessionLookupError,\n  TerminalNotRunningError,\n  TerminalWriteError,\n  TerminalResizeError,\n]);\nexport type TerminalError = typeof TerminalError.Type;\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport {\n  ApprovalRequestId,\n  EventId,\n  IsoDateTime,\n  ProviderItemId,\n  ThreadId,\n  TurnId,\n} from \"./baseSchemas.ts\";\nimport {\n  ChatAttachment,\n  ModelSelection,\n  PROVIDER_SEND_TURN_MAX_ATTACHMENTS,\n  PROVIDER_SEND_TURN_MAX_INPUT_CHARS,\n  ProviderApprovalDecision,\n  ProviderApprovalPolicy,\n  ProviderInteractionMode,\n  ProviderRequestKind,\n  ProviderSandboxMode,\n  ProviderUserInputAnswers,\n  RuntimeMode,\n} from \"./orchestration.ts\";\nimport { ProviderInstanceId, ProviderDriverKind } from \"./providerInstance.ts\";\n\nconst ProviderSessionStatus = Schema.Literals([\n  \"connecting\",\n  \"ready\",\n  \"running\",\n  \"error\",\n  \"closed\",\n]);\n\nexport const ProviderSession = Schema.Struct({\n  provider: ProviderDriverKind,\n  // Optional during the driver/instance migration. Once every producer\n  // populates it (post-slice-4), routing flips to instance-id-only and the\n  // legacy `provider` field is removed.\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  status: ProviderSessionStatus,\n  runtimeMode: RuntimeMode,\n  cwd: Schema.optional(TrimmedNonEmptyString),\n  model: Schema.optional(TrimmedNonEmptyString),\n  threadId: ThreadId,\n  resumeCursor: Schema.optional(Schema.Unknown),\n  activeTurnId: Schema.optional(TurnId),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  lastError: Schema.optional(TrimmedNonEmptyString),\n});\nexport type ProviderSession = typeof ProviderSession.Type;\n\nexport const ProviderSessionStartInput = Schema.Struct({\n  threadId: ThreadId,\n  provider: Schema.optional(ProviderDriverKind),\n  // See ProviderSession for the migration story.\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  cwd: Schema.optional(TrimmedNonEmptyString),\n  modelSelection: Schema.optional(ModelSelection),\n  resumeCursor: Schema.optional(Schema.Unknown),\n  approvalPolicy: Schema.optional(ProviderApprovalPolicy),\n  sandboxMode: Schema.optional(ProviderSandboxMode),\n  runtimeMode: RuntimeMode,\n});\nexport type ProviderSessionStartInput = typeof ProviderSessionStartInput.Type;\n\nexport const ProviderSendTurnInput = Schema.Struct({\n  threadId: ThreadId,\n  input: Schema.optional(\n    TrimmedNonEmptyString.check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS)),\n  ),\n  attachments: Schema.optional(\n    Schema.Array(ChatAttachment).check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_ATTACHMENTS)),\n  ),\n  modelSelection: Schema.optional(ModelSelection),\n  interactionMode: Schema.optional(ProviderInteractionMode),\n});\nexport type ProviderSendTurnInput = typeof ProviderSendTurnInput.Type;\n\nexport const ProviderTurnStartResult = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  resumeCursor: Schema.optional(Schema.Unknown),\n});\nexport type ProviderTurnStartResult = typeof ProviderTurnStartResult.Type;\n\nexport const ProviderInterruptTurnInput = Schema.Struct({\n  threadId: ThreadId,\n  turnId: Schema.optional(TurnId),\n});\nexport type ProviderInterruptTurnInput = typeof ProviderInterruptTurnInput.Type;\n\nexport const ProviderStopSessionInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ProviderStopSessionInput = typeof ProviderStopSessionInput.Type;\n\nexport const ProviderRespondToRequestInput = Schema.Struct({\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  decision: ProviderApprovalDecision,\n});\nexport type ProviderRespondToRequestInput = typeof ProviderRespondToRequestInput.Type;\n\nexport const ProviderRespondToUserInputInput = Schema.Struct({\n  threadId: ThreadId,\n  requestId: ApprovalRequestId,\n  answers: ProviderUserInputAnswers,\n});\nexport type ProviderRespondToUserInputInput = typeof ProviderRespondToUserInputInput.Type;\n\nconst ProviderEventKind = Schema.Literals([\"session\", \"notification\", \"request\", \"error\"]);\n\nexport const ProviderEvent = Schema.Struct({\n  id: EventId,\n  kind: ProviderEventKind,\n  provider: ProviderDriverKind,\n  // See ProviderSession for the migration story.\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  threadId: ThreadId,\n  createdAt: IsoDateTime,\n  method: TrimmedNonEmptyString,\n  message: Schema.optional(TrimmedNonEmptyString),\n  turnId: Schema.optional(TurnId),\n  itemId: Schema.optional(ProviderItemId),\n  requestId: Schema.optional(ApprovalRequestId),\n  requestKind: Schema.optional(ProviderRequestKind),\n  textDelta: Schema.optional(Schema.String),\n  payload: Schema.optional(Schema.Unknown),\n});\nexport type ProviderEvent = typeof ProviderEvent.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport {\n  EventId,\n  IsoDateTime,\n  NonNegativeInt,\n  ProviderItemId,\n  PositiveInt,\n  RuntimeItemId,\n  RuntimeRequestId,\n  RuntimeTaskId,\n  ThreadId,\n  TrimmedNonEmptyString,\n  TurnId,\n} from \"./baseSchemas.ts\";\nimport { ProviderInstanceId, ProviderDriverKind } from \"./providerInstance.ts\";\n\nconst TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;\nconst UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);\n\nconst RuntimeEventRawSource = Schema.Union([\n  Schema.Literal(\"codex.app-server.notification\"),\n  Schema.Literal(\"codex.app-server.request\"),\n  Schema.Literal(\"codex.eventmsg\"),\n  Schema.Literal(\"claude.sdk.message\"),\n  Schema.Literal(\"claude.sdk.permission\"),\n  Schema.Literal(\"codex.sdk.thread-event\"),\n  Schema.Literal(\"opencode.sdk.event\"),\n  Schema.Literal(\"acp.jsonrpc\"),\n  Schema.TemplateLiteral([\"acp.\", Schema.String, \".extension\"]),\n]);\nexport type RuntimeEventRawSource = typeof RuntimeEventRawSource.Type;\n\nexport const RuntimeEventRaw = Schema.Struct({\n  source: RuntimeEventRawSource,\n  method: Schema.optional(TrimmedNonEmptyStringSchema),\n  messageType: Schema.optional(TrimmedNonEmptyStringSchema),\n  payload: Schema.Unknown,\n});\nexport type RuntimeEventRaw = typeof RuntimeEventRaw.Type;\n\nconst ProviderRequestId = TrimmedNonEmptyStringSchema;\nexport type ProviderRequestId = typeof ProviderRequestId.Type;\n\nconst ProviderRefs = Schema.Struct({\n  providerTurnId: Schema.optional(TrimmedNonEmptyStringSchema),\n  providerItemId: Schema.optional(ProviderItemId),\n  providerRequestId: Schema.optional(ProviderRequestId),\n});\nexport type ProviderRefs = typeof ProviderRefs.Type;\n\nconst RuntimeSessionState = Schema.Literals([\n  \"starting\",\n  \"ready\",\n  \"running\",\n  \"waiting\",\n  \"stopped\",\n  \"error\",\n]);\nexport type RuntimeSessionState = typeof RuntimeSessionState.Type;\n\nconst RuntimeThreadState = Schema.Literals([\n  \"active\",\n  \"idle\",\n  \"archived\",\n  \"closed\",\n  \"compacted\",\n  \"error\",\n]);\nexport type RuntimeThreadState = typeof RuntimeThreadState.Type;\n\nconst RuntimeTurnState = Schema.Literals([\"completed\", \"failed\", \"interrupted\", \"cancelled\"]);\nexport type RuntimeTurnState = typeof RuntimeTurnState.Type;\n\nconst RuntimePlanStepStatus = Schema.Literals([\"pending\", \"inProgress\", \"completed\"]);\nexport type RuntimePlanStepStatus = typeof RuntimePlanStepStatus.Type;\n\nconst RuntimeItemStatus = Schema.Literals([\"inProgress\", \"completed\", \"failed\", \"declined\"]);\nexport type RuntimeItemStatus = typeof RuntimeItemStatus.Type;\n\nconst RuntimeContentStreamKind = Schema.Literals([\n  \"assistant_text\",\n  \"reasoning_text\",\n  \"reasoning_summary_text\",\n  \"plan_text\",\n  \"command_output\",\n  \"file_change_output\",\n  \"unknown\",\n]);\nexport type RuntimeContentStreamKind = typeof RuntimeContentStreamKind.Type;\n\nconst RuntimeSessionExitKind = Schema.Literals([\"graceful\", \"error\"]);\nexport type RuntimeSessionExitKind = typeof RuntimeSessionExitKind.Type;\n\nconst RuntimeErrorClass = Schema.Literals([\n  \"provider_error\",\n  \"transport_error\",\n  \"permission_error\",\n  \"validation_error\",\n  \"unknown\",\n]);\nexport type RuntimeErrorClass = typeof RuntimeErrorClass.Type;\n\nexport const TOOL_LIFECYCLE_ITEM_TYPES = [\n  \"command_execution\",\n  \"file_change\",\n  \"mcp_tool_call\",\n  \"dynamic_tool_call\",\n  \"collab_agent_tool_call\",\n  \"web_search\",\n  \"image_view\",\n] as const;\n\nexport const ToolLifecycleItemType = Schema.Literals(TOOL_LIFECYCLE_ITEM_TYPES);\nexport type ToolLifecycleItemType = typeof ToolLifecycleItemType.Type;\n\nexport function isToolLifecycleItemType(value: string): value is ToolLifecycleItemType {\n  return TOOL_LIFECYCLE_ITEM_TYPES.includes(value as ToolLifecycleItemType);\n}\n\nexport const CanonicalItemType = Schema.Literals([\n  \"user_message\",\n  \"assistant_message\",\n  \"reasoning\",\n  \"plan\",\n  ...TOOL_LIFECYCLE_ITEM_TYPES,\n  \"review_entered\",\n  \"review_exited\",\n  \"context_compaction\",\n  \"error\",\n  \"unknown\",\n]);\nexport type CanonicalItemType = typeof CanonicalItemType.Type;\n\nexport const CanonicalRequestType = Schema.Literals([\n  \"command_execution_approval\",\n  \"file_read_approval\",\n  \"file_change_approval\",\n  \"apply_patch_approval\",\n  \"exec_command_approval\",\n  \"tool_user_input\",\n  \"dynamic_tool_call\",\n  \"auth_tokens_refresh\",\n  \"unknown\",\n]);\nexport type CanonicalRequestType = typeof CanonicalRequestType.Type;\n\nconst ProviderRuntimeEventType = Schema.Literals([\n  \"session.started\",\n  \"session.configured\",\n  \"session.state.changed\",\n  \"session.exited\",\n  \"thread.started\",\n  \"thread.state.changed\",\n  \"thread.metadata.updated\",\n  \"thread.token-usage.updated\",\n  \"thread.realtime.started\",\n  \"thread.realtime.item-added\",\n  \"thread.realtime.audio.delta\",\n  \"thread.realtime.error\",\n  \"thread.realtime.closed\",\n  \"turn.started\",\n  \"turn.completed\",\n  \"turn.aborted\",\n  \"turn.plan.updated\",\n  \"turn.proposed.delta\",\n  \"turn.proposed.completed\",\n  \"turn.diff.updated\",\n  \"item.started\",\n  \"item.updated\",\n  \"item.completed\",\n  \"content.delta\",\n  \"request.opened\",\n  \"request.resolved\",\n  \"user-input.requested\",\n  \"user-input.resolved\",\n  \"task.started\",\n  \"task.progress\",\n  \"task.updated\",\n  \"task.completed\",\n  \"hook.started\",\n  \"hook.progress\",\n  \"hook.completed\",\n  \"tool.progress\",\n  \"tool.summary\",\n  \"auth.status\",\n  \"account.updated\",\n  \"account.rate-limits.updated\",\n  \"mcp.status.updated\",\n  \"mcp.oauth.completed\",\n  \"model.rerouted\",\n  \"config.warning\",\n  \"deprecation.notice\",\n  \"files.persisted\",\n  \"runtime.warning\",\n  \"runtime.error\",\n]);\nexport type ProviderRuntimeEventType = typeof ProviderRuntimeEventType.Type;\n\nconst SessionStartedType = Schema.Literal(\"session.started\");\nconst SessionConfiguredType = Schema.Literal(\"session.configured\");\nconst SessionStateChangedType = Schema.Literal(\"session.state.changed\");\nconst SessionExitedType = Schema.Literal(\"session.exited\");\nconst ThreadStartedType = Schema.Literal(\"thread.started\");\nconst ThreadStateChangedType = Schema.Literal(\"thread.state.changed\");\nconst ThreadMetadataUpdatedType = Schema.Literal(\"thread.metadata.updated\");\nconst ThreadTokenUsageUpdatedType = Schema.Literal(\"thread.token-usage.updated\");\nconst ThreadRealtimeStartedType = Schema.Literal(\"thread.realtime.started\");\nconst ThreadRealtimeItemAddedType = Schema.Literal(\"thread.realtime.item-added\");\nconst ThreadRealtimeAudioDeltaType = Schema.Literal(\"thread.realtime.audio.delta\");\nconst ThreadRealtimeErrorType = Schema.Literal(\"thread.realtime.error\");\nconst ThreadRealtimeClosedType = Schema.Literal(\"thread.realtime.closed\");\nconst TurnStartedType = Schema.Literal(\"turn.started\");\nconst TurnCompletedType = Schema.Literal(\"turn.completed\");\nconst TurnAbortedType = Schema.Literal(\"turn.aborted\");\nconst TurnPlanUpdatedType = Schema.Literal(\"turn.plan.updated\");\nconst TurnProposedDeltaType = Schema.Literal(\"turn.proposed.delta\");\nconst TurnProposedCompletedType = Schema.Literal(\"turn.proposed.completed\");\nconst TurnDiffUpdatedType = Schema.Literal(\"turn.diff.updated\");\nconst ItemStartedType = Schema.Literal(\"item.started\");\nconst ItemUpdatedType = Schema.Literal(\"item.updated\");\nconst ItemCompletedType = Schema.Literal(\"item.completed\");\nconst ContentDeltaType = Schema.Literal(\"content.delta\");\nconst RequestOpenedType = Schema.Literal(\"request.opened\");\nconst RequestResolvedType = Schema.Literal(\"request.resolved\");\nconst UserInputRequestedType = Schema.Literal(\"user-input.requested\");\nconst UserInputResolvedType = Schema.Literal(\"user-input.resolved\");\nconst TaskStartedType = Schema.Literal(\"task.started\");\nconst TaskProgressType = Schema.Literal(\"task.progress\");\nconst TaskUpdatedType = Schema.Literal(\"task.updated\");\nconst TaskCompletedType = Schema.Literal(\"task.completed\");\nconst HookStartedType = Schema.Literal(\"hook.started\");\nconst HookProgressType = Schema.Literal(\"hook.progress\");\nconst HookCompletedType = Schema.Literal(\"hook.completed\");\nconst ToolProgressType = Schema.Literal(\"tool.progress\");\nconst ToolSummaryType = Schema.Literal(\"tool.summary\");\nconst AuthStatusType = Schema.Literal(\"auth.status\");\nconst AccountUpdatedType = Schema.Literal(\"account.updated\");\nconst AccountRateLimitsUpdatedType = Schema.Literal(\"account.rate-limits.updated\");\nconst McpStatusUpdatedType = Schema.Literal(\"mcp.status.updated\");\nconst McpOauthCompletedType = Schema.Literal(\"mcp.oauth.completed\");\nconst ModelReroutedType = Schema.Literal(\"model.rerouted\");\nconst ConfigWarningType = Schema.Literal(\"config.warning\");\nconst DeprecationNoticeType = Schema.Literal(\"deprecation.notice\");\nconst FilesPersistedType = Schema.Literal(\"files.persisted\");\nconst ToolDeniedType = Schema.Literal(\"tool.denied\");\nconst RuntimeWarningType = Schema.Literal(\"runtime.warning\");\nconst RuntimeErrorType = Schema.Literal(\"runtime.error\");\n\nconst ProviderRuntimeEventBase = Schema.Struct({\n  eventId: EventId,\n  provider: ProviderDriverKind,\n  // Optional during the driver/instance migration. See providerInstance.ts\n  // for the routing-key-vs-driver-id distinction. Once every emitter\n  // populates it (post-slice-4), routing flips to instance-id-only.\n  providerInstanceId: Schema.optional(ProviderInstanceId),\n  threadId: ThreadId,\n  createdAt: IsoDateTime,\n  turnId: Schema.optional(TurnId),\n  itemId: Schema.optional(RuntimeItemId),\n  requestId: Schema.optional(RuntimeRequestId),\n  providerRefs: Schema.optional(ProviderRefs),\n  raw: Schema.optional(RuntimeEventRaw),\n});\nexport type ProviderRuntimeEventBase = typeof ProviderRuntimeEventBase.Type;\n\nconst SessionStartedPayload = Schema.Struct({\n  message: Schema.optional(TrimmedNonEmptyStringSchema),\n  resume: Schema.optional(Schema.Unknown),\n});\nexport type SessionStartedPayload = typeof SessionStartedPayload.Type;\n\nconst SessionConfiguredPayload = Schema.Struct({\n  config: UnknownRecordSchema,\n});\nexport type SessionConfiguredPayload = typeof SessionConfiguredPayload.Type;\n\nconst SessionStateChangedPayload = Schema.Struct({\n  state: RuntimeSessionState,\n  reason: Schema.optional(TrimmedNonEmptyStringSchema),\n  detail: Schema.optional(Schema.Unknown),\n});\nexport type SessionStateChangedPayload = typeof SessionStateChangedPayload.Type;\n\nconst SessionExitedPayload = Schema.Struct({\n  reason: Schema.optional(TrimmedNonEmptyStringSchema),\n  recoverable: Schema.optional(Schema.Boolean),\n  exitKind: Schema.optional(RuntimeSessionExitKind),\n});\nexport type SessionExitedPayload = typeof SessionExitedPayload.Type;\n\nconst ThreadStartedPayload = Schema.Struct({\n  providerThreadId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ThreadStartedPayload = typeof ThreadStartedPayload.Type;\n\nconst ThreadStateChangedPayload = Schema.Struct({\n  state: RuntimeThreadState,\n  detail: Schema.optional(Schema.Unknown),\n});\nexport type ThreadStateChangedPayload = typeof ThreadStateChangedPayload.Type;\n\nconst ThreadMetadataUpdatedPayload = Schema.Struct({\n  name: Schema.optional(TrimmedNonEmptyStringSchema),\n  metadata: Schema.optional(UnknownRecordSchema),\n});\nexport type ThreadMetadataUpdatedPayload = typeof ThreadMetadataUpdatedPayload.Type;\n\nexport const ThreadTokenUsageSnapshot = Schema.Struct({\n  usedTokens: NonNegativeInt,\n  totalProcessedTokens: Schema.optional(NonNegativeInt),\n  maxTokens: Schema.optional(PositiveInt),\n  inputTokens: Schema.optional(NonNegativeInt),\n  cachedInputTokens: Schema.optional(NonNegativeInt),\n  outputTokens: Schema.optional(NonNegativeInt),\n  reasoningOutputTokens: Schema.optional(NonNegativeInt),\n  lastUsedTokens: Schema.optional(NonNegativeInt),\n  lastInputTokens: Schema.optional(NonNegativeInt),\n  lastCachedInputTokens: Schema.optional(NonNegativeInt),\n  lastOutputTokens: Schema.optional(NonNegativeInt),\n  lastReasoningOutputTokens: Schema.optional(NonNegativeInt),\n  toolUses: Schema.optional(NonNegativeInt),\n  durationMs: Schema.optional(NonNegativeInt),\n  compactsAutomatically: Schema.optional(Schema.Boolean),\n});\nexport type ThreadTokenUsageSnapshot = typeof ThreadTokenUsageSnapshot.Type;\n\nconst ThreadTokenUsageUpdatedPayload = Schema.Struct({\n  usage: ThreadTokenUsageSnapshot,\n});\nexport type ThreadTokenUsageUpdatedPayload = typeof ThreadTokenUsageUpdatedPayload.Type;\n\nconst ThreadRealtimeStartedPayload = Schema.Struct({\n  realtimeSessionId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ThreadRealtimeStartedPayload = typeof ThreadRealtimeStartedPayload.Type;\n\nconst ThreadRealtimeItemAddedPayload = Schema.Struct({\n  item: Schema.Unknown,\n});\nexport type ThreadRealtimeItemAddedPayload = typeof ThreadRealtimeItemAddedPayload.Type;\n\nconst ThreadRealtimeAudioDeltaPayload = Schema.Struct({\n  audio: Schema.Unknown,\n});\nexport type ThreadRealtimeAudioDeltaPayload = typeof ThreadRealtimeAudioDeltaPayload.Type;\n\nconst ThreadRealtimeErrorPayload = Schema.Struct({\n  message: TrimmedNonEmptyStringSchema,\n});\nexport type ThreadRealtimeErrorPayload = typeof ThreadRealtimeErrorPayload.Type;\n\nconst ThreadRealtimeClosedPayload = Schema.Struct({\n  reason: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ThreadRealtimeClosedPayload = typeof ThreadRealtimeClosedPayload.Type;\n\nconst TurnStartedPayload = Schema.Struct({\n  model: Schema.optional(TrimmedNonEmptyStringSchema),\n  effort: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type TurnStartedPayload = typeof TurnStartedPayload.Type;\n\nconst TurnCompletedPayload = Schema.Struct({\n  state: RuntimeTurnState,\n  stopReason: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  usage: Schema.optional(Schema.Unknown),\n  modelUsage: Schema.optional(UnknownRecordSchema),\n  totalCostUsd: Schema.optional(Schema.Number),\n  errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type TurnCompletedPayload = typeof TurnCompletedPayload.Type;\n\nconst TurnAbortedPayload = Schema.Struct({\n  reason: TrimmedNonEmptyStringSchema,\n});\nexport type TurnAbortedPayload = typeof TurnAbortedPayload.Type;\n\nconst RuntimePlanStep = Schema.Struct({\n  step: TrimmedNonEmptyStringSchema,\n  status: RuntimePlanStepStatus,\n});\nexport type RuntimePlanStep = typeof RuntimePlanStep.Type;\n\nconst TurnPlanUpdatedPayload = Schema.Struct({\n  explanation: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),\n  plan: Schema.Array(RuntimePlanStep),\n});\nexport type TurnPlanUpdatedPayload = typeof TurnPlanUpdatedPayload.Type;\n\nconst TurnProposedDeltaPayload = Schema.Struct({\n  delta: Schema.String,\n});\nexport type TurnProposedDeltaPayload = typeof TurnProposedDeltaPayload.Type;\n\nconst TurnProposedCompletedPayload = Schema.Struct({\n  planMarkdown: TrimmedNonEmptyStringSchema,\n});\nexport type TurnProposedCompletedPayload = typeof TurnProposedCompletedPayload.Type;\n\nconst TurnDiffUpdatedPayload = Schema.Struct({\n  unifiedDiff: Schema.String,\n});\nexport type TurnDiffUpdatedPayload = typeof TurnDiffUpdatedPayload.Type;\n\nexport const ItemLifecyclePayload = Schema.Struct({\n  itemType: CanonicalItemType,\n  status: Schema.optional(RuntimeItemStatus),\n  title: Schema.optional(TrimmedNonEmptyStringSchema),\n  detail: Schema.optional(TrimmedNonEmptyStringSchema),\n  data: Schema.optional(Schema.Unknown),\n  /**\n   * Owning agent when this item ran inside a subagent (resolved from the\n   * SDK's parent_tool_use_id). Clients re-home attributed items out of the\n   * main timeline and into the owning agent's Agents-surface row.\n   */\n  agentId: Schema.optional(TrimmedNonEmptyStringSchema),\n  parentToolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ItemLifecyclePayload = typeof ItemLifecyclePayload.Type;\n\nconst ContentDeltaPayload = Schema.Struct({\n  streamKind: RuntimeContentStreamKind,\n  delta: Schema.String,\n  contentIndex: Schema.optional(Schema.Int),\n  summaryIndex: Schema.optional(Schema.Int),\n});\nexport type ContentDeltaPayload = typeof ContentDeltaPayload.Type;\n\nconst RequestOpenedPayload = Schema.Struct({\n  requestType: CanonicalRequestType,\n  detail: Schema.optional(TrimmedNonEmptyStringSchema),\n  args: Schema.optional(Schema.Unknown),\n});\nexport type RequestOpenedPayload = typeof RequestOpenedPayload.Type;\n\nconst RequestResolvedPayload = Schema.Struct({\n  requestType: CanonicalRequestType,\n  decision: Schema.optional(TrimmedNonEmptyStringSchema),\n  resolution: Schema.optional(Schema.Unknown),\n});\nexport type RequestResolvedPayload = typeof RequestResolvedPayload.Type;\n\nconst UserInputQuestionOption = Schema.Struct({\n  label: TrimmedNonEmptyStringSchema,\n  description: TrimmedNonEmptyStringSchema,\n});\nexport type UserInputQuestionOption = typeof UserInputQuestionOption.Type;\n\nexport const UserInputQuestion = Schema.Struct({\n  id: TrimmedNonEmptyStringSchema,\n  header: TrimmedNonEmptyStringSchema,\n  question: TrimmedNonEmptyStringSchema,\n  options: Schema.Array(UserInputQuestionOption),\n  multiSelect: Schema.optional(Schema.Boolean).pipe(\n    Schema.withConstructorDefault(Effect.succeed(false)),\n  ),\n});\nexport type UserInputQuestion = typeof UserInputQuestion.Type;\n\nconst UserInputRequestedPayload = Schema.Struct({\n  questions: Schema.Array(UserInputQuestion),\n});\nexport type UserInputRequestedPayload = typeof UserInputRequestedPayload.Type;\n\nconst UserInputResolvedPayload = Schema.Struct({\n  answers: UnknownRecordSchema,\n});\nexport type UserInputResolvedPayload = typeof UserInputResolvedPayload.Type;\n\n/**\n * Typed per-task usage rollup. Field names match the orchestration-v2 subagent\n * usage vocabulary (#4779) so the eventual migration is a rename, not a remap.\n * Claude reports per-activation deltas; Codex reports cumulative totals — the\n * merge strategy is provider-specific and lives in client-runtime.\n */\nexport const RuntimeTaskUsage = Schema.Struct({\n  totalTokens: NonNegativeInt,\n  inputTokens: Schema.optional(NonNegativeInt),\n  cachedInputTokens: Schema.optional(NonNegativeInt),\n  outputTokens: Schema.optional(NonNegativeInt),\n  reasoningOutputTokens: Schema.optional(NonNegativeInt),\n  toolUses: Schema.optional(NonNegativeInt),\n  durationMs: Schema.optional(NonNegativeInt),\n});\nexport type RuntimeTaskUsage = typeof RuntimeTaskUsage.Type;\n\nexport const TaskWorkflowPhase = Schema.Struct({\n  index: NonNegativeInt,\n  title: TrimmedNonEmptyStringSchema,\n});\nexport type TaskWorkflowPhase = typeof TaskWorkflowPhase.Type;\n\nexport const TaskRunHandles = Schema.Struct({\n  runId: Schema.optional(TrimmedNonEmptyStringSchema),\n  scriptPath: Schema.optional(TrimmedNonEmptyStringSchema),\n  transcriptDir: Schema.optional(TrimmedNonEmptyStringSchema),\n  /** Only http/https URLs may be stored here — sanitized at the adapter. */\n  sessionUrl: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type TaskRunHandles = typeof TaskRunHandles.Type;\n\n/**\n * Watch-loop task types: Monitor-tool tasks plus background shells (a shell\n * that outlives its turn is in practice a watch loop). Canonical single copy —\n * the server liveness registry, ingestion's agentKind stamp, and the client\n * fold's legacy fallback all classify with these sets.\n */\nexport const MONITOR_TASK_TYPES: ReadonlySet<string> = new Set([\n  \"monitor\",\n  \"monitor_mcp\",\n  \"local_bash\",\n  \"shell\",\n]);\n/** Task types that are neither agents nor watch loops (plan-mode bookkeeping). */\nexport const INERT_TASK_TYPES: ReadonlySet<string> = new Set([\"plan\", \"dream\"]);\n\n/**\n * Agent-vs-background classification, stamped by ingestion as `agentKind` so\n * persisted rows are self-describing. A deliberate denylist: the SDK's\n * agent-flavored type names drift (subagent, local_agent, local_workflow, …)\n * and an allowlist silently dropped real subagents when \"local_agent\"\n * appeared. A task launched from inside a subagent (agentId set) is\n * agent-internal background work UNLESS it is itself agent-flavored — a\n * nested agent can outlive its parent and stays in the roster.\n */\nexport function classifyTaskAgentKind(input: {\n  readonly taskType?: string | undefined;\n  readonly agentId?: string | undefined;\n}): \"agent\" | \"background\" {\n  const { taskType, agentId } = input;\n  const nonAgentType =\n    taskType !== undefined && (MONITOR_TASK_TYPES.has(taskType) || INERT_TASK_TYPES.has(taskType));\n  if (agentId !== undefined && agentId.trim().length > 0) {\n    return taskType === undefined || nonAgentType ? \"background\" : \"agent\";\n  }\n  return nonAgentType ? \"background\" : \"agent\";\n}\n\n/**\n * Optional agent-identity linkage carried on every task lifecycle payload.\n * Repeated on progress and terminal rows (not just start) so client folds can\n * reconstruct an agent even when its start row aged out of activity retention.\n * All fields optional: old emitters and old rows decode unchanged.\n */\nconst taskAgentLinkageFields = {\n  /** SDK task_type (subagent/shell/monitor/local_workflow/…), repeated on\n   * every row so folds can classify without the start row. */\n  taskType: Schema.optional(TrimmedNonEmptyStringSchema),\n  /**\n   * Server-stamped classification (classifyTaskAgentKind at ingestion).\n   * Clients trust this stamp outright; rows without it (legacy, pre-stamp)\n   * fall back to client-side heuristics.\n   */\n  agentKind: Schema.optional(Schema.Literals([\"agent\", \"background\"])),\n  /**\n   * Owning agent when the task itself was launched from inside a subagent\n   * (e.g. a subagent's background shell). Clients treat such tasks as\n   * agent-internal and keep them out of the parent work log.\n   */\n  agentId: Schema.optional(TrimmedNonEmptyStringSchema),\n  title: Schema.optional(TrimmedNonEmptyStringSchema),\n  role: Schema.optional(TrimmedNonEmptyStringSchema),\n  model: Schema.optional(TrimmedNonEmptyStringSchema),\n  /** Reasoning effort when known (e.g. \"high\"). Open string: provider vocabularies differ. */\n  effort: Schema.optional(TrimmedNonEmptyStringSchema),\n  toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n  parentAgentId: Schema.optional(TrimmedNonEmptyStringSchema),\n  workflowName: Schema.optional(TrimmedNonEmptyStringSchema),\n  agentIndex: Schema.optional(NonNegativeInt),\n  phaseIndex: Schema.optional(NonNegativeInt),\n  phaseTitle: Schema.optional(TrimmedNonEmptyStringSchema),\n  phases: Schema.optional(Schema.Array(TaskWorkflowPhase)),\n  attempt: Schema.optional(NonNegativeInt),\n  runHandles: Schema.optional(TaskRunHandles),\n  outputFile: Schema.optional(TrimmedNonEmptyStringSchema),\n  /** Codex agent hierarchy path, e.g. \"/root/marlow\". */\n  agentPath: Schema.optional(TrimmedNonEmptyStringSchema),\n  /**\n   * Set on provider-synthesized child-agent events (Codex) whose activity\n   * belongs in the Agents surface, never the parent timeline.\n   */\n  timelineBypass: Schema.optional(Schema.Boolean),\n} as const;\n\nexport const TaskAgentLinkage = Schema.Struct(taskAgentLinkageFields);\nexport type TaskAgentLinkage = typeof TaskAgentLinkage.Type;\n\nconst TaskStartedPayload = Schema.Struct({\n  taskId: RuntimeTaskId,\n  description: Schema.optional(TrimmedNonEmptyStringSchema),\n  ...taskAgentLinkageFields,\n});\nexport type TaskStartedPayload = typeof TaskStartedPayload.Type;\n\nexport const RuntimeTaskStatus = Schema.Literals([\n  \"pending\",\n  \"running\",\n  \"waiting\",\n  \"idle\",\n  \"completed\",\n  \"failed\",\n  \"cancelled\",\n  \"interrupted\",\n]);\nexport type RuntimeTaskStatus = typeof RuntimeTaskStatus.Type;\n\nconst TaskProgressPayload = Schema.Struct({\n  taskId: RuntimeTaskId,\n  description: TrimmedNonEmptyStringSchema,\n  summary: Schema.optional(TrimmedNonEmptyStringSchema),\n  usage: Schema.optional(Schema.Unknown),\n  typedUsage: Schema.optional(RuntimeTaskUsage),\n  lastToolName: Schema.optional(TrimmedNonEmptyStringSchema),\n  /** Present on synthesized member/child progress rows that carry state. */\n  status: Schema.optional(RuntimeTaskStatus),\n  error: Schema.optional(TrimmedNonEmptyStringSchema),\n  ...taskAgentLinkageFields,\n});\nexport type TaskProgressPayload = typeof TaskProgressPayload.Type;\n\n/**\n * Non-terminal status patch (from the Claude SDK's task_updated, which main\n * previously dropped). killed→cancelled and paused→idle are mapped at the\n * adapter so the wire only carries the shared vocabulary.\n */\nconst TaskUpdatedPayload = Schema.Struct({\n  taskId: RuntimeTaskId,\n  status: Schema.optional(RuntimeTaskStatus),\n  description: Schema.optional(TrimmedNonEmptyStringSchema),\n  error: Schema.optional(TrimmedNonEmptyStringSchema),\n  endedAt: Schema.optional(IsoDateTime),\n  isBackgrounded: Schema.optional(Schema.Boolean),\n  ...taskAgentLinkageFields,\n});\nexport type TaskUpdatedPayload = typeof TaskUpdatedPayload.Type;\n\nconst TaskCompletedPayload = Schema.Struct({\n  taskId: RuntimeTaskId,\n  status: Schema.Literals([\"completed\", \"failed\", \"stopped\"]),\n  summary: Schema.optional(TrimmedNonEmptyStringSchema),\n  usage: Schema.optional(Schema.Unknown),\n  typedUsage: Schema.optional(RuntimeTaskUsage),\n  ...taskAgentLinkageFields,\n});\nexport type TaskCompletedPayload = typeof TaskCompletedPayload.Type;\n\nconst HookStartedPayload = Schema.Struct({\n  hookId: TrimmedNonEmptyStringSchema,\n  hookName: TrimmedNonEmptyStringSchema,\n  hookEvent: TrimmedNonEmptyStringSchema,\n});\nexport type HookStartedPayload = typeof HookStartedPayload.Type;\n\nconst HookProgressPayload = Schema.Struct({\n  hookId: TrimmedNonEmptyStringSchema,\n  output: Schema.optional(Schema.String),\n  stdout: Schema.optional(Schema.String),\n  stderr: Schema.optional(Schema.String),\n});\nexport type HookProgressPayload = typeof HookProgressPayload.Type;\n\nconst HookCompletedPayload = Schema.Struct({\n  hookId: TrimmedNonEmptyStringSchema,\n  outcome: Schema.Literals([\"success\", \"error\", \"cancelled\"]),\n  output: Schema.optional(Schema.String),\n  stdout: Schema.optional(Schema.String),\n  stderr: Schema.optional(Schema.String),\n  exitCode: Schema.optional(Schema.Int),\n});\nexport type HookCompletedPayload = typeof HookCompletedPayload.Type;\n\nconst ToolProgressPayload = Schema.Struct({\n  toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n  toolName: Schema.optional(TrimmedNonEmptyStringSchema),\n  summary: Schema.optional(TrimmedNonEmptyStringSchema),\n  elapsedSeconds: Schema.optional(Schema.Number),\n  /** Owning task/agent when the tool ran inside a subagent. */\n  taskId: Schema.optional(RuntimeTaskId),\n  parentToolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ToolProgressPayload = typeof ToolProgressPayload.Type;\n\nconst ToolSummaryPayload = Schema.Struct({\n  summary: TrimmedNonEmptyStringSchema,\n  precedingToolUseIds: Schema.optional(Schema.Array(TrimmedNonEmptyStringSchema)),\n});\nexport type ToolSummaryPayload = typeof ToolSummaryPayload.Type;\n\nconst AuthStatusPayload = Schema.Struct({\n  isAuthenticating: Schema.optional(Schema.Boolean),\n  output: Schema.optional(Schema.Array(Schema.String)),\n  error: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type AuthStatusPayload = typeof AuthStatusPayload.Type;\n\nconst AccountUpdatedPayload = Schema.Struct({\n  account: Schema.Unknown,\n});\nexport type AccountUpdatedPayload = typeof AccountUpdatedPayload.Type;\n\nconst AccountRateLimitsUpdatedPayload = Schema.Struct({\n  rateLimits: Schema.Unknown,\n});\nexport type AccountRateLimitsUpdatedPayload = typeof AccountRateLimitsUpdatedPayload.Type;\n\nconst McpStatusUpdatedPayload = Schema.Struct({\n  status: Schema.Unknown,\n});\nexport type McpStatusUpdatedPayload = typeof McpStatusUpdatedPayload.Type;\n\nconst McpOauthCompletedPayload = Schema.Struct({\n  success: Schema.Boolean,\n  name: Schema.optional(TrimmedNonEmptyStringSchema),\n  error: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type McpOauthCompletedPayload = typeof McpOauthCompletedPayload.Type;\n\nconst ModelReroutedPayload = Schema.Struct({\n  fromModel: TrimmedNonEmptyStringSchema,\n  toModel: TrimmedNonEmptyStringSchema,\n  reason: TrimmedNonEmptyStringSchema,\n});\nexport type ModelReroutedPayload = typeof ModelReroutedPayload.Type;\n\nconst ConfigWarningPayload = Schema.Struct({\n  summary: TrimmedNonEmptyStringSchema,\n  details: Schema.optional(TrimmedNonEmptyStringSchema),\n  path: Schema.optional(TrimmedNonEmptyStringSchema),\n  range: Schema.optional(Schema.Unknown),\n});\nexport type ConfigWarningPayload = typeof ConfigWarningPayload.Type;\n\nconst DeprecationNoticePayload = Schema.Struct({\n  summary: TrimmedNonEmptyStringSchema,\n  details: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type DeprecationNoticePayload = typeof DeprecationNoticePayload.Type;\n\nconst FilesPersistedPayload = Schema.Struct({\n  files: Schema.Array(\n    Schema.Struct({\n      filename: TrimmedNonEmptyStringSchema,\n      fileId: TrimmedNonEmptyStringSchema,\n    }),\n  ),\n  failed: Schema.optional(\n    Schema.Array(\n      Schema.Struct({\n        filename: TrimmedNonEmptyStringSchema,\n        error: TrimmedNonEmptyStringSchema,\n      }),\n    ),\n  ),\n});\nexport type FilesPersistedPayload = typeof FilesPersistedPayload.Type;\n\nconst ToolDeniedPayload = Schema.Struct({\n  toolName: TrimmedNonEmptyStringSchema,\n  toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),\n  reason: Schema.optional(TrimmedNonEmptyStringSchema),\n  agentId: Schema.optional(TrimmedNonEmptyStringSchema),\n});\nexport type ToolDeniedPayload = typeof ToolDeniedPayload.Type;\n\nconst RuntimeWarningPayload = Schema.Struct({\n  message: TrimmedNonEmptyStringSchema,\n  detail: Schema.optional(Schema.Unknown),\n});\nexport type RuntimeWarningPayload = typeof RuntimeWarningPayload.Type;\n\nconst RuntimeErrorPayload = Schema.Struct({\n  message: TrimmedNonEmptyStringSchema,\n  class: Schema.optional(RuntimeErrorClass),\n  detail: Schema.optional(Schema.Unknown),\n});\nexport type RuntimeErrorPayload = typeof RuntimeErrorPayload.Type;\n\nconst ProviderRuntimeSessionStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: SessionStartedType,\n  payload: SessionStartedPayload,\n});\nexport type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type;\n\nconst ProviderRuntimeSessionConfiguredEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: SessionConfiguredType,\n  payload: SessionConfiguredPayload,\n});\nexport type ProviderRuntimeSessionConfiguredEvent =\n  typeof ProviderRuntimeSessionConfiguredEvent.Type;\n\nconst ProviderRuntimeSessionStateChangedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: SessionStateChangedType,\n  payload: SessionStateChangedPayload,\n});\nexport type ProviderRuntimeSessionStateChangedEvent =\n  typeof ProviderRuntimeSessionStateChangedEvent.Type;\n\nconst ProviderRuntimeSessionExitedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: SessionExitedType,\n  payload: SessionExitedPayload,\n});\nexport type ProviderRuntimeSessionExitedEvent = typeof ProviderRuntimeSessionExitedEvent.Type;\n\nconst ProviderRuntimeThreadStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadStartedType,\n  payload: ThreadStartedPayload,\n});\nexport type ProviderRuntimeThreadStartedEvent = typeof ProviderRuntimeThreadStartedEvent.Type;\n\nconst ProviderRuntimeThreadStateChangedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadStateChangedType,\n  payload: ThreadStateChangedPayload,\n});\nexport type ProviderRuntimeThreadStateChangedEvent =\n  typeof ProviderRuntimeThreadStateChangedEvent.Type;\n\nconst ProviderRuntimeThreadMetadataUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadMetadataUpdatedType,\n  payload: ThreadMetadataUpdatedPayload,\n});\nexport type ProviderRuntimeThreadMetadataUpdatedEvent =\n  typeof ProviderRuntimeThreadMetadataUpdatedEvent.Type;\n\nconst ProviderRuntimeThreadTokenUsageUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadTokenUsageUpdatedType,\n  payload: ThreadTokenUsageUpdatedPayload,\n});\nexport type ProviderRuntimeThreadTokenUsageUpdatedEvent =\n  typeof ProviderRuntimeThreadTokenUsageUpdatedEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeStartedType,\n  payload: ThreadRealtimeStartedPayload,\n});\nexport type ProviderRuntimeThreadRealtimeStartedEvent =\n  typeof ProviderRuntimeThreadRealtimeStartedEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeItemAddedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeItemAddedType,\n  payload: ThreadRealtimeItemAddedPayload,\n});\nexport type ProviderRuntimeThreadRealtimeItemAddedEvent =\n  typeof ProviderRuntimeThreadRealtimeItemAddedEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeAudioDeltaEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeAudioDeltaType,\n  payload: ThreadRealtimeAudioDeltaPayload,\n});\nexport type ProviderRuntimeThreadRealtimeAudioDeltaEvent =\n  typeof ProviderRuntimeThreadRealtimeAudioDeltaEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeErrorEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeErrorType,\n  payload: ThreadRealtimeErrorPayload,\n});\nexport type ProviderRuntimeThreadRealtimeErrorEvent =\n  typeof ProviderRuntimeThreadRealtimeErrorEvent.Type;\n\nconst ProviderRuntimeThreadRealtimeClosedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ThreadRealtimeClosedType,\n  payload: ThreadRealtimeClosedPayload,\n});\nexport type ProviderRuntimeThreadRealtimeClosedEvent =\n  typeof ProviderRuntimeThreadRealtimeClosedEvent.Type;\n\nconst ProviderRuntimeTurnStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnStartedType,\n  payload: TurnStartedPayload,\n});\nexport type ProviderRuntimeTurnStartedEvent = typeof ProviderRuntimeTurnStartedEvent.Type;\n\nconst ProviderRuntimeTurnCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnCompletedType,\n  payload: TurnCompletedPayload,\n});\nexport type ProviderRuntimeTurnCompletedEvent = typeof ProviderRuntimeTurnCompletedEvent.Type;\n\nconst ProviderRuntimeTurnAbortedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnAbortedType,\n  payload: TurnAbortedPayload,\n});\nexport type ProviderRuntimeTurnAbortedEvent = typeof ProviderRuntimeTurnAbortedEvent.Type;\n\nconst ProviderRuntimeTurnPlanUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnPlanUpdatedType,\n  payload: TurnPlanUpdatedPayload,\n});\nexport type ProviderRuntimeTurnPlanUpdatedEvent = typeof ProviderRuntimeTurnPlanUpdatedEvent.Type;\n\nconst ProviderRuntimeTurnProposedDeltaEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnProposedDeltaType,\n  payload: TurnProposedDeltaPayload,\n});\nexport type ProviderRuntimeTurnProposedDeltaEvent =\n  typeof ProviderRuntimeTurnProposedDeltaEvent.Type;\n\nconst ProviderRuntimeTurnProposedCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnProposedCompletedType,\n  payload: TurnProposedCompletedPayload,\n});\nexport type ProviderRuntimeTurnProposedCompletedEvent =\n  typeof ProviderRuntimeTurnProposedCompletedEvent.Type;\n\nconst ProviderRuntimeTurnDiffUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TurnDiffUpdatedType,\n  payload: TurnDiffUpdatedPayload,\n});\nexport type ProviderRuntimeTurnDiffUpdatedEvent = typeof ProviderRuntimeTurnDiffUpdatedEvent.Type;\n\nconst ProviderRuntimeItemStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ItemStartedType,\n  payload: ItemLifecyclePayload,\n});\nexport type ProviderRuntimeItemStartedEvent = typeof ProviderRuntimeItemStartedEvent.Type;\n\nconst ProviderRuntimeItemUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ItemUpdatedType,\n  payload: ItemLifecyclePayload,\n});\nexport type ProviderRuntimeItemUpdatedEvent = typeof ProviderRuntimeItemUpdatedEvent.Type;\n\nconst ProviderRuntimeItemCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ItemCompletedType,\n  payload: ItemLifecyclePayload,\n});\nexport type ProviderRuntimeItemCompletedEvent = typeof ProviderRuntimeItemCompletedEvent.Type;\n\nconst ProviderRuntimeContentDeltaEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ContentDeltaType,\n  payload: ContentDeltaPayload,\n});\nexport type ProviderRuntimeContentDeltaEvent = typeof ProviderRuntimeContentDeltaEvent.Type;\n\nconst ProviderRuntimeRequestOpenedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: RequestOpenedType,\n  payload: RequestOpenedPayload,\n});\nexport type ProviderRuntimeRequestOpenedEvent = typeof ProviderRuntimeRequestOpenedEvent.Type;\n\nconst ProviderRuntimeRequestResolvedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: RequestResolvedType,\n  payload: RequestResolvedPayload,\n});\nexport type ProviderRuntimeRequestResolvedEvent = typeof ProviderRuntimeRequestResolvedEvent.Type;\n\nconst ProviderRuntimeUserInputRequestedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: UserInputRequestedType,\n  payload: UserInputRequestedPayload,\n});\nexport type ProviderRuntimeUserInputRequestedEvent =\n  typeof ProviderRuntimeUserInputRequestedEvent.Type;\n\nconst ProviderRuntimeUserInputResolvedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: UserInputResolvedType,\n  payload: UserInputResolvedPayload,\n});\nexport type ProviderRuntimeUserInputResolvedEvent =\n  typeof ProviderRuntimeUserInputResolvedEvent.Type;\n\nconst ProviderRuntimeTaskStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TaskStartedType,\n  payload: TaskStartedPayload,\n});\nexport type ProviderRuntimeTaskStartedEvent = typeof ProviderRuntimeTaskStartedEvent.Type;\n\nconst ProviderRuntimeTaskProgressEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TaskProgressType,\n  payload: TaskProgressPayload,\n});\nexport type ProviderRuntimeTaskProgressEvent = typeof ProviderRuntimeTaskProgressEvent.Type;\n\nconst ProviderRuntimeTaskUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TaskUpdatedType,\n  payload: TaskUpdatedPayload,\n});\nexport type ProviderRuntimeTaskUpdatedEvent = typeof ProviderRuntimeTaskUpdatedEvent.Type;\n\nconst ProviderRuntimeTaskCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: TaskCompletedType,\n  payload: TaskCompletedPayload,\n});\nexport type ProviderRuntimeTaskCompletedEvent = typeof ProviderRuntimeTaskCompletedEvent.Type;\n\nconst ProviderRuntimeHookStartedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: HookStartedType,\n  payload: HookStartedPayload,\n});\nexport type ProviderRuntimeHookStartedEvent = typeof ProviderRuntimeHookStartedEvent.Type;\n\nconst ProviderRuntimeHookProgressEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: HookProgressType,\n  payload: HookProgressPayload,\n});\nexport type ProviderRuntimeHookProgressEvent = typeof ProviderRuntimeHookProgressEvent.Type;\n\nconst ProviderRuntimeHookCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: HookCompletedType,\n  payload: HookCompletedPayload,\n});\nexport type ProviderRuntimeHookCompletedEvent = typeof ProviderRuntimeHookCompletedEvent.Type;\n\nconst ProviderRuntimeToolProgressEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ToolProgressType,\n  payload: ToolProgressPayload,\n});\nexport type ProviderRuntimeToolProgressEvent = typeof ProviderRuntimeToolProgressEvent.Type;\n\nconst ProviderRuntimeToolSummaryEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ToolSummaryType,\n  payload: ToolSummaryPayload,\n});\nexport type ProviderRuntimeToolSummaryEvent = typeof ProviderRuntimeToolSummaryEvent.Type;\n\nconst ProviderRuntimeAuthStatusEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: AuthStatusType,\n  payload: AuthStatusPayload,\n});\nexport type ProviderRuntimeAuthStatusEvent = typeof ProviderRuntimeAuthStatusEvent.Type;\n\nconst ProviderRuntimeAccountUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: AccountUpdatedType,\n  payload: AccountUpdatedPayload,\n});\nexport type ProviderRuntimeAccountUpdatedEvent = typeof ProviderRuntimeAccountUpdatedEvent.Type;\n\nconst ProviderRuntimeAccountRateLimitsUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: AccountRateLimitsUpdatedType,\n  payload: AccountRateLimitsUpdatedPayload,\n});\nexport type ProviderRuntimeAccountRateLimitsUpdatedEvent =\n  typeof ProviderRuntimeAccountRateLimitsUpdatedEvent.Type;\n\nconst ProviderRuntimeMcpStatusUpdatedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: McpStatusUpdatedType,\n  payload: McpStatusUpdatedPayload,\n});\nexport type ProviderRuntimeMcpStatusUpdatedEvent = typeof ProviderRuntimeMcpStatusUpdatedEvent.Type;\n\nconst ProviderRuntimeMcpOauthCompletedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: McpOauthCompletedType,\n  payload: McpOauthCompletedPayload,\n});\nexport type ProviderRuntimeMcpOauthCompletedEvent =\n  typeof ProviderRuntimeMcpOauthCompletedEvent.Type;\n\nconst ProviderRuntimeModelReroutedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ModelReroutedType,\n  payload: ModelReroutedPayload,\n});\nexport type ProviderRuntimeModelReroutedEvent = typeof ProviderRuntimeModelReroutedEvent.Type;\n\nconst ProviderRuntimeConfigWarningEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ConfigWarningType,\n  payload: ConfigWarningPayload,\n});\nexport type ProviderRuntimeConfigWarningEvent = typeof ProviderRuntimeConfigWarningEvent.Type;\n\nconst ProviderRuntimeDeprecationNoticeEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: DeprecationNoticeType,\n  payload: DeprecationNoticePayload,\n});\nexport type ProviderRuntimeDeprecationNoticeEvent =\n  typeof ProviderRuntimeDeprecationNoticeEvent.Type;\n\nconst ProviderRuntimeFilesPersistedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: FilesPersistedType,\n  payload: FilesPersistedPayload,\n});\nexport type ProviderRuntimeFilesPersistedEvent = typeof ProviderRuntimeFilesPersistedEvent.Type;\n\nconst ProviderRuntimeToolDeniedEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: ToolDeniedType,\n  payload: ToolDeniedPayload,\n});\nexport type ProviderRuntimeToolDeniedEvent = typeof ProviderRuntimeToolDeniedEvent.Type;\n\nconst ProviderRuntimeWarningEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: RuntimeWarningType,\n  payload: RuntimeWarningPayload,\n});\nexport type ProviderRuntimeWarningEvent = typeof ProviderRuntimeWarningEvent.Type;\n\nconst ProviderRuntimeErrorEvent = Schema.Struct({\n  ...ProviderRuntimeEventBase.fields,\n  type: RuntimeErrorType,\n  payload: RuntimeErrorPayload,\n});\nexport type ProviderRuntimeErrorEvent = typeof ProviderRuntimeErrorEvent.Type;\n\nexport const ProviderRuntimeEventV2 = Schema.Union([\n  ProviderRuntimeSessionStartedEvent,\n  ProviderRuntimeSessionConfiguredEvent,\n  ProviderRuntimeSessionStateChangedEvent,\n  ProviderRuntimeSessionExitedEvent,\n  ProviderRuntimeThreadStartedEvent,\n  ProviderRuntimeThreadStateChangedEvent,\n  ProviderRuntimeThreadMetadataUpdatedEvent,\n  ProviderRuntimeThreadTokenUsageUpdatedEvent,\n  ProviderRuntimeThreadRealtimeStartedEvent,\n  ProviderRuntimeThreadRealtimeItemAddedEvent,\n  ProviderRuntimeThreadRealtimeAudioDeltaEvent,\n  ProviderRuntimeThreadRealtimeErrorEvent,\n  ProviderRuntimeThreadRealtimeClosedEvent,\n  ProviderRuntimeTurnStartedEvent,\n  ProviderRuntimeTurnCompletedEvent,\n  ProviderRuntimeTurnAbortedEvent,\n  ProviderRuntimeTurnPlanUpdatedEvent,\n  ProviderRuntimeTurnProposedDeltaEvent,\n  ProviderRuntimeTurnProposedCompletedEvent,\n  ProviderRuntimeTurnDiffUpdatedEvent,\n  ProviderRuntimeItemStartedEvent,\n  ProviderRuntimeItemUpdatedEvent,\n  ProviderRuntimeItemCompletedEvent,\n  ProviderRuntimeContentDeltaEvent,\n  ProviderRuntimeRequestOpenedEvent,\n  ProviderRuntimeRequestResolvedEvent,\n  ProviderRuntimeUserInputRequestedEvent,\n  ProviderRuntimeUserInputResolvedEvent,\n  ProviderRuntimeTaskStartedEvent,\n  ProviderRuntimeTaskProgressEvent,\n  ProviderRuntimeTaskUpdatedEvent,\n  ProviderRuntimeTaskCompletedEvent,\n  ProviderRuntimeHookStartedEvent,\n  ProviderRuntimeHookProgressEvent,\n  ProviderRuntimeHookCompletedEvent,\n  ProviderRuntimeToolProgressEvent,\n  ProviderRuntimeToolSummaryEvent,\n  ProviderRuntimeAuthStatusEvent,\n  ProviderRuntimeAccountUpdatedEvent,\n  ProviderRuntimeAccountRateLimitsUpdatedEvent,\n  ProviderRuntimeMcpStatusUpdatedEvent,\n  ProviderRuntimeMcpOauthCompletedEvent,\n  ProviderRuntimeModelReroutedEvent,\n  ProviderRuntimeConfigWarningEvent,\n  ProviderRuntimeDeprecationNoticeEvent,\n  ProviderRuntimeFilesPersistedEvent,\n  ProviderRuntimeToolDeniedEvent,\n  ProviderRuntimeWarningEvent,\n  ProviderRuntimeErrorEvent,\n]);\nexport type ProviderRuntimeEventV2 = typeof ProviderRuntimeEventV2.Type;\n\nexport const ProviderRuntimeEvent = ProviderRuntimeEventV2;\nexport type ProviderRuntimeEvent = ProviderRuntimeEventV2;\n\n// Compatibility aliases for call sites still importing legacy names.\nconst ProviderRuntimeMessageDeltaEvent = ProviderRuntimeContentDeltaEvent;\nexport type ProviderRuntimeMessageDeltaEvent = ProviderRuntimeContentDeltaEvent;\nconst ProviderRuntimeMessageCompletedEvent = ProviderRuntimeItemCompletedEvent;\nexport type ProviderRuntimeMessageCompletedEvent = ProviderRuntimeItemCompletedEvent;\nconst ProviderRuntimeToolStartedEvent = ProviderRuntimeItemStartedEvent;\nexport type ProviderRuntimeToolStartedEvent = ProviderRuntimeItemStartedEvent;\nconst ProviderRuntimeToolCompletedEvent = ProviderRuntimeItemCompletedEvent;\nexport type ProviderRuntimeToolCompletedEvent = ProviderRuntimeItemCompletedEvent;\nconst ProviderRuntimeApprovalRequestedEvent = ProviderRuntimeRequestOpenedEvent;\nexport type ProviderRuntimeApprovalRequestedEvent = ProviderRuntimeRequestOpenedEvent;\nconst ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent;\nexport type ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent;\n\n// Legacy helper aliases retained for adapters/tests.\nconst ProviderRuntimeToolKind = Schema.Literals([\"command\", \"file-read\", \"file-change\", \"other\"]);\nexport type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;\n\nexport const ProviderRuntimeTurnStatus = RuntimeTurnState;\nexport type ProviderRuntimeTurnStatus = RuntimeTurnState;\n","import * as Schema from \"effect/Schema\";\nimport { ForwardCompatibleArray, TrimmedString } from \"./baseSchemas.ts\";\n\nexport const MAX_KEYBINDING_VALUE_LENGTH = 64;\nexport const MAX_KEYBINDING_WHEN_LENGTH = 256;\nexport const MAX_WHEN_EXPRESSION_DEPTH = 64;\nexport const MAX_SCRIPT_ID_LENGTH = 24;\nexport const MAX_KEYBINDINGS_COUNT = 256;\n\nexport const THREAD_JUMP_KEYBINDING_COMMANDS = [\n  \"thread.jump.1\",\n  \"thread.jump.2\",\n  \"thread.jump.3\",\n  \"thread.jump.4\",\n  \"thread.jump.5\",\n  \"thread.jump.6\",\n  \"thread.jump.7\",\n  \"thread.jump.8\",\n  \"thread.jump.9\",\n] as const;\nexport type ThreadJumpKeybindingCommand = (typeof THREAD_JUMP_KEYBINDING_COMMANDS)[number];\n\nexport const MODEL_PICKER_JUMP_KEYBINDING_COMMANDS = [\n  \"modelPicker.jump.1\",\n  \"modelPicker.jump.2\",\n  \"modelPicker.jump.3\",\n  \"modelPicker.jump.4\",\n  \"modelPicker.jump.5\",\n  \"modelPicker.jump.6\",\n  \"modelPicker.jump.7\",\n  \"modelPicker.jump.8\",\n  \"modelPicker.jump.9\",\n] as const;\nexport type ModelPickerJumpKeybindingCommand =\n  (typeof MODEL_PICKER_JUMP_KEYBINDING_COMMANDS)[number];\n\nexport const THREAD_KEYBINDING_COMMANDS = [\n  \"thread.previous\",\n  \"thread.next\",\n  ...THREAD_JUMP_KEYBINDING_COMMANDS,\n] as const;\nexport type ThreadKeybindingCommand = (typeof THREAD_KEYBINDING_COMMANDS)[number];\n\nexport const MODEL_PICKER_KEYBINDING_COMMANDS = [\n  \"modelPicker.toggle\",\n  ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,\n] as const;\nexport type ModelPickerKeybindingCommand = (typeof MODEL_PICKER_KEYBINDING_COMMANDS)[number];\n\nconst STATIC_KEYBINDING_COMMANDS = [\n  \"sidebar.toggle\",\n  \"terminal.toggle\",\n  \"terminal.split\",\n  \"terminal.splitVertical\",\n  \"terminal.new\",\n  \"terminal.close\",\n  \"rightPanel.toggle\",\n  \"diff.toggle\",\n  \"preview.toggle\",\n  \"preview.refresh\",\n  \"preview.focusUrl\",\n  \"preview.zoomIn\",\n  \"preview.zoomOut\",\n  \"preview.resetZoom\",\n  \"commandPalette.toggle\",\n  \"filePicker.toggle\",\n  \"projectSearch.toggle\",\n  \"themeEditor.toggle\",\n  \"composer.stash\",\n  \"chat.new\",\n  \"chat.newLocal\",\n  \"editor.openFavorite\",\n  ...MODEL_PICKER_KEYBINDING_COMMANDS,\n  ...THREAD_KEYBINDING_COMMANDS,\n] as const;\n\nexport const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([\n  Schema.Literal(\"script.\"),\n  Schema.NonEmptyString.check(\n    Schema.isMaxLength(MAX_SCRIPT_ID_LENGTH),\n    Schema.isPattern(/^[a-z0-9][a-z0-9-]*$/),\n  ),\n  Schema.Literal(\".run\"),\n]);\n\nexport const KeybindingCommand = Schema.Union([\n  Schema.Literals(STATIC_KEYBINDING_COMMANDS),\n  SCRIPT_RUN_COMMAND_PATTERN,\n]);\nexport type KeybindingCommand = typeof KeybindingCommand.Type;\n\nexport const KeybindingValue = TrimmedString.check(\n  Schema.isMinLength(1),\n  Schema.isMaxLength(MAX_KEYBINDING_VALUE_LENGTH),\n);\n\nexport const KeybindingWhen = TrimmedString.check(\n  Schema.isMinLength(1),\n  Schema.isMaxLength(MAX_KEYBINDING_WHEN_LENGTH),\n);\nexport const KeybindingRule = Schema.Struct({\n  key: KeybindingValue,\n  command: KeybindingCommand,\n  when: Schema.optional(KeybindingWhen),\n});\nexport type KeybindingRule = typeof KeybindingRule.Type;\n\nexport const KeybindingsConfig = Schema.Array(KeybindingRule).check(\n  Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),\n);\nexport type KeybindingsConfig = typeof KeybindingsConfig.Type;\n\nexport const KeybindingShortcut = Schema.Struct({\n  key: KeybindingValue,\n  metaKey: Schema.Boolean,\n  ctrlKey: Schema.Boolean,\n  shiftKey: Schema.Boolean,\n  altKey: Schema.Boolean,\n  modKey: Schema.Boolean,\n});\nexport type KeybindingShortcut = typeof KeybindingShortcut.Type;\n\nconst KeybindingWhenNodeRef = Schema.suspend(\n  (): Schema.Codec<KeybindingWhenNode> => KeybindingWhenNode,\n);\nexport const KeybindingWhenNode = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"identifier\"),\n    name: Schema.NonEmptyString,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"not\"),\n    node: KeybindingWhenNodeRef,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"and\"),\n    left: KeybindingWhenNodeRef,\n    right: KeybindingWhenNodeRef,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"or\"),\n    left: KeybindingWhenNodeRef,\n    right: KeybindingWhenNodeRef,\n  }),\n]);\nexport type KeybindingWhenNode =\n  | { type: \"identifier\"; name: string }\n  | { type: \"not\"; node: KeybindingWhenNode }\n  | { type: \"and\"; left: KeybindingWhenNode; right: KeybindingWhenNode }\n  | { type: \"or\"; left: KeybindingWhenNode; right: KeybindingWhenNode };\n\nexport const ResolvedKeybindingRule = Schema.Struct({\n  command: KeybindingCommand,\n  shortcut: KeybindingShortcut,\n  whenAst: Schema.optional(KeybindingWhenNode),\n}).annotate({ parseOptions: { onExcessProperty: \"ignore\" } });\nexport type ResolvedKeybindingRule = typeof ResolvedKeybindingRule.Type;\n\n/**\n * The command set grows over time, so a client may receive rules it cannot\n * represent (a command or `when` node added after that client shipped).\n * Decoding drops those rules instead of failing the whole payload —\n * rejecting the config would take down the connection over a shortcut the\n * client couldn't dispatch anyway.\n */\nexport const ResolvedKeybindingsConfig = ForwardCompatibleArray(ResolvedKeybindingRule).check(\n  Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),\n);\nexport type ResolvedKeybindingsConfig = typeof ResolvedKeybindingsConfig.Type;\n\nexport class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(\n  \"KeybindingsConfigParseError\",\n  {\n    configPath: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`;\n  }\n}\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const EditorLaunchStyle = Schema.Literals([\"direct-path\", \"goto\", \"line-column\"]);\nexport type EditorLaunchStyle = typeof EditorLaunchStyle.Type;\n\ntype EditorDefinition = {\n  readonly id: string;\n  readonly label: string;\n  readonly commands: readonly [string, ...string[]] | null;\n  readonly baseArgs?: readonly string[];\n  readonly launchStyle: EditorLaunchStyle;\n};\n\nexport const EDITORS = [\n  { id: \"cursor\", label: \"Cursor\", commands: [\"cursor\"], launchStyle: \"goto\" },\n  { id: \"trae\", label: \"Trae\", commands: [\"trae\"], launchStyle: \"goto\" },\n  { id: \"kiro\", label: \"Kiro\", commands: [\"kiro\"], baseArgs: [\"ide\"], launchStyle: \"goto\" },\n  { id: \"vscode\", label: \"VS Code\", commands: [\"code\"], launchStyle: \"goto\" },\n  {\n    id: \"vscode-insiders\",\n    label: \"VS Code Insiders\",\n    commands: [\"code-insiders\"],\n    launchStyle: \"goto\",\n  },\n  { id: \"vscodium\", label: \"VSCodium\", commands: [\"codium\"], launchStyle: \"goto\" },\n  { id: \"zed\", label: \"Zed\", commands: [\"zed\", \"zeditor\"], launchStyle: \"direct-path\" },\n  { id: \"antigravity\", label: \"Antigravity\", commands: [\"agy\"], launchStyle: \"goto\" },\n  { id: \"idea\", label: \"IntelliJ IDEA\", commands: [\"idea\"], launchStyle: \"line-column\" },\n  { id: \"aqua\", label: \"Aqua\", commands: [\"aqua\"], launchStyle: \"line-column\" },\n  { id: \"clion\", label: \"CLion\", commands: [\"clion\"], launchStyle: \"line-column\" },\n  { id: \"datagrip\", label: \"DataGrip\", commands: [\"datagrip\"], launchStyle: \"line-column\" },\n  { id: \"dataspell\", label: \"DataSpell\", commands: [\"dataspell\"], launchStyle: \"line-column\" },\n  { id: \"goland\", label: \"GoLand\", commands: [\"goland\"], launchStyle: \"line-column\" },\n  { id: \"phpstorm\", label: \"PhpStorm\", commands: [\"phpstorm\"], launchStyle: \"line-column\" },\n  { id: \"pycharm\", label: \"PyCharm\", commands: [\"pycharm\"], launchStyle: \"line-column\" },\n  { id: \"rider\", label: \"Rider\", commands: [\"rider\"], launchStyle: \"line-column\" },\n  { id: \"rubymine\", label: \"RubyMine\", commands: [\"rubymine\"], launchStyle: \"line-column\" },\n  { id: \"rustrover\", label: \"RustRover\", commands: [\"rustrover\"], launchStyle: \"line-column\" },\n  { id: \"webstorm\", label: \"WebStorm\", commands: [\"webstorm\"], launchStyle: \"line-column\" },\n  { id: \"file-manager\", label: \"File Manager\", commands: null, launchStyle: \"direct-path\" },\n] as const satisfies ReadonlyArray<EditorDefinition>;\n\nexport const EditorId = Schema.Literals(EDITORS.map((e) => e.id));\nexport type EditorId = typeof EditorId.Type;\n\nexport const LaunchEditorInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  editor: EditorId,\n});\nexport type LaunchEditorInput = typeof LaunchEditorInput.Type;\n\nexport class ExternalLauncherUnknownEditorError extends Schema.TaggedErrorClass<ExternalLauncherUnknownEditorError>()(\n  \"ExternalLauncherUnknownEditorError\",\n  {\n    editor: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Unknown editor: ${this.editor}`;\n  }\n}\n\nexport class ExternalLauncherUnsupportedEditorError extends Schema.TaggedErrorClass<ExternalLauncherUnsupportedEditorError>()(\n  \"ExternalLauncherUnsupportedEditorError\",\n  {\n    editor: EditorId,\n  },\n) {\n  override get message(): string {\n    return `Unsupported editor: ${this.editor}`;\n  }\n}\n\nexport class ExternalLauncherCommandNotFoundError extends Schema.TaggedErrorClass<ExternalLauncherCommandNotFoundError>()(\n  \"ExternalLauncherCommandNotFoundError\",\n  {\n    editor: EditorId,\n    command: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Editor command not found: ${this.command}`;\n  }\n}\n\nconst ExternalLauncherSpawnFields = {\n  command: Schema.String,\n  args: Schema.Array(Schema.String),\n  cause: Schema.Defect(),\n};\n\nexport class ExternalLauncherBrowserSpawnError extends Schema.TaggedErrorClass<ExternalLauncherBrowserSpawnError>()(\n  \"ExternalLauncherBrowserSpawnError\",\n  {\n    ...ExternalLauncherSpawnFields,\n    target: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Failed to launch browser target '${this.target}' with '${[this.command, ...this.args].join(\" \")}'`;\n  }\n}\n\nexport class ExternalLauncherEditorSpawnError extends Schema.TaggedErrorClass<ExternalLauncherEditorSpawnError>()(\n  \"ExternalLauncherEditorSpawnError\",\n  {\n    ...ExternalLauncherSpawnFields,\n    editor: EditorId,\n    target: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Failed to launch '${this.target}' in ${this.editor} with '${[this.command, ...this.args].join(\" \")}'`;\n  }\n}\n\nexport const ExternalLauncherError = Schema.Union([\n  ExternalLauncherUnknownEditorError,\n  ExternalLauncherUnsupportedEditorError,\n  ExternalLauncherCommandNotFoundError,\n  ExternalLauncherBrowserSpawnError,\n  ExternalLauncherEditorSpawnError,\n]);\nexport type ExternalLauncherError = typeof ExternalLauncherError.Type;\n\nexport const isExternalLauncherError = Schema.is(ExternalLauncherError);\n","import * as Effect from \"effect/Effect\";\nimport * as Duration from \"effect/Duration\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport { TrimmedNonEmptyString, TrimmedString } from \"./baseSchemas.ts\";\nimport {\n  DEFAULT_TEXT_GENERATION_MODEL,\n  DEFAULT_TEXT_GENERATION_REASONING_EFFORT,\n  ProviderOptionSelections,\n} from \"./model.ts\";\nimport { ModelSelection } from \"./orchestration.ts\";\nimport { ProviderInstanceConfig, ProviderInstanceId } from \"./providerInstance.ts\";\n\n// ── Client Settings (local-only) ───────────────────────────────\n\nexport const TimestampFormat = Schema.Literals([\"locale\", \"12-hour\", \"24-hour\"]);\nexport type TimestampFormat = typeof TimestampFormat.Type;\nexport const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = \"locale\";\n\nexport const SidebarProjectSortOrder = Schema.Literals([\"updated_at\", \"created_at\", \"manual\"]);\nexport type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;\nexport const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = \"updated_at\";\n\nexport const SidebarThreadSortOrder = Schema.Literals([\"updated_at\", \"created_at\"]);\nexport type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;\nexport const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = \"updated_at\";\n\nexport const SidebarProjectGroupingMode = Schema.Literals([\n  \"repository\",\n  \"repository_path\",\n  \"separate\",\n]);\nexport type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type;\nexport const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = \"repository\";\nexport const MIN_SIDEBAR_THREAD_PREVIEW_COUNT = 1;\nexport const MAX_SIDEBAR_THREAD_PREVIEW_COUNT = 15;\nexport const SidebarThreadPreviewCount = Schema.Int.check(\n  Schema.isBetween({\n    minimum: MIN_SIDEBAR_THREAD_PREVIEW_COUNT,\n    maximum: MAX_SIDEBAR_THREAD_PREVIEW_COUNT,\n  }),\n);\nexport type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type;\nexport const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6;\nexport const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1;\nexport const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90;\nexport const SidebarAutoSettleAfterDays = Schema.Number.check(\n  Schema.isBetween({\n    minimum: MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,\n    maximum: MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,\n  }),\n);\nexport type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type;\nexport const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 3;\nexport const MIN_GLASS_OPACITY = 40;\nexport const MAX_GLASS_OPACITY = 100;\nexport const GlassOpacity = Schema.Int.check(\n  Schema.isBetween({\n    minimum: MIN_GLASS_OPACITY,\n    maximum: MAX_GLASS_OPACITY,\n  }),\n);\nexport type GlassOpacity = typeof GlassOpacity.Type;\nexport const DEFAULT_GLASS_OPACITY: GlassOpacity = 80;\n/**\n * Font size preferences, in CSS pixels. The ranges are deliberately narrow:\n * the interface size scales every rem-based dimension in the app, so the\n * bounds keep layouts intact rather than offering unusable extremes.\n */\nexport const MIN_INTERFACE_FONT_SIZE = 12;\nexport const MAX_INTERFACE_FONT_SIZE = 20;\nexport const InterfaceFontSize = Schema.Int.check(\n  Schema.isBetween({ minimum: MIN_INTERFACE_FONT_SIZE, maximum: MAX_INTERFACE_FONT_SIZE }),\n);\nexport type InterfaceFontSize = typeof InterfaceFontSize.Type;\nexport const DEFAULT_INTERFACE_FONT_SIZE: InterfaceFontSize = 16;\n\nexport const MIN_PROMPT_FONT_SIZE = 12;\nexport const MAX_PROMPT_FONT_SIZE = 20;\nexport const PromptFontSize = Schema.Int.check(\n  Schema.isBetween({ minimum: MIN_PROMPT_FONT_SIZE, maximum: MAX_PROMPT_FONT_SIZE }),\n);\nexport type PromptFontSize = typeof PromptFontSize.Type;\nexport const DEFAULT_PROMPT_FONT_SIZE: PromptFontSize = 14;\n\nexport const MIN_CODE_FONT_SIZE = 10;\nexport const MAX_CODE_FONT_SIZE = 18;\nexport const CodeFontSize = Schema.Int.check(\n  Schema.isBetween({ minimum: MIN_CODE_FONT_SIZE, maximum: MAX_CODE_FONT_SIZE }),\n);\nexport type CodeFontSize = typeof CodeFontSize.Type;\nexport const DEFAULT_CODE_FONT_SIZE: CodeFontSize = 13;\n\nexport const MIN_TERMINAL_FONT_SIZE = 8;\nexport const MAX_TERMINAL_FONT_SIZE = 20;\nexport const TerminalFontSize = Schema.Int.check(\n  Schema.isBetween({ minimum: MIN_TERMINAL_FONT_SIZE, maximum: MAX_TERMINAL_FONT_SIZE }),\n);\nexport type TerminalFontSize = typeof TerminalFontSize.Type;\nexport const DEFAULT_TERMINAL_FONT_SIZE: TerminalFontSize = 12;\n\nexport const EnvironmentIdentificationMode = Schema.Literals([\"artwork\", \"pill\", \"none\"]);\nexport type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type;\nexport const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = \"artwork\";\n\n/**\n * A user-chosen font family (a single name or a comma-separated list). Empty\n * means \"use the app default\"; clients compose their own fallback stacks.\n */\nexport const FontFamilyPreference = Schema.String.check(Schema.isMaxLength(200));\nexport type FontFamilyPreference = typeof FontFamilyPreference.Type;\n\nexport const ClientSettingsSchema = Schema.Struct({\n  confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n  dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(\n    Schema.withDecodingDefault(Effect.succeed([])),\n  ),\n  diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n  environmentIdentificationMode: EnvironmentIdentificationMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE)),\n  ),\n  glassOpacity: GlassOpacity.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_GLASS_OPACITY)),\n  ),\n  fontSizeInterface: InterfaceFontSize.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_INTERFACE_FONT_SIZE)),\n  ),\n  fontSizePrompt: PromptFontSize.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROMPT_FONT_SIZE)),\n  ),\n  fontSizeCode: CodeFontSize.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_CODE_FONT_SIZE)),\n  ),\n  fontSizeTerminal: TerminalFontSize.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_TERMINAL_FONT_SIZE)),\n  ),\n  fontFamilyCode: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  fontFamilyComposer: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  fontFamilySans: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  fontFamilyTerminal: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  // Grayscale `-webkit-font-smoothing: antialiased` (thinner strokes);\n  // disabling restores the platform's heavier default. No effect off macOS.\n  fontSmoothing: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n  // Model favorites. Historically keyed by provider kind, now\n  // widened to `ProviderInstanceId` so users can favorite a specific model\n  // on a custom provider instance (e.g. \"Codex Personal · gpt-5\") without\n  // the UI collapsing it into the same bucket as the default Codex. The\n  // widening is backward-compatible by construction: prior provider-kind\n  // strings satisfy the `ProviderInstanceId` slug schema, so previously\n  // persisted favorites decode unchanged and continue to point at the\n  // default instance for their kind (because `defaultInstanceIdForDriver(kind)`\n  // uses the same slug). The field name is kept as `provider` for storage\n  // stability; new call sites should treat the value as an instance id.\n  favorites: Schema.Array(\n    Schema.Struct({\n      provider: ProviderInstanceId,\n      model: TrimmedNonEmptyString,\n    }),\n  ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n  providerModelPreferences: Schema.Record(\n    ProviderInstanceId,\n    Schema.Struct({\n      hiddenModels: Schema.Array(Schema.String).pipe(\n        Schema.withDecodingDefault(Effect.succeed([])),\n      ),\n      modelOrder: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n    }),\n  ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n  // Legacy plan mode. The composer's Build/Plan toggle was removed from the\n  // default UI; this beta flag restores it (plus the /plan and /default slash\n  // commands) for users who still rely on the old workflow.\n  planModeEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  // Legacy sidebar (the original per-project tree). Deliberately a fresh key\n  // (was `sidebarV2Enabled` + `sidebarV2ConfiguredByUser`): decoding drops the\n  // old keys, so everyone, including prior beta opt-outs, resets to the new\n  // default sidebar.\n  legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),\n  ),\n  sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),\n  ),\n  sidebarProjectGroupingOverrides: Schema.Record(\n    TrimmedNonEmptyString,\n    SidebarProjectGroupingMode,\n  ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n  sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),\n  ),\n  sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),\n  ),\n  sidebarThreadPreviewCount: SidebarThreadPreviewCount.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT)),\n  ),\n  timestampFormat: TimestampFormat.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),\n  ),\n  wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n});\nexport type ClientSettings = typeof ClientSettingsSchema.Type;\n\nexport const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});\n\n// ── Server Settings (server-authoritative) ────────────────────\n\nexport const ThreadEnvMode = Schema.Literals([\"local\", \"worktree\"]);\nexport type ThreadEnvMode = typeof ThreadEnvMode.Type;\n\nconst makeBinaryPathSetting = (fallback: string) =>\n  TrimmedString.pipe(\n    Schema.decodeTo(\n      Schema.String,\n      SchemaTransformation.transformOrFail({\n        decode: (value) => Effect.succeed(value || fallback),\n        encode: (value) => Effect.succeed(value),\n      }),\n    ),\n    Schema.withDecodingDefault(Effect.succeed(fallback)),\n  );\n\nexport type ProviderSettingsFormControl = \"text\" | \"password\" | \"textarea\" | \"switch\";\n\nexport interface ProviderSettingsFormAnnotation {\n  readonly control?: ProviderSettingsFormControl | undefined;\n  readonly placeholder?: string | undefined;\n  readonly hidden?: boolean | undefined;\n  readonly clearWhenEmpty?: \"omit\" | \"persist\" | undefined;\n}\n\nexport interface ProviderSettingsFormSchemaAnnotation {\n  readonly order?: readonly string[] | undefined;\n}\n\ndeclare module \"effect/Schema\" {\n  namespace Annotations {\n    interface Annotations {\n      readonly providerSettingsForm?: ProviderSettingsFormAnnotation | undefined;\n      readonly providerSettingsFormSchema?: ProviderSettingsFormSchemaAnnotation | undefined;\n    }\n  }\n}\n\nexport type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<\n  keyof Fields,\n  string\n>[];\n\nexport function makeProviderSettingsSchema<const Fields extends Schema.Struct.Fields>(\n  fields: Fields,\n  options?: {\n    readonly order?: ProviderSettingsOrder<Fields> | undefined;\n  },\n): Schema.Struct<Fields> {\n  return Schema.Struct(fields).pipe(\n    Schema.annotate({\n      providerSettingsFormSchema:\n        options?.order === undefined ? undefined : { order: options.order },\n    }),\n  );\n}\n\nexport const CodexSettings = makeProviderSettingsSchema(\n  {\n    enabled: Schema.Boolean.pipe(\n      Schema.withDecodingDefault(Effect.succeed(true)),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n    binaryPath: makeBinaryPathSetting(\"codex\").pipe(\n      Schema.annotateKey({\n        title: \"Binary path\",\n        description: \"Path to the Codex binary used by this instance.\",\n        providerSettingsForm: { placeholder: \"codex\", clearWhenEmpty: \"omit\" },\n      }),\n    ),\n    homePath: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"CODEX_HOME path\",\n        description: \"Custom Codex home and config directory.\",\n        providerSettingsForm: {\n          placeholder: \"~/.codex\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n    shadowHomePath: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"Shadow home path\",\n        description:\n          \"Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.\",\n        providerSettingsForm: {\n          placeholder: \"~/.codex-synaptic/personal\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n    launchArgs: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"Launch arguments\",\n        description: \"Additional CLI arguments passed to codex app-server on session start.\",\n      }),\n    ),\n    customModels: Schema.Array(Schema.String).pipe(\n      Schema.withDecodingDefault(Effect.succeed([])),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n  },\n  {\n    order: [\"binaryPath\", \"homePath\", \"shadowHomePath\", \"launchArgs\"],\n  },\n);\nexport type CodexSettings = typeof CodexSettings.Type;\n\nexport const ClaudeSettings = makeProviderSettingsSchema(\n  {\n    enabled: Schema.Boolean.pipe(\n      Schema.withDecodingDefault(Effect.succeed(true)),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n    binaryPath: makeBinaryPathSetting(\"claude\").pipe(\n      Schema.annotateKey({\n        title: \"Binary path\",\n        description: \"Path to the Claude binary used by this instance.\",\n        providerSettingsForm: { placeholder: \"claude\", clearWhenEmpty: \"omit\" },\n      }),\n    ),\n    homePath: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"CLAUDE_CONFIG_DIR path\",\n        description:\n          \"Custom Claude home and config directory. Keeps .claude.json and .claude separate.\",\n        providerSettingsForm: { placeholder: \"~/.claude\", clearWhenEmpty: \"omit\" },\n      }),\n    ),\n    customModels: Schema.Array(Schema.String).pipe(\n      Schema.withDecodingDefault(Effect.succeed([])),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n    launchArgs: Schema.String.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"Launch arguments\",\n        description: \"Additional CLI arguments passed on session start.\",\n        providerSettingsForm: {\n          placeholder: \"e.g. --chrome\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n  },\n  {\n    order: [\"binaryPath\", \"homePath\", \"launchArgs\"],\n  },\n);\nexport type ClaudeSettings = typeof ClaudeSettings.Type;\n\nexport const CursorSettings = makeProviderSettingsSchema(\n  {\n    enabled: Schema.Boolean.pipe(\n      Schema.withDecodingDefault(Effect.succeed(false)),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n    binaryPath: makeBinaryPathSetting(\"cursor-agent\").pipe(\n      Schema.annotateKey({\n        title: \"Binary path\",\n        description: \"Path to the Cursor agent binary.\",\n        providerSettingsForm: { placeholder: \"cursor-agent\", clearWhenEmpty: \"omit\" },\n      }),\n    ),\n    apiEndpoint: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"API endpoint\",\n        description: \"Override the Cursor API endpoint for this instance.\",\n        providerSettingsForm: {\n          placeholder: \"https://...\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n    customModels: Schema.Array(Schema.String).pipe(\n      Schema.withDecodingDefault(Effect.succeed([])),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n  },\n  {\n    order: [\"binaryPath\", \"apiEndpoint\"],\n  },\n);\nexport type CursorSettings = typeof CursorSettings.Type;\n\nexport const GrokSettings = makeProviderSettingsSchema(\n  {\n    enabled: Schema.Boolean.pipe(\n      Schema.withDecodingDefault(Effect.succeed(true)),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n    binaryPath: makeBinaryPathSetting(\"grok\").pipe(\n      Schema.annotateKey({\n        title: \"Binary path\",\n        description: \"Path to the Grok CLI binary.\",\n        providerSettingsForm: { placeholder: \"grok\", clearWhenEmpty: \"omit\" },\n      }),\n    ),\n    customModels: Schema.Array(Schema.String).pipe(\n      Schema.withDecodingDefault(Effect.succeed([])),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n  },\n  {\n    order: [\"binaryPath\"],\n  },\n);\nexport type GrokSettings = typeof GrokSettings.Type;\n\nexport const OpenCodeSettings = makeProviderSettingsSchema(\n  {\n    enabled: Schema.Boolean.pipe(\n      Schema.withDecodingDefault(Effect.succeed(true)),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n    binaryPath: makeBinaryPathSetting(\"opencode\").pipe(\n      Schema.annotateKey({\n        title: \"Binary path\",\n        description: \"Path to the OpenCode binary.\",\n        providerSettingsForm: {\n          placeholder: \"opencode\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n    serverUrl: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"Server URL\",\n        description: \"Leave blank to let Synaptic Code spawn the server when needed.\",\n        providerSettingsForm: {\n          placeholder: \"http://127.0.0.1:4096\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n    serverPassword: TrimmedString.pipe(\n      Schema.withDecodingDefault(Effect.succeed(\"\")),\n      Schema.annotateKey({\n        title: \"Server password\",\n        description: \"Stored in plain text on disk.\",\n        providerSettingsForm: {\n          control: \"password\",\n          placeholder: \"Optional\",\n          clearWhenEmpty: \"omit\",\n        },\n      }),\n    ),\n    customModels: Schema.Array(Schema.String).pipe(\n      Schema.withDecodingDefault(Effect.succeed([])),\n      Schema.annotateKey({ providerSettingsForm: { hidden: true } }),\n    ),\n  },\n  {\n    order: [\"binaryPath\", \"serverUrl\", \"serverPassword\"],\n  },\n);\nexport type OpenCodeSettings = typeof OpenCodeSettings.Type;\n\nexport const ObservabilitySettings = Schema.Struct({\n  otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n});\nexport type ObservabilitySettings = typeof ObservabilitySettings.Type;\n\nexport const SourceControlWritingStyleMode = Schema.Literals([\n  \"repo_conventions\",\n  \"conventional_commits\",\n  \"custom\",\n]);\nexport type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;\n\nexport const SourceControlWritingStyleSettings = Schema.Struct({\n  mode: SourceControlWritingStyleMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(\"repo_conventions\" as const)),\n  ),\n  customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  followChangeRequestTemplates: Schema.Boolean.pipe(\n    Schema.withDecodingDefault(Effect.succeed(true)),\n  ),\n});\nexport type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;\n\nexport const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);\nexport const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);\n\nexport const BackgroundActivityProfile = Schema.Literals([\n  \"balanced\",\n  \"performance\",\n  \"battery-saver\",\n]);\nexport type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;\nexport const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = \"balanced\";\n\nexport const BackgroundActivityProfileSelection = Schema.Literals([\n  \"balanced\",\n  \"performance\",\n  \"battery-saver\",\n  \"custom\",\n]);\nexport type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;\n\nexport const BackgroundActivityOverrides = Schema.Struct({\n  automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),\n  pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),\n  pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),\n  pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),\n  pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),\n});\nexport type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;\n\nexport const BackgroundActivitySettings = Schema.Struct({\n  schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),\n  profile: BackgroundActivityProfileSelection.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),\n  ),\n  baseProfile: Schema.optionalKey(BackgroundActivityProfile),\n  overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n}).pipe(Schema.withDecodingDefault(Effect.succeed({})));\nexport type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;\n\nexport const ServerSettings = Schema.Struct({\n  // Legacy token-by-token assistant output. Deliberately a fresh key (was\n  // `enableAssistantStreaming`): decoding drops the old key, so everyone,\n  // including prior opt-ins, resets to the buffered default.\n  enableLegacyTokenStreaming: Schema.Boolean.pipe(\n    Schema.withDecodingDefault(Effect.succeed(false)),\n  ),\n  enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),\n  backgroundActivity: BackgroundActivitySettings,\n  // Legacy flat fields retained for old settings files and old clients. New\n  // consumers should resolve `backgroundActivity` instead.\n  automaticGitFetchInterval: Schema.DurationFromMillis.pipe(\n    Schema.withDecodingDefault(\n      Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),\n    ),\n  ),\n  providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(\n    Schema.withDecodingDefault(\n      Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),\n    ),\n  ),\n  backgroundActivityProfile: BackgroundActivityProfile.pipe(\n    Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),\n  ),\n  defaultThreadEnvMode: ThreadEnvMode.pipe(\n    Schema.withDecodingDefault(Effect.succeed(\"local\" as const satisfies ThreadEnvMode)),\n  ),\n  newWorktreesStartFromOrigin: Schema.Boolean.pipe(\n    Schema.withDecodingDefault(Effect.succeed(true)),\n  ),\n  addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(\"\"))),\n  textGenerationModelSelection: ModelSelection.pipe(\n    Schema.withDecodingDefault(\n      Effect.succeed({\n        instanceId: ProviderInstanceId.make(\"codex\"),\n        model: DEFAULT_TEXT_GENERATION_MODEL,\n        options: [\n          {\n            id: \"reasoningEffort\",\n            value: DEFAULT_TEXT_GENERATION_REASONING_EFFORT,\n          },\n        ],\n      }),\n    ),\n  ),\n  sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(\n    Schema.withDecodingDefault(Effect.succeed({})),\n  ),\n  sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(\n    Schema.withDecodingDefault(Effect.succeed(null)),\n  ),\n\n  // Legacy single-instance-per-driver settings. Continues to be the source\n  // of truth until `providerInstances` (below) lands per-driver migration\n  // shims and the server starts hydrating instances from it. Driver-specific\n  // schemas live here for the duration of the migration; once each driver\n  // owns its config in its own package, this struct shrinks to nothing and\n  // is removed entirely.\n  providers: Schema.Struct({\n    codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n    claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n    cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n    grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n    opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n  }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n  // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values\n  // are `ProviderInstanceConfig` envelopes. The driver-specific config blob\n  // is `Schema.Unknown` at this layer so envelopes with unknown drivers\n  // (forks, downgrades, in-flight PR branches) round-trip without loss.\n  // See providerInstance.ts for the forward/backward compatibility invariant.\n  providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(\n    Schema.withDecodingDefault(Effect.succeed({})),\n  ),\n  observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),\n});\nexport type ServerSettings = typeof ServerSettings.Type;\n\nexport const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});\n\nexport const ServerSettingsOperation = Schema.Literals([\n  \"normalize\",\n  \"check-exists\",\n  \"read-file\",\n  \"read-secret\",\n  \"remove-secret\",\n  \"remove-stale-secret\",\n  \"write-secret\",\n  \"write-file\",\n  \"prepare-directory\",\n]);\nexport type ServerSettingsOperation = typeof ServerSettingsOperation.Type;\n\nexport class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(\n  \"ServerSettingsError\",\n  {\n    settingsPath: Schema.String,\n    operation: ServerSettingsOperation,\n    providerInstanceId: Schema.optional(Schema.String),\n    environmentVariable: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    const provider =\n      this.providerInstanceId === undefined ? \"\" : ` for provider ${this.providerInstanceId}`;\n    const variable =\n      this.environmentVariable === undefined\n        ? \"\"\n        : ` and environment variable ${this.environmentVariable}`;\n    return `Server settings ${this.operation} failed${provider}${variable} at ${this.settingsPath}.`;\n  }\n}\n\n// ── Unified type ─────────────────────────────────────────────────────\n\nexport type UnifiedSettings = ServerSettings & ClientSettings;\nexport const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {\n  ...DEFAULT_SERVER_SETTINGS,\n  ...DEFAULT_CLIENT_SETTINGS,\n};\n\n// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────\n\nconst ModelSelectionPatch = Schema.Struct({\n  instanceId: Schema.optionalKey(ProviderInstanceId),\n  model: Schema.optionalKey(TrimmedNonEmptyString),\n  options: Schema.optionalKey(ProviderOptionSelections),\n});\n\nconst CodexSettingsPatch = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Boolean),\n  binaryPath: Schema.optionalKey(TrimmedString),\n  homePath: Schema.optionalKey(TrimmedString),\n  shadowHomePath: Schema.optionalKey(TrimmedString),\n  launchArgs: Schema.optionalKey(TrimmedString),\n  customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n});\n\nconst ClaudeSettingsPatch = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Boolean),\n  binaryPath: Schema.optionalKey(TrimmedString),\n  homePath: Schema.optionalKey(TrimmedString),\n  customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n  launchArgs: Schema.optionalKey(TrimmedString),\n});\n\nconst CursorSettingsPatch = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Boolean),\n  binaryPath: Schema.optionalKey(TrimmedString),\n  apiEndpoint: Schema.optionalKey(TrimmedString),\n  customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n});\n\nconst GrokSettingsPatch = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Boolean),\n  binaryPath: Schema.optionalKey(TrimmedString),\n  customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n});\n\nconst OpenCodeSettingsPatch = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Boolean),\n  binaryPath: Schema.optionalKey(TrimmedString),\n  serverUrl: Schema.optionalKey(TrimmedString),\n  serverPassword: Schema.optionalKey(TrimmedString),\n  customModels: Schema.optionalKey(Schema.Array(Schema.String)),\n});\n\nexport const ServerSettingsPatch = Schema.Struct({\n  // Server settings\n  enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),\n  enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),\n  backgroundActivity: Schema.optionalKey(\n    Schema.Struct({\n      schemaVersion: Schema.optionalKey(Schema.Literal(1)),\n      profile: Schema.optionalKey(BackgroundActivityProfileSelection),\n      baseProfile: Schema.optionalKey(BackgroundActivityProfile),\n      overrides: Schema.optionalKey(BackgroundActivityOverrides),\n    }),\n  ),\n  automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),\n  backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),\n  defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),\n  newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),\n  addProjectBaseDirectory: Schema.optionalKey(TrimmedString),\n  textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),\n  sourceControlWritingStyle: Schema.optionalKey(\n    Schema.Struct({\n      mode: Schema.optionalKey(SourceControlWritingStyleMode),\n      customInstructions: Schema.optionalKey(TrimmedString),\n      followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),\n    }),\n  ),\n  sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),\n  observability: Schema.optionalKey(\n    Schema.Struct({\n      otlpTracesUrl: Schema.optionalKey(TrimmedString),\n      otlpMetricsUrl: Schema.optionalKey(TrimmedString),\n    }),\n  ),\n  providers: Schema.optionalKey(\n    Schema.Struct({\n      codex: Schema.optionalKey(CodexSettingsPatch),\n      claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),\n      cursor: Schema.optionalKey(CursorSettingsPatch),\n      grok: Schema.optionalKey(GrokSettingsPatch),\n      opencode: Schema.optionalKey(OpenCodeSettingsPatch),\n    }),\n  ),\n  // Whole-map replacement for the new instance config. Patching individual\n  // entries is intentionally out of scope: the map is small, and partial\n  // patches risk leaving driver-specific config in a half-merged state.\n  // The web UI sends a fully-formed map every time it edits this field.\n  providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),\n});\nexport type ServerSettingsPatch = typeof ServerSettingsPatch.Type;\n\nexport const ClientSettingsPatch = Schema.Struct({\n  confirmThreadArchive: Schema.optionalKey(Schema.Boolean),\n  confirmThreadDelete: Schema.optionalKey(Schema.Boolean),\n  diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),\n  environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),\n  glassOpacity: Schema.optionalKey(GlassOpacity),\n  fontSizeInterface: Schema.optionalKey(InterfaceFontSize),\n  fontSizePrompt: Schema.optionalKey(PromptFontSize),\n  fontSizeCode: Schema.optionalKey(CodeFontSize),\n  fontSizeTerminal: Schema.optionalKey(TerminalFontSize),\n  fontFamilyCode: Schema.optionalKey(FontFamilyPreference),\n  fontFamilyComposer: Schema.optionalKey(FontFamilyPreference),\n  fontFamilySans: Schema.optionalKey(FontFamilyPreference),\n  fontFamilyTerminal: Schema.optionalKey(FontFamilyPreference),\n  fontSmoothing: Schema.optionalKey(Schema.Boolean),\n  favorites: Schema.optionalKey(\n    Schema.Array(\n      Schema.Struct({\n        provider: ProviderInstanceId,\n        model: TrimmedNonEmptyString,\n      }),\n    ),\n  ),\n  providerModelPreferences: Schema.optionalKey(\n    Schema.Record(\n      ProviderInstanceId,\n      Schema.Struct({\n        hiddenModels: Schema.Array(Schema.String).pipe(\n          Schema.withDecodingDefault(Effect.succeed([])),\n        ),\n        modelOrder: Schema.Array(Schema.String).pipe(\n          Schema.withDecodingDefault(Effect.succeed([])),\n        ),\n      }),\n    ),\n  ),\n  planModeEnabled: Schema.optionalKey(Schema.Boolean),\n  legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),\n  sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),\n  sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),\n  sidebarProjectGroupingOverrides: Schema.optionalKey(\n    Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),\n  ),\n  sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),\n  sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),\n  sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),\n  timestampFormat: Schema.optionalKey(TimestampFormat),\n  wordWrap: Schema.optionalKey(Schema.Boolean),\n});\nexport type ClientSettingsPatch = typeof ClientSettingsPatch.Type;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport { ExecutionEnvironmentDescriptor, ServerSelfUpdateMethod } from \"./environment.ts\";\nimport { ServerAuthDescriptor } from \"./auth.ts\";\nimport {\n  ForwardCompatibleArray,\n  IsoDateTime,\n  NonNegativeInt,\n  PositiveInt,\n  ProjectId,\n  ThreadId,\n  TrimmedNonEmptyString,\n} from \"./baseSchemas.ts\";\nimport {\n  KeybindingCommand,\n  KeybindingValue,\n  KeybindingWhen,\n  ResolvedKeybindingsConfig,\n} from \"./keybindings.ts\";\nimport { EditorId } from \"./editor.ts\";\nimport { ModelCapabilities } from \"./model.ts\";\nimport { ProviderDriverKind, ProviderInstanceId } from \"./providerInstance.ts\";\nimport { ServerSettings } from \"./settings.ts\";\n\nconst KeybindingsMalformedConfigIssue = Schema.Struct({\n  kind: Schema.Literal(\"keybindings.malformed-config\"),\n  message: TrimmedNonEmptyString,\n});\n\nconst KeybindingsInvalidEntryIssue = Schema.Struct({\n  kind: Schema.Literal(\"keybindings.invalid-entry\"),\n  message: TrimmedNonEmptyString,\n  index: Schema.Number,\n});\n\nexport const ServerConfigIssue = Schema.Union([\n  KeybindingsMalformedConfigIssue,\n  KeybindingsInvalidEntryIssue,\n]);\nexport type ServerConfigIssue = typeof ServerConfigIssue.Type;\n\n// Issue kinds grow over time; older clients must not fail the whole config\n// decode over a kind they cannot render.\nconst ServerConfigIssues = ForwardCompatibleArray(ServerConfigIssue);\n\nexport const ServerProviderState = Schema.Literals([\"ready\", \"warning\", \"error\", \"disabled\"]);\nexport type ServerProviderState = typeof ServerProviderState.Type;\n\nexport const ServerProviderAuthStatus = Schema.Literals([\n  \"authenticated\",\n  \"unauthenticated\",\n  \"unknown\",\n]);\nexport type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;\n\nexport const ServerProviderAuth = Schema.Struct({\n  status: ServerProviderAuthStatus,\n  type: Schema.optional(TrimmedNonEmptyString),\n  label: Schema.optional(TrimmedNonEmptyString),\n  email: Schema.optional(TrimmedNonEmptyString),\n});\nexport type ServerProviderAuth = typeof ServerProviderAuth.Type;\n\nexport const ServerProviderModel = Schema.Struct({\n  slug: TrimmedNonEmptyString,\n  name: TrimmedNonEmptyString,\n  shortName: Schema.optional(TrimmedNonEmptyString),\n  subProvider: Schema.optional(TrimmedNonEmptyString),\n  isCustom: Schema.Boolean,\n  isDefault: Schema.optional(Schema.Boolean),\n  isLegacy: Schema.optional(Schema.Boolean),\n  capabilities: Schema.NullOr(ModelCapabilities),\n});\nexport type ServerProviderModel = typeof ServerProviderModel.Type;\n\nexport const ServerProviderSlashCommandInput = Schema.Struct({\n  hint: TrimmedNonEmptyString,\n});\nexport type ServerProviderSlashCommandInput = typeof ServerProviderSlashCommandInput.Type;\n\nexport const ServerProviderSlashCommand = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  description: Schema.optional(TrimmedNonEmptyString),\n  input: Schema.optional(ServerProviderSlashCommandInput),\n});\nexport type ServerProviderSlashCommand = typeof ServerProviderSlashCommand.Type;\n\nexport const ServerProviderSkill = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  description: Schema.optional(TrimmedNonEmptyString),\n  path: TrimmedNonEmptyString,\n  scope: Schema.optional(TrimmedNonEmptyString),\n  enabled: Schema.Boolean,\n  displayName: Schema.optional(TrimmedNonEmptyString),\n  shortDescription: Schema.optional(TrimmedNonEmptyString),\n});\nexport type ServerProviderSkill = typeof ServerProviderSkill.Type;\n\n/**\n * Availability of a configured provider instance from the runtime's POV.\n *\n *  - `available` — the build ships this driver and an instance is wired\n *    up. Default for legacy snapshots produced from the closed\n *    `ServerSettings.providers` map.\n *  - `unavailable` — the user's `ServerSettings.providerInstances` (or a\n *    persisted thread / session binding) references a driver this build\n *    doesn't ship. Common after rolling back from a fork or PR branch\n *    that introduced a new driver. The snapshot is preserved so the UI\n *    can render \"missing driver\" affordances and so the data round-trips\n *    when the user moves back to the fork.\n *\n * Snapshots with `availability: \"unavailable\"` MUST set\n * `installed: false` and `enabled: false`; the runtime refuses turn\n * starts against them with a structured error.\n */\nexport const ServerProviderAvailability = Schema.Literals([\"available\", \"unavailable\"]);\nexport type ServerProviderAvailability = typeof ServerProviderAvailability.Type;\n\nexport const ServerProviderContinuation = Schema.Struct({\n  groupKey: TrimmedNonEmptyString,\n});\nexport type ServerProviderContinuation = typeof ServerProviderContinuation.Type;\n\nexport const ServerProviderVersionAdvisoryStatus = Schema.Literals([\n  \"unknown\",\n  \"current\",\n  \"behind_latest\",\n]);\nexport type ServerProviderVersionAdvisoryStatus = typeof ServerProviderVersionAdvisoryStatus.Type;\n\nexport const ServerProviderVersionAdvisory = Schema.Struct({\n  status: ServerProviderVersionAdvisoryStatus,\n  currentVersion: Schema.NullOr(TrimmedNonEmptyString),\n  latestVersion: Schema.NullOr(TrimmedNonEmptyString),\n  updateCommand: Schema.NullOr(TrimmedNonEmptyString),\n  canUpdate: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),\n  checkedAt: Schema.NullOr(IsoDateTime),\n  message: Schema.NullOr(TrimmedNonEmptyString),\n});\nexport type ServerProviderVersionAdvisory = typeof ServerProviderVersionAdvisory.Type;\n\nexport const ServerProviderUpdateStatus = Schema.Literals([\n  \"idle\",\n  \"queued\",\n  \"running\",\n  \"succeeded\",\n  \"failed\",\n  \"unchanged\",\n]);\nexport type ServerProviderUpdateStatus = typeof ServerProviderUpdateStatus.Type;\n\nexport const ServerProviderUpdateState = Schema.Struct({\n  status: ServerProviderUpdateStatus,\n  startedAt: Schema.NullOr(IsoDateTime),\n  finishedAt: Schema.NullOr(IsoDateTime),\n  message: Schema.NullOr(TrimmedNonEmptyString),\n  output: Schema.NullOr(Schema.String.check(Schema.isMaxLength(10_000))),\n});\nexport type ServerProviderUpdateState = typeof ServerProviderUpdateState.Type;\n\nexport const ServerProvider = Schema.Struct({\n  // Routing key for the configured instance this snapshot represents. This\n  // is the only stable identity consumers may use for provider routing.\n  instanceId: ProviderInstanceId,\n  // Open driver kind slug that selects the implementation handling this\n  // instance. It is metadata/capability context, not a routing key.\n  driver: ProviderDriverKind,\n  displayName: Schema.optional(TrimmedNonEmptyString),\n  accentColor: Schema.optional(TrimmedNonEmptyString),\n  badgeLabel: Schema.optional(TrimmedNonEmptyString),\n  continuation: Schema.optional(ServerProviderContinuation),\n  showInteractionModeToggle: Schema.optional(Schema.Boolean),\n  requiresNewThreadForModelChange: Schema.optional(Schema.Boolean),\n  enabled: Schema.Boolean,\n  installed: Schema.Boolean,\n  version: Schema.NullOr(TrimmedNonEmptyString),\n  status: ServerProviderState,\n  auth: ServerProviderAuth,\n  checkedAt: IsoDateTime,\n  message: Schema.optional(TrimmedNonEmptyString),\n  // Optional for back-compat: every legacy producer omits this field and\n  // an absent value is interpreted as `\"available\"` by consumers (see\n  // `isProviderAvailable`). New `ProviderInstanceRegistry` outputs set it\n  // explicitly so the UI can render unavailable shadows from\n  // `ServerSettings.providerInstances`.\n  availability: Schema.optional(ServerProviderAvailability),\n  // Human-readable reason populated when `availability === \"unavailable\"`.\n  // Surfaces in the UI alongside the missing-driver affordance.\n  unavailableReason: Schema.optional(TrimmedNonEmptyString),\n  models: Schema.Array(ServerProviderModel),\n  slashCommands: Schema.Array(ServerProviderSlashCommand).pipe(\n    Schema.withDecodingDefault(Effect.succeed([])),\n  ),\n  skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))),\n  versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory),\n  updateState: Schema.optionalKey(ServerProviderUpdateState),\n});\nexport type ServerProvider = typeof ServerProvider.Type;\n\n// Provider status kinds grow over time (ServerProviderState,\n// ServerProviderAuthStatus, ServerProviderVersionAdvisoryStatus,\n// ServerProviderUpdateStatus); an older client must not fail the whole config\n// decode over one provider it cannot render.\nexport const ServerProviders = ForwardCompatibleArray(ServerProvider);\nexport type ServerProviders = typeof ServerProviders.Type;\n\n/**\n * Treat the optional `availability` as \"available\" when absent. This is\n * the rule legacy producers (which omit the field) and new producers\n * (which set it explicitly) agree on so consumers never have to thread\n * `?? \"available\"` defaults through their code paths.\n */\nexport const isProviderAvailable = (snapshot: ServerProvider): boolean =>\n  snapshot.availability !== \"unavailable\";\n\nexport const ServerObservability = Schema.Struct({\n  logsDirectoryPath: TrimmedNonEmptyString,\n  localTracingEnabled: Schema.Boolean,\n  otlpTracesUrl: Schema.optional(TrimmedNonEmptyString),\n  otlpTracesEnabled: Schema.Boolean,\n  otlpMetricsUrl: Schema.optional(TrimmedNonEmptyString),\n  otlpMetricsEnabled: Schema.Boolean,\n});\nexport type ServerObservability = typeof ServerObservability.Type;\n\nexport const ServerTraceDiagnosticsErrorKind = Schema.Literals([\n  \"trace-file-not-found\",\n  \"trace-file-read-failed\",\n]);\nexport type ServerTraceDiagnosticsErrorKind = typeof ServerTraceDiagnosticsErrorKind.Type;\n\nexport const ServerTraceDiagnosticsSpanSummary = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  count: NonNegativeInt,\n  failureCount: NonNegativeInt,\n  totalDurationMs: Schema.Number,\n  averageDurationMs: Schema.Number,\n  maxDurationMs: Schema.Number,\n});\nexport type ServerTraceDiagnosticsSpanSummary = typeof ServerTraceDiagnosticsSpanSummary.Type;\n\nexport const ServerTraceDiagnosticsFailureSummary = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  cause: TrimmedNonEmptyString,\n  count: NonNegativeInt,\n  lastSeenAt: Schema.DateTimeUtc,\n  traceId: TrimmedNonEmptyString,\n  spanId: TrimmedNonEmptyString,\n});\nexport type ServerTraceDiagnosticsFailureSummary = typeof ServerTraceDiagnosticsFailureSummary.Type;\n\nexport const ServerTraceDiagnosticsRecentFailure = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  cause: TrimmedNonEmptyString,\n  durationMs: Schema.Number,\n  endedAt: Schema.DateTimeUtc,\n  traceId: TrimmedNonEmptyString,\n  spanId: TrimmedNonEmptyString,\n});\nexport type ServerTraceDiagnosticsRecentFailure = typeof ServerTraceDiagnosticsRecentFailure.Type;\n\nexport const ServerTraceDiagnosticsSpanOccurrence = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  durationMs: Schema.Number,\n  endedAt: Schema.DateTimeUtc,\n  traceId: TrimmedNonEmptyString,\n  spanId: TrimmedNonEmptyString,\n});\nexport type ServerTraceDiagnosticsSpanOccurrence = typeof ServerTraceDiagnosticsSpanOccurrence.Type;\n\nexport const ServerTraceDiagnosticsLogEvent = Schema.Struct({\n  spanName: TrimmedNonEmptyString,\n  level: TrimmedNonEmptyString,\n  message: TrimmedNonEmptyString,\n  seenAt: Schema.DateTimeUtc,\n  traceId: TrimmedNonEmptyString,\n  spanId: TrimmedNonEmptyString,\n});\nexport type ServerTraceDiagnosticsLogEvent = typeof ServerTraceDiagnosticsLogEvent.Type;\n\nexport const ServerTraceDiagnosticsResult = Schema.Struct({\n  traceFilePath: TrimmedNonEmptyString,\n  scannedFilePaths: Schema.Array(TrimmedNonEmptyString),\n  readAt: Schema.DateTimeUtc,\n  recordCount: NonNegativeInt,\n  parseErrorCount: NonNegativeInt,\n  firstSpanAt: Schema.Option(Schema.DateTimeUtc),\n  lastSpanAt: Schema.Option(Schema.DateTimeUtc),\n  failureCount: NonNegativeInt,\n  interruptionCount: NonNegativeInt,\n  slowSpanThresholdMs: NonNegativeInt,\n  slowSpanCount: NonNegativeInt,\n  logLevelCounts: Schema.Record(TrimmedNonEmptyString, NonNegativeInt),\n  topSpansByCount: Schema.Array(ServerTraceDiagnosticsSpanSummary),\n  slowestSpans: Schema.Array(ServerTraceDiagnosticsSpanOccurrence),\n  commonFailures: Schema.Array(ServerTraceDiagnosticsFailureSummary),\n  latestFailures: Schema.Array(ServerTraceDiagnosticsRecentFailure),\n  latestWarningAndErrorLogs: Schema.Array(ServerTraceDiagnosticsLogEvent),\n  partialFailure: Schema.Option(Schema.Boolean),\n  error: Schema.Option(\n    Schema.Struct({\n      kind: ServerTraceDiagnosticsErrorKind,\n      message: TrimmedNonEmptyString,\n    }),\n  ),\n});\nexport type ServerTraceDiagnosticsResult = typeof ServerTraceDiagnosticsResult.Type;\n\nexport const ServerProcessSignal = Schema.Literals([\"SIGINT\", \"SIGKILL\"]);\nexport type ServerProcessSignal = typeof ServerProcessSignal.Type;\n\nexport const ServerProcessDiagnosticsEntry = Schema.Struct({\n  pid: PositiveInt,\n  startTimeMs: NonNegativeInt,\n  ppid: NonNegativeInt,\n  pgid: Schema.Option(Schema.Int),\n  status: TrimmedNonEmptyString,\n  cpuPercent: Schema.Number,\n  rssBytes: NonNegativeInt,\n  elapsed: TrimmedNonEmptyString,\n  command: TrimmedNonEmptyString,\n  depth: NonNegativeInt,\n  childPids: Schema.Array(PositiveInt),\n});\nexport type ServerProcessDiagnosticsEntry = typeof ServerProcessDiagnosticsEntry.Type;\n\nexport const ServerProcessDiagnosticsResult = Schema.Struct({\n  serverPid: PositiveInt,\n  readAt: Schema.DateTimeUtc,\n  processCount: NonNegativeInt,\n  totalRssBytes: NonNegativeInt,\n  totalCpuPercent: Schema.Number,\n  processes: Schema.Array(ServerProcessDiagnosticsEntry),\n  error: Schema.Option(\n    Schema.Struct({\n      message: TrimmedNonEmptyString,\n    }),\n  ),\n});\nexport type ServerProcessDiagnosticsResult = typeof ServerProcessDiagnosticsResult.Type;\n\nexport const ServerProcessResourceHistoryInput = Schema.Struct({\n  windowMs: NonNegativeInt,\n  bucketMs: NonNegativeInt,\n});\nexport type ServerProcessResourceHistoryInput = typeof ServerProcessResourceHistoryInput.Type;\n\nexport const ServerProcessResourceHistoryBucket = Schema.Struct({\n  startedAt: Schema.DateTimeUtc,\n  endedAt: Schema.DateTimeUtc,\n  avgCpuPercent: Schema.Number,\n  maxCpuPercent: Schema.Number,\n  maxRssBytes: NonNegativeInt,\n  maxProcessCount: NonNegativeInt,\n});\nexport type ServerProcessResourceHistoryBucket = typeof ServerProcessResourceHistoryBucket.Type;\n\nexport const ServerProcessResourceHistorySummary = Schema.Struct({\n  processKey: TrimmedNonEmptyString,\n  pid: PositiveInt,\n  ppid: NonNegativeInt,\n  command: TrimmedNonEmptyString,\n  depth: NonNegativeInt,\n  isServerRoot: Schema.Boolean,\n  firstSeenAt: Schema.DateTimeUtc,\n  lastSeenAt: Schema.DateTimeUtc,\n  currentCpuPercent: Schema.Number,\n  avgCpuPercent: Schema.Number,\n  maxCpuPercent: Schema.Number,\n  cpuSecondsApprox: Schema.Number,\n  currentRssBytes: NonNegativeInt,\n  maxRssBytes: NonNegativeInt,\n  sampleCount: NonNegativeInt,\n});\nexport type ServerProcessResourceHistorySummary = typeof ServerProcessResourceHistorySummary.Type;\n\nexport const ServerProcessResourceHistoryFailureTag = Schema.Literals([\n  \"ProcessDiagnosticsQueryTimeoutError\",\n  \"ProcessDiagnosticsQueryFailedError\",\n  \"ProcessDiagnosticsServerProcessSignalError\",\n  \"ProcessDiagnosticsNotDescendantError\",\n  \"ProcessDiagnosticsSignalFailedError\",\n]);\nexport type ServerProcessResourceHistoryFailureTag =\n  typeof ServerProcessResourceHistoryFailureTag.Type;\n\nexport const ServerProcessResourceHistoryResult = Schema.Struct({\n  readAt: Schema.DateTimeUtc,\n  windowMs: NonNegativeInt,\n  bucketMs: NonNegativeInt,\n  sampleIntervalMs: NonNegativeInt,\n  retainedSampleCount: NonNegativeInt,\n  totalCpuSecondsApprox: Schema.Number,\n  buckets: Schema.Array(ServerProcessResourceHistoryBucket),\n  topProcesses: Schema.Array(ServerProcessResourceHistorySummary),\n  error: Schema.Option(\n    Schema.Struct({\n      failureTag: ServerProcessResourceHistoryFailureTag,\n      message: TrimmedNonEmptyString,\n    }),\n  ),\n});\nexport type ServerProcessResourceHistoryResult = typeof ServerProcessResourceHistoryResult.Type;\n\nexport const ServerSignalProcessInput = Schema.Struct({\n  pid: PositiveInt,\n  startTimeMs: NonNegativeInt,\n  signal: ServerProcessSignal,\n});\nexport type ServerSignalProcessInput = typeof ServerSignalProcessInput.Type;\n\nexport const ServerSignalProcessResult = Schema.Struct({\n  pid: PositiveInt,\n  signal: ServerProcessSignal,\n  signaled: Schema.Boolean,\n  message: Schema.Option(TrimmedNonEmptyString),\n});\nexport type ServerSignalProcessResult = typeof ServerSignalProcessResult.Type;\n\nexport const ServerConfig = Schema.Struct({\n  environment: ExecutionEnvironmentDescriptor,\n  auth: ServerAuthDescriptor,\n  cwd: TrimmedNonEmptyString,\n  keybindingsConfigPath: TrimmedNonEmptyString,\n  keybindings: ResolvedKeybindingsConfig,\n  issues: ServerConfigIssues,\n  providers: ServerProviders,\n  // Editor ids grow over time; drop ones this build does not know rather than\n  // failing the whole config decode.\n  availableEditors: ForwardCompatibleArray(EditorId),\n  observability: ServerObservability,\n  settings: ServerSettings,\n  /** Whether shell subscriptions can emit an opt-in catch-up completion marker. */\n  shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),\n  /** Whether thread subscriptions can emit an opt-in catch-up completion marker. */\n  threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),\n  /**\n   * Whether thread detail reads accept a turn window (`turnLimit`/\n   * `beforeCursor`) and return `page` metadata. Clients must not send window\n   * fields to servers that don't advertise this.\n   */\n  threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),\n});\nexport type ServerConfig = typeof ServerConfig.Type;\n\nconst ServerUpsertKeybindingReplaceTarget = Schema.Struct({\n  key: KeybindingValue,\n  command: KeybindingCommand,\n  when: Schema.optional(KeybindingWhen),\n});\n\nexport const ServerUpsertKeybindingInput = Schema.Struct({\n  key: KeybindingValue,\n  command: KeybindingCommand,\n  when: Schema.optional(KeybindingWhen),\n  replace: Schema.optional(ServerUpsertKeybindingReplaceTarget),\n});\nexport type ServerUpsertKeybindingInput = typeof ServerUpsertKeybindingInput.Type;\n\nexport const ServerRemoveKeybindingInput = ServerUpsertKeybindingReplaceTarget;\nexport type ServerRemoveKeybindingInput = typeof ServerRemoveKeybindingInput.Type;\n\nexport const ServerUpsertKeybindingResult = Schema.Struct({\n  keybindings: ResolvedKeybindingsConfig,\n  issues: ServerConfigIssues,\n});\nexport type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.Type;\n\nexport const ServerRemoveKeybindingResult = ServerUpsertKeybindingResult;\nexport type ServerRemoveKeybindingResult = typeof ServerRemoveKeybindingResult.Type;\n\nexport const ServerConfigUpdatedPayload = Schema.Struct({\n  issues: ServerConfigIssues,\n  providers: ServerProviders,\n  settings: Schema.optional(ServerSettings),\n});\nexport type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;\n\nexport const ServerConfigKeybindingsUpdatedPayload = Schema.Struct({\n  keybindings: ResolvedKeybindingsConfig,\n  issues: ServerConfigIssues,\n});\nexport type ServerConfigKeybindingsUpdatedPayload =\n  typeof ServerConfigKeybindingsUpdatedPayload.Type;\n\nexport const ServerConfigProviderStatusesPayload = Schema.Struct({\n  providers: ServerProviders,\n});\nexport type ServerConfigProviderStatusesPayload = typeof ServerConfigProviderStatusesPayload.Type;\n\nexport const ServerConfigSettingsUpdatedPayload = Schema.Struct({\n  settings: ServerSettings,\n});\nexport type ServerConfigSettingsUpdatedPayload = typeof ServerConfigSettingsUpdatedPayload.Type;\n\nexport const ServerConfigStreamSnapshotEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"snapshot\"),\n  config: ServerConfig,\n});\nexport type ServerConfigStreamSnapshotEvent = typeof ServerConfigStreamSnapshotEvent.Type;\n\nexport const ServerConfigStreamKeybindingsUpdatedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"keybindingsUpdated\"),\n  payload: ServerConfigKeybindingsUpdatedPayload,\n});\nexport type ServerConfigStreamKeybindingsUpdatedEvent =\n  typeof ServerConfigStreamKeybindingsUpdatedEvent.Type;\n\nexport const ServerConfigStreamProviderStatusesEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"providerStatuses\"),\n  payload: ServerConfigProviderStatusesPayload,\n});\nexport type ServerConfigStreamProviderStatusesEvent =\n  typeof ServerConfigStreamProviderStatusesEvent.Type;\n\nexport const ServerConfigStreamSettingsUpdatedEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"settingsUpdated\"),\n  payload: ServerConfigSettingsUpdatedPayload,\n});\nexport type ServerConfigStreamSettingsUpdatedEvent =\n  typeof ServerConfigStreamSettingsUpdatedEvent.Type;\n\nexport const ServerConfigStreamEvent = Schema.Union([\n  ServerConfigStreamSnapshotEvent,\n  ServerConfigStreamKeybindingsUpdatedEvent,\n  ServerConfigStreamProviderStatusesEvent,\n  ServerConfigStreamSettingsUpdatedEvent,\n]);\nexport type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;\n\n/** Terminal selection recorded by the service launcher for one update. */\nexport const ServerSelfUpdateOutcome = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  fromVersion: TrimmedNonEmptyString,\n  targetVersion: TrimmedNonEmptyString,\n  status: Schema.Literals([\"committed\", \"rolled-back\", \"failed\"]),\n  reason: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type ServerSelfUpdateOutcome = typeof ServerSelfUpdateOutcome.Type;\n\nexport const ServerLifecycleReadyPayload = Schema.Struct({\n  at: IsoDateTime,\n  environment: ExecutionEnvironmentDescriptor,\n  /** Present when this process resumed a launcher-managed update. */\n  updateOutcome: Schema.optionalKey(ServerSelfUpdateOutcome),\n});\nexport type ServerLifecycleReadyPayload = typeof ServerLifecycleReadyPayload.Type;\n\nexport const ServerLifecycleWelcomePayload = Schema.Struct({\n  environment: ExecutionEnvironmentDescriptor,\n  cwd: TrimmedNonEmptyString,\n  projectName: TrimmedNonEmptyString,\n  bootstrapProjectId: Schema.optional(ProjectId),\n  bootstrapThreadId: Schema.optional(ThreadId),\n});\nexport type ServerLifecycleWelcomePayload = typeof ServerLifecycleWelcomePayload.Type;\n\nexport const ServerLifecycleStreamWelcomeEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  sequence: NonNegativeInt,\n  type: Schema.Literal(\"welcome\"),\n  payload: ServerLifecycleWelcomePayload,\n});\nexport type ServerLifecycleStreamWelcomeEvent = typeof ServerLifecycleStreamWelcomeEvent.Type;\n\nexport const ServerLifecycleStreamReadyEvent = Schema.Struct({\n  version: Schema.Literal(1),\n  sequence: NonNegativeInt,\n  type: Schema.Literal(\"ready\"),\n  payload: ServerLifecycleReadyPayload,\n});\nexport type ServerLifecycleStreamReadyEvent = typeof ServerLifecycleStreamReadyEvent.Type;\n\nexport const ServerLifecycleStreamEvent = Schema.Union([\n  ServerLifecycleStreamWelcomeEvent,\n  ServerLifecycleStreamReadyEvent,\n]);\nexport type ServerLifecycleStreamEvent = typeof ServerLifecycleStreamEvent.Type;\n\nexport const ServerProviderUpdatedPayload = Schema.Struct({\n  providers: ServerProviders,\n});\nexport type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;\n\nexport const ServerProviderUpdateInput = Schema.Struct({\n  provider: ProviderDriverKind,\n  instanceId: Schema.optionalKey(ProviderInstanceId),\n});\nexport type ServerProviderUpdateInput = typeof ServerProviderUpdateInput.Type;\n\nexport class ServerProviderUpdateError extends Schema.TaggedErrorClass<ServerProviderUpdateError>()(\n  \"ServerProviderUpdateError\",\n  {\n    provider: ProviderDriverKind,\n    reason: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider update failed for ${this.provider}: ${this.reason}`;\n  }\n}\n\nexport const ServerSelfUpdateInput = Schema.Struct({\n  /** Exact npm version of the `@dmccore/code` package to install (never a dist-tag, so\n      the server and the acknowledging client agree on what was requested). */\n  targetVersion: TrimmedNonEmptyString,\n});\nexport type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;\n\n/** Acknowledgement that the update artifact is installed and the server is\n    about to restart into it — the connection will drop moments later. */\nexport const ServerSelfUpdateResult = Schema.Struct({\n  targetVersion: TrimmedNonEmptyString,\n  method: ServerSelfUpdateMethod,\n  /** Launcher-generated correlation ID. Absent when talking to older servers. */\n  updateId: Schema.optionalKey(TrimmedNonEmptyString),\n});\nexport type ServerSelfUpdateResult = typeof ServerSelfUpdateResult.Type;\n\nexport const ServerSelfUpdateProgressStage = Schema.Literals([\"downloading\", \"installing\"]);\nexport type ServerSelfUpdateProgressStage = typeof ServerSelfUpdateProgressStage.Type;\n\nexport const ServerSelfUpdateProgressEvent = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"progress\"),\n    stage: ServerSelfUpdateProgressStage,\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"complete\"),\n    result: ServerSelfUpdateResult,\n  }),\n]);\nexport type ServerSelfUpdateProgressEvent = typeof ServerSelfUpdateProgressEvent.Type;\n\nexport class ServerSelfUpdateError extends Schema.TaggedErrorClass<ServerSelfUpdateError>()(\n  \"ServerSelfUpdateError\",\n  {\n    reason: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Server update failed: ${this.reason}`;\n  }\n}\n","import * as Schema from \"effect/Schema\";\nimport { NonNegativeInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nexport const VcsDriverKind = Schema.Literals([\"git\", \"jj\", \"unknown\"]);\nexport type VcsDriverKind = typeof VcsDriverKind.Type;\n\nexport const VcsFreshnessSource = Schema.Literals([\n  \"live-local\",\n  \"cached-local\",\n  \"cached-remote\",\n  \"explicit-remote\",\n]);\nexport type VcsFreshnessSource = typeof VcsFreshnessSource.Type;\n\nexport const VcsFreshness = Schema.Struct({\n  source: VcsFreshnessSource,\n  observedAt: Schema.DateTimeUtc,\n  expiresAt: Schema.Option(Schema.DateTimeUtc),\n});\nexport type VcsFreshness = typeof VcsFreshness.Type;\n\nexport const VcsDriverCapabilities = Schema.Struct({\n  kind: VcsDriverKind,\n  supportsWorktrees: Schema.Boolean,\n  supportsBookmarks: Schema.Boolean,\n  supportsAtomicSnapshot: Schema.Boolean,\n  supportsPushDefaultRemote: Schema.Boolean,\n  ignoreClassifier: Schema.Literals([\"native\", \"git-compatible-fallback\"]),\n});\nexport type VcsDriverCapabilities = typeof VcsDriverCapabilities.Type;\n\nexport const VcsRepositoryIdentity = Schema.Struct({\n  kind: VcsDriverKind,\n  rootPath: TrimmedNonEmptyString,\n  metadataPath: Schema.NullOr(TrimmedNonEmptyString),\n  freshness: VcsFreshness,\n});\nexport type VcsRepositoryIdentity = typeof VcsRepositoryIdentity.Type;\n\nexport const VcsListWorkspaceFilesResult = Schema.Struct({\n  paths: Schema.Array(TrimmedNonEmptyString),\n  truncated: Schema.Boolean,\n  freshness: VcsFreshness,\n});\nexport type VcsListWorkspaceFilesResult = typeof VcsListWorkspaceFilesResult.Type;\n\nexport const VcsRemote = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  url: TrimmedNonEmptyString,\n  pushUrl: Schema.Option(TrimmedNonEmptyString),\n  isPrimary: Schema.Boolean,\n});\nexport type VcsRemote = typeof VcsRemote.Type;\n\nexport const VcsListRemotesResult = Schema.Struct({\n  remotes: Schema.Array(VcsRemote),\n  freshness: VcsFreshness,\n});\nexport type VcsListRemotesResult = typeof VcsListRemotesResult.Type;\n\nexport interface VcsProcessErrorContext {\n  readonly operation: string;\n  readonly command: string;\n  readonly cwd: string;\n  readonly argumentCount?: number;\n}\n\nexport interface VcsProcessSpawnFailure {\n  readonly cause: unknown;\n}\n\nexport interface VcsProcessTimeoutFailure {\n  readonly timeoutMs: number;\n}\n\nexport const VcsProcessExitFailureKind = Schema.Literals([\n  \"authentication\",\n  \"not-found\",\n  \"command-failed\",\n]);\nexport type VcsProcessExitFailureKind = typeof VcsProcessExitFailureKind.Type;\n\nexport interface VcsProcessExitFailure {\n  readonly exitCode: number;\n  readonly stderr: string;\n  readonly stderrTruncated: boolean;\n}\n\nexport class VcsProcessSpawnError extends Schema.TaggedErrorClass<VcsProcessSpawnError>()(\n  \"VcsProcessSpawnError\",\n  {\n    operation: Schema.String,\n    command: Schema.String,\n    cwd: Schema.String,\n    argumentCount: Schema.optional(NonNegativeInt),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `VCS process failed to spawn in ${this.operation}: ${this.command} (${this.cwd})`;\n  }\n\n  static fromProcessSpawnError(context: VcsProcessErrorContext, error: VcsProcessSpawnFailure) {\n    return new VcsProcessSpawnError({\n      ...context,\n      cause: error.cause,\n    });\n  }\n}\n\nexport class VcsProcessExitError extends Schema.TaggedErrorClass<VcsProcessExitError>()(\n  \"VcsProcessExitError\",\n  {\n    operation: Schema.String,\n    command: Schema.String,\n    cwd: Schema.String,\n    argumentCount: Schema.optional(NonNegativeInt),\n    exitCode: Schema.Number,\n    detail: Schema.String,\n    failureKind: Schema.optional(VcsProcessExitFailureKind),\n    stderrLength: Schema.optional(NonNegativeInt),\n    stderrTruncated: Schema.optional(Schema.Boolean),\n  },\n) {\n  override get message(): string {\n    return `VCS process failed in ${this.operation}: ${this.command} (${this.cwd}) exited with ${this.exitCode} - ${this.detail}`;\n  }\n\n  static fromProcessExit(\n    context: VcsProcessErrorContext,\n    error: VcsProcessExitFailure,\n    failureKind: VcsProcessExitFailureKind,\n  ) {\n    const detail =\n      failureKind === \"authentication\"\n        ? \"Authentication failed.\"\n        : failureKind === \"not-found\"\n          ? context.command === \"glab\"\n            ? \"Merge request not found.\"\n            : context.command === \"gh\" || context.command === \"az\"\n              ? \"Pull request not found.\"\n              : \"VCS resource not found.\"\n          : \"Process exited with a non-zero status.\";\n\n    return new VcsProcessExitError({\n      ...context,\n      exitCode: error.exitCode,\n      detail,\n      failureKind,\n      stderrLength: error.stderr.length,\n      stderrTruncated: error.stderrTruncated,\n    });\n  }\n}\n\nexport class VcsProcessTimeoutError extends Schema.TaggedErrorClass<VcsProcessTimeoutError>()(\n  \"VcsProcessTimeoutError\",\n  {\n    operation: Schema.String,\n    command: Schema.String,\n    cwd: Schema.String,\n    argumentCount: Schema.optional(NonNegativeInt),\n    timeoutMs: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `VCS process timed out in ${this.operation}: ${this.command} (${this.cwd}) after ${this.timeoutMs}ms`;\n  }\n\n  static fromProcessTimeoutError(context: VcsProcessErrorContext, error: VcsProcessTimeoutFailure) {\n    return new VcsProcessTimeoutError({\n      ...context,\n      timeoutMs: error.timeoutMs,\n    });\n  }\n}\n\nconst VcsProcessBoundaryErrorFields = {\n  operation: Schema.String,\n  command: Schema.String,\n  cwd: Schema.String,\n  argumentCount: Schema.optional(NonNegativeInt),\n};\n\nexport class VcsProcessStdinWriteError extends Schema.TaggedErrorClass<VcsProcessStdinWriteError>()(\n  \"VcsProcessStdinWriteError\",\n  {\n    ...VcsProcessBoundaryErrorFields,\n    stdinBytes: NonNegativeInt,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `VCS process failed to write ${this.stdinBytes} bytes to stdin in ${this.operation}: ${this.command} (${this.cwd})`;\n  }\n}\n\nexport class VcsProcessOutputReadError extends Schema.TaggedErrorClass<VcsProcessOutputReadError>()(\n  \"VcsProcessOutputReadError\",\n  {\n    ...VcsProcessBoundaryErrorFields,\n    stream: Schema.Literals([\"stdout\", \"stderr\", \"exitCode\"]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `VCS process failed to read ${this.stream} in ${this.operation}: ${this.command} (${this.cwd})`;\n  }\n}\n\nexport class VcsProcessOutputLimitError extends Schema.TaggedErrorClass<VcsProcessOutputLimitError>()(\n  \"VcsProcessOutputLimitError\",\n  {\n    ...VcsProcessBoundaryErrorFields,\n    stream: Schema.Literals([\"stdout\", \"stderr\"]),\n    maxBytes: NonNegativeInt,\n    observedBytes: NonNegativeInt,\n  },\n) {\n  override get message(): string {\n    return `VCS process ${this.stream} produced ${this.observedBytes} bytes in ${this.operation}: ${this.command} (${this.cwd}), exceeding the ${this.maxBytes} byte limit`;\n  }\n}\n\nexport class VcsProcessMissingExitCodeError extends Schema.TaggedErrorClass<VcsProcessMissingExitCodeError>()(\n  \"VcsProcessMissingExitCodeError\",\n  VcsProcessBoundaryErrorFields,\n) {\n  override get message(): string {\n    return `VCS process completed without an exit code in ${this.operation}: ${this.command} (${this.cwd})`;\n  }\n}\n\nexport const VcsOutputDecodeError = Schema.Union([\n  VcsProcessStdinWriteError,\n  VcsProcessOutputReadError,\n  VcsProcessOutputLimitError,\n  VcsProcessMissingExitCodeError,\n]);\nexport type VcsOutputDecodeError = typeof VcsOutputDecodeError.Type;\n\nexport class VcsRepositoryDetectionError extends Schema.TaggedErrorClass<VcsRepositoryDetectionError>()(\n  \"VcsRepositoryDetectionError\",\n  {\n    operation: Schema.String,\n    cwd: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `VCS repository detection failed in ${this.operation}: ${this.cwd} - ${this.detail}`;\n  }\n}\n\nexport class VcsUnsupportedOperationError extends Schema.TaggedErrorClass<VcsUnsupportedOperationError>()(\n  \"VcsUnsupportedOperationError\",\n  {\n    operation: Schema.String,\n    kind: VcsDriverKind,\n    detail: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `VCS operation is unsupported for ${this.kind} in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport const VcsError = Schema.Union([\n  VcsProcessSpawnError,\n  VcsProcessExitError,\n  VcsProcessTimeoutError,\n  VcsProcessStdinWriteError,\n  VcsProcessOutputReadError,\n  VcsProcessOutputLimitError,\n  VcsProcessMissingExitCodeError,\n  VcsRepositoryDetectionError,\n  VcsUnsupportedOperationError,\n]);\nexport type VcsError = typeof VcsError.Type;\n","import * as Schema from \"effect/Schema\";\nimport { PositiveInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { VcsDriverKind } from \"./vcs.ts\";\n\nexport const SourceControlProviderKind = Schema.Literals([\n  \"github\",\n  \"gitlab\",\n  \"azure-devops\",\n  \"bitbucket\",\n  \"unknown\",\n]);\nexport type SourceControlProviderKind = typeof SourceControlProviderKind.Type;\n\nexport const SourceControlProviderInfo = Schema.Struct({\n  kind: SourceControlProviderKind,\n  name: TrimmedNonEmptyString,\n  baseUrl: Schema.String,\n});\nexport type SourceControlProviderInfo = typeof SourceControlProviderInfo.Type;\n\nexport const ChangeRequestState = Schema.Literals([\"open\", \"closed\", \"merged\"]);\nexport type ChangeRequestState = typeof ChangeRequestState.Type;\n\nexport const ChangeRequest = Schema.Struct({\n  provider: SourceControlProviderKind,\n  number: PositiveInt,\n  title: TrimmedNonEmptyString,\n  url: Schema.String,\n  baseRefName: TrimmedNonEmptyString,\n  headRefName: TrimmedNonEmptyString,\n  state: ChangeRequestState,\n  updatedAt: Schema.Option(Schema.DateTimeUtc),\n  isCrossRepository: Schema.optional(Schema.Boolean),\n  headRepositoryNameWithOwner: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  headRepositoryOwnerLogin: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n});\nexport type ChangeRequest = typeof ChangeRequest.Type;\n\nexport const SourceControlRepositoryCloneUrls = Schema.Struct({\n  nameWithOwner: TrimmedNonEmptyString,\n  url: TrimmedNonEmptyString,\n  sshUrl: TrimmedNonEmptyString,\n});\nexport type SourceControlRepositoryCloneUrls = typeof SourceControlRepositoryCloneUrls.Type;\n\nexport const SourceControlRepositoryVisibility = Schema.Literals([\"private\", \"public\"]);\nexport type SourceControlRepositoryVisibility = typeof SourceControlRepositoryVisibility.Type;\n\nexport const SourceControlCloneProtocol = Schema.Literals([\"auto\", \"ssh\", \"https\"]);\nexport type SourceControlCloneProtocol = typeof SourceControlCloneProtocol.Type;\n\nexport const SourceControlRepositoryInfo = Schema.Struct({\n  provider: SourceControlProviderKind,\n  nameWithOwner: TrimmedNonEmptyString,\n  url: TrimmedNonEmptyString,\n  sshUrl: TrimmedNonEmptyString,\n});\nexport type SourceControlRepositoryInfo = typeof SourceControlRepositoryInfo.Type;\n\nexport const SourceControlRepositoryLookupInput = Schema.Struct({\n  provider: SourceControlProviderKind,\n  repository: TrimmedNonEmptyString,\n  cwd: Schema.optional(TrimmedNonEmptyString),\n});\nexport type SourceControlRepositoryLookupInput = typeof SourceControlRepositoryLookupInput.Type;\n\nexport const SourceControlCloneRepositoryInput = Schema.Struct({\n  provider: Schema.optional(SourceControlProviderKind),\n  repository: Schema.optional(TrimmedNonEmptyString),\n  remoteUrl: Schema.optional(TrimmedNonEmptyString),\n  destinationPath: TrimmedNonEmptyString,\n  protocol: Schema.optional(SourceControlCloneProtocol),\n});\nexport type SourceControlCloneRepositoryInput = typeof SourceControlCloneRepositoryInput.Type;\n\nexport const SourceControlCloneRepositoryResult = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  remoteUrl: TrimmedNonEmptyString,\n  repository: Schema.NullOr(SourceControlRepositoryInfo),\n});\nexport type SourceControlCloneRepositoryResult = typeof SourceControlCloneRepositoryResult.Type;\n\nexport const SourceControlPublishRepositoryInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  provider: SourceControlProviderKind,\n  repository: TrimmedNonEmptyString,\n  visibility: SourceControlRepositoryVisibility,\n  remoteName: Schema.optional(TrimmedNonEmptyString),\n  protocol: Schema.optional(SourceControlCloneProtocol),\n});\nexport type SourceControlPublishRepositoryInput = typeof SourceControlPublishRepositoryInput.Type;\n\nexport const SourceControlPublishStatus = Schema.Literals([\"pushed\", \"remote_added\"]);\nexport type SourceControlPublishStatus = typeof SourceControlPublishStatus.Type;\n\nexport const SourceControlPublishRepositoryResult = Schema.Struct({\n  repository: SourceControlRepositoryInfo,\n  remoteName: TrimmedNonEmptyString,\n  remoteUrl: TrimmedNonEmptyString,\n  branch: TrimmedNonEmptyString,\n  upstreamBranch: Schema.optional(TrimmedNonEmptyString),\n  status: SourceControlPublishStatus,\n});\nexport type SourceControlPublishRepositoryResult = typeof SourceControlPublishRepositoryResult.Type;\n\nexport const SourceControlDiscoveryStatus = Schema.Literals([\"available\", \"missing\"]);\nexport type SourceControlDiscoveryStatus = typeof SourceControlDiscoveryStatus.Type;\n\nexport const SourceControlProviderAuthStatus = Schema.Literals([\n  \"authenticated\",\n  \"unauthenticated\",\n  \"unknown\",\n]);\nexport type SourceControlProviderAuthStatus = typeof SourceControlProviderAuthStatus.Type;\n\nexport const SourceControlProviderAuth = Schema.Struct({\n  status: SourceControlProviderAuthStatus,\n  account: Schema.Option(TrimmedNonEmptyString),\n  host: Schema.Option(TrimmedNonEmptyString),\n  detail: Schema.Option(TrimmedNonEmptyString),\n});\nexport type SourceControlProviderAuth = typeof SourceControlProviderAuth.Type;\n\nconst SourceControlDiscoverySharedFields = {\n  label: TrimmedNonEmptyString,\n  executable: Schema.optional(TrimmedNonEmptyString),\n  status: SourceControlDiscoveryStatus,\n  version: Schema.Option(TrimmedNonEmptyString),\n  installHint: TrimmedNonEmptyString,\n  detail: Schema.Option(TrimmedNonEmptyString),\n} as const;\n\nexport const VcsDiscoveryItem = Schema.Struct({\n  kind: VcsDriverKind,\n  implemented: Schema.Boolean,\n  ...SourceControlDiscoverySharedFields,\n});\nexport type VcsDiscoveryItem = typeof VcsDiscoveryItem.Type;\n\nexport const SourceControlProviderDiscoveryItem = Schema.Struct({\n  kind: SourceControlProviderKind,\n  ...SourceControlDiscoverySharedFields,\n  auth: SourceControlProviderAuth,\n});\nexport type SourceControlProviderDiscoveryItem = typeof SourceControlProviderDiscoveryItem.Type;\n\nexport const SourceControlDiscoveryResult = Schema.Struct({\n  versionControlSystems: Schema.Array(VcsDiscoveryItem),\n  sourceControlProviders: Schema.Array(SourceControlProviderDiscoveryItem),\n});\nexport type SourceControlDiscoveryResult = typeof SourceControlDiscoveryResult.Type;\n\nexport class SourceControlProviderError extends Schema.TaggedErrorClass<SourceControlProviderError>()(\n  \"SourceControlProviderError\",\n  {\n    provider: SourceControlProviderKind,\n    operation: Schema.String,\n    cwd: Schema.String,\n    command: Schema.optional(Schema.String),\n    repository: Schema.optional(Schema.String),\n    reference: Schema.optional(Schema.String),\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Source control provider ${this.provider} failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class SourceControlRepositoryError extends Schema.TaggedErrorClass<SourceControlRepositoryError>()(\n  \"SourceControlRepositoryError\",\n  {\n    provider: SourceControlProviderKind,\n    operation: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Source control repository operation ${this.operation} failed for ${this.provider}: ${this.detail}`;\n  }\n}\n","import * as Schema from \"effect/Schema\";\nimport { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { SourceControlProviderError, SourceControlProviderInfo } from \"./sourceControl.ts\";\nimport { VcsDriverKind } from \"./vcs.ts\";\n\nconst TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;\nconst GIT_LIST_BRANCHES_MAX_LIMIT = 200;\n\n// Domain Types\n\nexport const GitStackedAction = Schema.Literals([\n  \"commit\",\n  \"push\",\n  \"create_pr\",\n  \"commit_push\",\n  \"commit_push_pr\",\n]);\nexport type GitStackedAction = typeof GitStackedAction.Type;\nexport const GitActionProgressPhase = Schema.Literals([\"branch\", \"commit\", \"push\", \"pr\"]);\nexport type GitActionProgressPhase = typeof GitActionProgressPhase.Type;\nexport const GitActionProgressKind = Schema.Literals([\n  \"action_started\",\n  \"phase_started\",\n  \"hook_started\",\n  \"hook_output\",\n  \"hook_finished\",\n  \"action_finished\",\n  \"action_failed\",\n]);\nexport type GitActionProgressKind = typeof GitActionProgressKind.Type;\nexport const GitActionProgressStream = Schema.Literals([\"stdout\", \"stderr\"]);\nexport type GitActionProgressStream = typeof GitActionProgressStream.Type;\nconst GitCommitStepStatus = Schema.Literals([\n  \"created\",\n  \"skipped_no_changes\",\n  \"skipped_not_requested\",\n]);\nconst GitPushStepStatus = Schema.Literals([\n  \"pushed\",\n  \"skipped_not_requested\",\n  \"skipped_up_to_date\",\n]);\nconst GitBranchStepStatus = Schema.Literals([\"created\", \"skipped_not_requested\"]);\nconst GitPrStepStatus = Schema.Literals([\"created\", \"opened_existing\", \"skipped_not_requested\"]);\nconst VcsStatusChangeRequestState = Schema.Literals([\"open\", \"closed\", \"merged\"]);\nconst GitPullRequestReference = TrimmedNonEmptyStringSchema;\nconst GitPullRequestState = Schema.Literals([\"open\", \"closed\", \"merged\"]);\nconst GitPreparePullRequestThreadMode = Schema.Literals([\"local\", \"worktree\"]);\nexport const GitRunStackedActionToastRunAction = Schema.Struct({\n  kind: GitStackedAction,\n});\nexport type GitRunStackedActionToastRunAction = typeof GitRunStackedActionToastRunAction.Type;\nconst GitRunStackedActionToastCta = Schema.Union([\n  Schema.Struct({\n    kind: Schema.Literal(\"none\"),\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"open_pr\"),\n    label: TrimmedNonEmptyStringSchema,\n    url: Schema.String,\n  }),\n  Schema.Struct({\n    kind: Schema.Literal(\"run_action\"),\n    label: TrimmedNonEmptyStringSchema,\n    action: GitRunStackedActionToastRunAction,\n  }),\n]);\nexport type GitRunStackedActionToastCta = typeof GitRunStackedActionToastCta.Type;\nconst GitRunStackedActionToast = Schema.Struct({\n  title: TrimmedNonEmptyStringSchema,\n  description: Schema.optional(TrimmedNonEmptyStringSchema),\n  cta: GitRunStackedActionToastCta,\n});\nexport type GitRunStackedActionToast = typeof GitRunStackedActionToast.Type;\n\nexport const VcsRef = Schema.Struct({\n  name: TrimmedNonEmptyStringSchema,\n  isRemote: Schema.optional(Schema.Boolean),\n  remoteName: Schema.optional(TrimmedNonEmptyStringSchema),\n  current: Schema.Boolean,\n  isDefault: Schema.Boolean,\n  worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),\n});\nexport type VcsRef = typeof VcsRef.Type;\n\nconst VcsWorktree = Schema.Struct({\n  path: TrimmedNonEmptyStringSchema,\n  refName: TrimmedNonEmptyStringSchema,\n});\nconst GitResolvedPullRequest = Schema.Struct({\n  number: PositiveInt,\n  title: TrimmedNonEmptyStringSchema,\n  url: Schema.String,\n  baseBranch: TrimmedNonEmptyStringSchema,\n  headBranch: TrimmedNonEmptyStringSchema,\n  state: GitPullRequestState,\n});\nexport type GitResolvedPullRequest = typeof GitResolvedPullRequest.Type;\n\n// RPC Inputs\n\nexport const VcsStatusInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n});\nexport type VcsStatusInput = typeof VcsStatusInput.Type;\n\nexport const VcsPullInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n});\nexport type VcsPullInput = typeof VcsPullInput.Type;\n\nexport const GitRunStackedActionInput = Schema.Struct({\n  actionId: TrimmedNonEmptyStringSchema,\n  cwd: TrimmedNonEmptyStringSchema,\n  action: GitStackedAction,\n  commitMessage: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(10_000))),\n  featureBranch: Schema.optional(Schema.Boolean),\n  filePaths: Schema.optional(\n    Schema.Array(TrimmedNonEmptyStringSchema).check(Schema.isMinLength(1)),\n  ),\n});\nexport type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;\n\nexport const VcsListRefsInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  query: Schema.optional(TrimmedNonEmptyStringSchema.check(Schema.isMaxLength(256))),\n  cursor: Schema.optional(NonNegativeInt),\n  includeMatchingRemoteRefs: Schema.optional(Schema.Boolean),\n  refKind: Schema.optional(Schema.Literals([\"all\", \"local\", \"remote\"])),\n  refresh: Schema.optional(Schema.Boolean),\n  limit: Schema.optional(\n    PositiveInt.check(Schema.isLessThanOrEqualTo(GIT_LIST_BRANCHES_MAX_LIMIT)),\n  ),\n});\nexport type VcsListRefsInput = typeof VcsListRefsInput.Type;\n\nexport const VcsCreateWorktreeInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  refName: TrimmedNonEmptyStringSchema,\n  newRefName: Schema.optional(TrimmedNonEmptyStringSchema),\n  baseRefName: Schema.optional(TrimmedNonEmptyStringSchema),\n  path: Schema.NullOr(TrimmedNonEmptyStringSchema),\n});\nexport type VcsCreateWorktreeInput = typeof VcsCreateWorktreeInput.Type;\n\nexport const GitPullRequestRefInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  reference: GitPullRequestReference,\n});\nexport type GitPullRequestRefInput = typeof GitPullRequestRefInput.Type;\n\nexport const GitPreparePullRequestThreadInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  reference: GitPullRequestReference,\n  mode: GitPreparePullRequestThreadMode,\n  threadId: Schema.optional(ThreadId),\n});\nexport type GitPreparePullRequestThreadInput = typeof GitPreparePullRequestThreadInput.Type;\n\nexport const VcsRemoveWorktreeInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  path: TrimmedNonEmptyStringSchema,\n  force: Schema.optional(Schema.Boolean),\n});\nexport type VcsRemoveWorktreeInput = typeof VcsRemoveWorktreeInput.Type;\n\nexport const VcsCreateRefInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  refName: TrimmedNonEmptyStringSchema,\n  switchRef: Schema.optional(Schema.Boolean),\n});\nexport type VcsCreateRefInput = typeof VcsCreateRefInput.Type;\n\nexport const VcsCreateRefResult = Schema.Struct({\n  refName: TrimmedNonEmptyStringSchema,\n});\nexport type VcsCreateRefResult = typeof VcsCreateRefResult.Type;\n\nexport const VcsSwitchRefInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  refName: TrimmedNonEmptyStringSchema,\n});\nexport type VcsSwitchRefInput = typeof VcsSwitchRefInput.Type;\n\nexport const VcsInitInput = Schema.Struct({\n  cwd: TrimmedNonEmptyStringSchema,\n  kind: Schema.optional(VcsDriverKind),\n});\nexport type VcsInitInput = typeof VcsInitInput.Type;\n\n// RPC Results\n\nconst VcsStatusChangeRequest = Schema.Struct({\n  number: PositiveInt,\n  title: TrimmedNonEmptyStringSchema,\n  url: Schema.String,\n  baseRef: TrimmedNonEmptyStringSchema,\n  headRef: TrimmedNonEmptyStringSchema,\n  state: VcsStatusChangeRequestState,\n});\n\nconst VcsStatusLocalShape = {\n  isRepo: Schema.Boolean,\n  sourceControlProvider: Schema.optional(SourceControlProviderInfo),\n  hasPrimaryRemote: Schema.Boolean,\n  isDefaultRef: Schema.Boolean,\n  refName: Schema.NullOr(TrimmedNonEmptyStringSchema),\n  hasWorkingTreeChanges: Schema.Boolean,\n  workingTree: Schema.Struct({\n    files: Schema.Array(\n      Schema.Struct({\n        path: TrimmedNonEmptyStringSchema,\n        insertions: NonNegativeInt,\n        deletions: NonNegativeInt,\n      }),\n    ),\n    insertions: NonNegativeInt,\n    deletions: NonNegativeInt,\n  }),\n};\n\nconst VcsStatusRemoteShape = {\n  hasUpstream: Schema.Boolean,\n  aheadCount: NonNegativeInt,\n  behindCount: NonNegativeInt,\n  aheadOfDefaultCount: Schema.optional(NonNegativeInt),\n  pr: Schema.NullOr(VcsStatusChangeRequest),\n};\n\nexport const VcsStatusLocalResult = Schema.Struct(VcsStatusLocalShape);\nexport type VcsStatusLocalResult = typeof VcsStatusLocalResult.Type;\n\nexport const VcsStatusRemoteResult = Schema.Struct(VcsStatusRemoteShape);\nexport type VcsStatusRemoteResult = typeof VcsStatusRemoteResult.Type;\n\nexport const VcsStatusResult = Schema.Struct({\n  ...VcsStatusLocalShape,\n  ...VcsStatusRemoteShape,\n});\nexport type VcsStatusResult = typeof VcsStatusResult.Type;\n\nexport const VcsStatusStreamEvent = Schema.Union([\n  Schema.TaggedStruct(\"snapshot\", {\n    local: VcsStatusLocalResult,\n    remote: Schema.NullOr(VcsStatusRemoteResult),\n  }),\n  Schema.TaggedStruct(\"localUpdated\", {\n    local: VcsStatusLocalResult,\n  }),\n  Schema.TaggedStruct(\"remoteUpdated\", {\n    remote: Schema.NullOr(VcsStatusRemoteResult),\n  }),\n]);\nexport type VcsStatusStreamEvent = typeof VcsStatusStreamEvent.Type;\n\nexport const VcsListRefsResult = Schema.Struct({\n  refs: Schema.Array(VcsRef),\n  isRepo: Schema.Boolean,\n  hasPrimaryRemote: Schema.Boolean,\n  nextCursor: NonNegativeInt.pipe(Schema.NullOr),\n  totalCount: NonNegativeInt,\n});\nexport type VcsListRefsResult = typeof VcsListRefsResult.Type;\n\nexport const VcsCreateWorktreeResult = Schema.Struct({\n  worktree: VcsWorktree,\n});\nexport type VcsCreateWorktreeResult = typeof VcsCreateWorktreeResult.Type;\n\nexport const GitResolvePullRequestResult = Schema.Struct({\n  pullRequest: GitResolvedPullRequest,\n});\nexport type GitResolvePullRequestResult = typeof GitResolvePullRequestResult.Type;\n\nexport const GitPreparePullRequestThreadResult = Schema.Struct({\n  pullRequest: GitResolvedPullRequest,\n  branch: TrimmedNonEmptyStringSchema,\n  worktreePath: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),\n});\nexport type GitPreparePullRequestThreadResult = typeof GitPreparePullRequestThreadResult.Type;\n\nexport const VcsSwitchRefResult = Schema.Struct({\n  refName: Schema.NullOr(TrimmedNonEmptyStringSchema),\n});\nexport type VcsSwitchRefResult = typeof VcsSwitchRefResult.Type;\n\nexport const GitRunStackedActionResult = Schema.Struct({\n  action: GitStackedAction,\n  branch: Schema.Struct({\n    status: GitBranchStepStatus,\n    name: Schema.optional(TrimmedNonEmptyStringSchema),\n  }),\n  commit: Schema.Struct({\n    status: GitCommitStepStatus,\n    commitSha: Schema.optional(TrimmedNonEmptyStringSchema),\n    subject: Schema.optional(TrimmedNonEmptyStringSchema),\n  }),\n  push: Schema.Struct({\n    status: GitPushStepStatus,\n    branch: Schema.optional(TrimmedNonEmptyStringSchema),\n    upstreamBranch: Schema.optional(TrimmedNonEmptyStringSchema),\n    setUpstream: Schema.optional(Schema.Boolean),\n  }),\n  pr: Schema.Struct({\n    status: GitPrStepStatus,\n    url: Schema.optional(Schema.String),\n    number: Schema.optional(PositiveInt),\n    baseBranch: Schema.optional(TrimmedNonEmptyStringSchema),\n    headBranch: Schema.optional(TrimmedNonEmptyStringSchema),\n    title: Schema.optional(TrimmedNonEmptyStringSchema),\n  }),\n  toast: GitRunStackedActionToast,\n});\nexport type GitRunStackedActionResult = typeof GitRunStackedActionResult.Type;\n\nexport const VcsPullResult = Schema.Struct({\n  status: Schema.Literals([\"pulled\", \"skipped_up_to_date\"]),\n  refName: TrimmedNonEmptyStringSchema,\n  upstreamRef: TrimmedNonEmptyStringSchema.pipe(Schema.NullOr),\n});\nexport type VcsPullResult = typeof VcsPullResult.Type;\n\n// RPC / domain errors\nexport class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()(\"GitCommandError\", {\n  operation: Schema.String,\n  command: Schema.String,\n  cwd: Schema.String,\n  argumentCount: Schema.optional(Schema.Number),\n  exitCode: Schema.optional(Schema.Number),\n  stdoutLength: Schema.optional(Schema.Number),\n  stderrLength: Schema.optional(Schema.Number),\n  outputLength: Schema.optional(Schema.Number),\n  detail: Schema.String,\n  cause: Schema.optional(Schema.Defect()),\n}) {\n  override get message(): string {\n    return `Git command failed in ${this.operation} (${this.cwd}): ${this.detail}`;\n  }\n}\n\nexport class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(\n  \"TextGenerationError\",\n  {\n    operation: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Text generation failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()(\"GitManagerError\", {\n  operation: Schema.String,\n  cwd: Schema.String,\n  detail: Schema.String,\n  cause: Schema.optional(Schema.Defect()),\n}) {\n  override get message(): string {\n    return `Git manager failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class GitPullRequestMaterializationError extends Schema.TaggedErrorClass<GitPullRequestMaterializationError>()(\n  \"GitPullRequestMaterializationError\",\n  {\n    cwd: TrimmedNonEmptyStringSchema,\n    pullRequestNumber: PositiveInt,\n    headRepository: Schema.NullOr(TrimmedNonEmptyStringSchema),\n    headBranch: TrimmedNonEmptyStringSchema,\n    localBranch: TrimmedNonEmptyStringSchema,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to materialize pull request #${this.pullRequestNumber} branch ${this.headBranch} as ${this.localBranch}.`;\n  }\n}\n\nexport const GitManagerServiceError = Schema.Union([\n  GitManagerError,\n  GitPullRequestMaterializationError,\n  GitCommandError,\n  SourceControlProviderError,\n  TextGenerationError,\n]);\nexport type GitManagerServiceError = typeof GitManagerServiceError.Type;\n\nconst GitActionProgressBase = Schema.Struct({\n  actionId: TrimmedNonEmptyStringSchema,\n  cwd: TrimmedNonEmptyStringSchema,\n  action: GitStackedAction,\n});\n\nconst GitActionStartedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"action_started\"),\n  phases: Schema.Array(GitActionProgressPhase),\n});\nconst GitActionPhaseStartedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"phase_started\"),\n  phase: GitActionProgressPhase,\n  label: TrimmedNonEmptyStringSchema,\n});\nconst GitActionHookStartedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"hook_started\"),\n  hookName: TrimmedNonEmptyStringSchema,\n});\nconst GitActionHookOutputEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"hook_output\"),\n  hookName: Schema.NullOr(TrimmedNonEmptyStringSchema),\n  stream: GitActionProgressStream,\n  text: TrimmedNonEmptyStringSchema,\n});\nconst GitActionHookFinishedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"hook_finished\"),\n  hookName: TrimmedNonEmptyStringSchema,\n  exitCode: Schema.NullOr(Schema.Int),\n  durationMs: Schema.NullOr(NonNegativeInt),\n});\nconst GitActionFinishedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"action_finished\"),\n  result: GitRunStackedActionResult,\n});\nconst GitActionFailedEvent = Schema.Struct({\n  ...GitActionProgressBase.fields,\n  kind: Schema.Literal(\"action_failed\"),\n  phase: Schema.NullOr(GitActionProgressPhase),\n  message: TrimmedNonEmptyStringSchema,\n});\n\nexport const GitActionProgressEvent = Schema.Union([\n  GitActionStartedEvent,\n  GitActionPhaseStartedEvent,\n  GitActionHookStartedEvent,\n  GitActionHookOutputEvent,\n  GitActionHookFinishedEvent,\n  GitActionFinishedEvent,\n  GitActionFailedEvent,\n]);\nexport type GitActionProgressEvent = typeof GitActionProgressEvent.Type;\n","import * as Schema from \"effect/Schema\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\n\nimport { ProjectScriptIcon } from \"./orchestration.ts\";\n\n/** File name of the checked-in Synaptic project file, resolved at the workspace root. */\nexport const SYNAPTIC_PROJECT_FILE_NAME = \"synaptic.json\";\n\n/** Public URL of the published JSON Schema for {@link T3ProjectFile}. */\nexport const SYNAPTIC_PROJECT_FILE_SCHEMA_URL = \"https://code.dmccore.ai/schema/synaptic.json\";\n\nconst SYNAPTIC_PROJECT_FILE_PATH_MAX_LENGTH = 512;\nconst SYNAPTIC_PROJECT_FILE_MAX_SCRIPTS = 50;\n\n// Annotations go on the encoded (string) side so they survive into the\n// published JSON Schema; decoding still trims and re-validates non-emptiness.\nconst trimmedNonEmpty = (annotations: { readonly description: string }, maxLength?: number) => {\n  const annotated = Schema.String.annotate(annotations);\n  const encoded =\n    maxLength === undefined\n      ? annotated.check(Schema.isNonEmpty())\n      : annotated.check(Schema.isNonEmpty(), Schema.isMaxLength(maxLength));\n  return encoded.pipe(Schema.decodeTo(encoded, SchemaTransformation.trim()));\n};\n\nexport const T3ProjectFileScript = Schema.Struct({\n  name: trimmedNonEmpty({\n    description: \"Display name for the script, shown in the Synaptic Code scripts menu.\",\n  }),\n  command: trimmedNonEmpty({\n    description: \"Shell command executed in a Synaptic Code terminal at the project root.\",\n  }),\n  icon: Schema.optionalKey(\n    ProjectScriptIcon.annotate({\n      description: 'Icon shown next to the script in the scripts menu. Defaults to \"play\".',\n    }),\n  ),\n  runOnWorktreeCreate: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, the script runs automatically after a worktree is created for a new thread.\",\n    }),\n  ),\n  previewUrl: Schema.optionalKey(\n    trimmedNonEmpty({\n      description:\n        \"URL opened in the in-app browser preview when this script runs. Only honored on the desktop build.\",\n    }),\n  ),\n  autoOpenPreview: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, automatically open the preview panel at `previewUrl` the moment the script starts.\",\n    }),\n  ),\n}).annotate({\n  description: \"A project script that team members can import into Synaptic Code.\",\n});\nexport type T3ProjectFileScript = typeof T3ProjectFileScript.Type;\n\nexport const T3ProjectFile = Schema.Struct({\n  $schema: Schema.optionalKey(\n    Schema.String.annotate({\n      description: `URL of the JSON Schema for this file, typically \"${SYNAPTIC_PROJECT_FILE_SCHEMA_URL}\".`,\n    }),\n  ),\n  iconPath: Schema.optionalKey(\n    trimmedNonEmpty(\n      {\n        description:\n          'Workspace-relative path to the project icon (e.g. \"assets/logo.svg\"). Checked before Synaptic Code\\'s built-in icon locations.',\n      },\n      SYNAPTIC_PROJECT_FILE_PATH_MAX_LENGTH,\n    ),\n  ),\n  scripts: Schema.optionalKey(\n    Schema.Array(T3ProjectFileScript)\n      .annotate({\n        description:\n          \"Project scripts shared with everyone who opens this repository in Synaptic Code.\",\n      })\n      .check(Schema.isMaxLength(SYNAPTIC_PROJECT_FILE_MAX_SCRIPTS)),\n  ),\n}).annotate({\n  title: \"Synaptic project file\",\n  description:\n    \"Checked-in project configuration read by Synaptic Code (synaptic.json at the repository root). See https://code.dmccore.ai for documentation.\",\n});\nexport type T3ProjectFile = typeof T3ProjectFile.Type;\n","import * as Schema from \"effect/Schema\";\nimport {\n  NonNegativeInt,\n  PositiveInt,\n  TrimmedNonEmptyString,\n  TrimmedString,\n} from \"./baseSchemas.ts\";\n\nconst PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;\nconst PROJECT_SEARCH_CONTENTS_MAX_LIMIT = 500;\nconst PROJECT_WRITE_FILE_PATH_MAX_LENGTH = 512;\nconst PROJECT_READ_FILE_PATH_MAX_LENGTH = 512;\n\nexport const ProjectEntryKind = Schema.Literals([\"file\", \"directory\"]);\nexport type ProjectEntryKind = typeof ProjectEntryKind.Type;\n\nexport const ProjectSearchEntriesInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  // An empty query is a bounded browse: the index returns frecency-ordered\n  // entries, which the file picker uses for its initial results.\n  query: TrimmedString.check(Schema.isMaxLength(256)),\n  limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_ENTRIES_MAX_LIMIT)),\n  kind: Schema.optional(ProjectEntryKind),\n});\nexport type ProjectSearchEntriesInput = typeof ProjectSearchEntriesInput.Type;\n\nexport const ProjectEntry = Schema.Struct({\n  path: TrimmedNonEmptyString,\n  kind: ProjectEntryKind,\n});\nexport type ProjectEntry = typeof ProjectEntry.Type;\n\nexport const ProjectSearchEntriesResult = Schema.Struct({\n  entries: Schema.Array(ProjectEntry),\n  truncated: Schema.Boolean,\n});\nexport type ProjectSearchEntriesResult = typeof ProjectSearchEntriesResult.Type;\n\nexport const ProjectSearchContentsInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  // Whitespace is significant in content queries (\" foo\", regex trailing\n  // spaces), so the query is deliberately not trimmed on the wire.\n  query: Schema.String.check(Schema.isNonEmpty(), Schema.isMaxLength(256)),\n  limit: PositiveInt.check(Schema.isLessThanOrEqualTo(PROJECT_SEARCH_CONTENTS_MAX_LIMIT)),\n  caseSensitive: Schema.Boolean,\n  wholeWord: Schema.Boolean,\n  useRegex: Schema.Boolean,\n});\nexport type ProjectSearchContentsInput = typeof ProjectSearchContentsInput.Type;\n\nexport const ProjectContentMatchRange = Schema.Struct({\n  start: NonNegativeInt,\n  end: NonNegativeInt,\n});\nexport type ProjectContentMatchRange = typeof ProjectContentMatchRange.Type;\n\nexport const ProjectContentMatch = Schema.Struct({\n  path: TrimmedNonEmptyString,\n  lineNumber: PositiveInt,\n  lineContent: Schema.String,\n  matchRanges: Schema.Array(ProjectContentMatchRange),\n});\nexport type ProjectContentMatch = typeof ProjectContentMatch.Type;\n\nexport const ProjectSearchContentsResult = Schema.Struct({\n  matches: Schema.Array(ProjectContentMatch),\n  truncated: Schema.Boolean,\n  regexFallbackError: Schema.optional(Schema.String),\n});\nexport type ProjectSearchContentsResult = typeof ProjectSearchContentsResult.Type;\n\nexport const ProjectListEntriesInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n});\nexport type ProjectListEntriesInput = typeof ProjectListEntriesInput.Type;\n\nexport const ProjectListEntriesResult = Schema.Struct({\n  entries: Schema.Array(ProjectEntry),\n  truncated: Schema.Boolean,\n});\nexport type ProjectListEntriesResult = typeof ProjectListEntriesResult.Type;\n\nexport const ProjectEntriesFailure = Schema.Literals([\n  \"workspace_root_not_found\",\n  \"workspace_root_create_failed\",\n  \"workspace_root_stat_failed\",\n  \"workspace_root_not_directory\",\n  \"search_index_create_failed\",\n  \"search_index_scan_timed_out\",\n  \"search_index_search_failed\",\n]);\nexport type ProjectEntriesFailure = typeof ProjectEntriesFailure.Type;\n\ntype ProjectEntriesFailureContext = {\n  readonly failure: ProjectEntriesFailure;\n  readonly normalizedCwd?: string;\n  readonly timeout?: string;\n  readonly detail?: string;\n  readonly cause?: unknown;\n};\n\nfunction decodedProjectErrorMessage(props: object): string | undefined {\n  if (!(\"message\" in props)) return undefined;\n  return typeof props.message === \"string\" ? props.message : undefined;\n}\n\nexport class ProjectSearchEntriesError extends Schema.TaggedErrorClass<ProjectSearchEntriesError>()(\n  \"ProjectSearchEntriesError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    queryLength: Schema.optional(NonNegativeInt),\n    limit: Schema.optional(PositiveInt),\n    failure: Schema.optional(ProjectEntriesFailure),\n    normalizedCwd: Schema.optional(TrimmedNonEmptyString),\n    timeout: Schema.optional(TrimmedNonEmptyString),\n    detail: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // The structured fields are optional on the wire so newer peers can decode legacy message-only\n  // failures. New application code must provide them through this constructor.\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(\n    props: ProjectEntriesFailureContext & {\n      readonly cwd: string;\n      readonly queryLength: number;\n      readonly limit: number;\n    },\n  ) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ??\n        `Failed to search workspace entries in '${props.cwd}'.`,\n    } as any);\n  }\n}\n\nexport class ProjectSearchContentsError extends Schema.TaggedErrorClass<ProjectSearchContentsError>()(\n  \"ProjectSearchContentsError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    queryLength: Schema.optional(NonNegativeInt),\n    limit: Schema.optional(PositiveInt),\n    failure: Schema.optional(ProjectEntriesFailure),\n    normalizedCwd: Schema.optional(TrimmedNonEmptyString),\n    timeout: Schema.optional(TrimmedNonEmptyString),\n    detail: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(\n    props: ProjectEntriesFailureContext & {\n      readonly cwd: string;\n      readonly queryLength: number;\n      readonly limit: number;\n    },\n  ) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ??\n        `Failed to search workspace contents in '${props.cwd}'.`,\n    } as any);\n  }\n}\n\nexport class ProjectListEntriesError extends Schema.TaggedErrorClass<ProjectListEntriesError>()(\n  \"ProjectListEntriesError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    failure: Schema.optional(ProjectEntriesFailure),\n    normalizedCwd: Schema.optional(TrimmedNonEmptyString),\n    timeout: Schema.optional(TrimmedNonEmptyString),\n    detail: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(props: ProjectEntriesFailureContext & { readonly cwd: string }) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ?? `Failed to list workspace entries in '${props.cwd}'.`,\n    } as any);\n  }\n}\n\nexport const ProjectReadFileInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_READ_FILE_PATH_MAX_LENGTH)),\n});\nexport type ProjectReadFileInput = typeof ProjectReadFileInput.Type;\n\nexport const ProjectReadFileResult = Schema.Struct({\n  relativePath: TrimmedNonEmptyString,\n  contents: Schema.String,\n  byteLength: NonNegativeInt,\n  truncated: Schema.Boolean,\n});\nexport type ProjectReadFileResult = typeof ProjectReadFileResult.Type;\n\nexport const ProjectFileFailure = Schema.Literals([\n  \"workspace_path_outside_root\",\n  \"resolved_path_outside_root\",\n  \"path_not_file\",\n  \"binary_file\",\n  \"operation_failed\",\n]);\nexport type ProjectFileFailure = typeof ProjectFileFailure.Type;\n\nexport const ProjectFileOperation = Schema.Literals([\n  \"realpath-workspace-root\",\n  \"realpath-target\",\n  \"open\",\n  \"stat\",\n  \"read\",\n  \"close\",\n  \"make-directory\",\n  \"write-file\",\n]);\nexport type ProjectFileOperation = typeof ProjectFileOperation.Type;\n\ntype ProjectFileFailureContext = {\n  readonly cwd: string;\n  readonly relativePath: string;\n  readonly failure: ProjectFileFailure;\n  readonly resolvedPath?: string;\n  readonly resolvedWorkspaceRoot?: string;\n  readonly operation?: ProjectFileOperation;\n  readonly operationPath?: string;\n  readonly cause?: unknown;\n};\n\nexport class ProjectReadFileError extends Schema.TaggedErrorClass<ProjectReadFileError>()(\n  \"ProjectReadFileError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    relativePath: Schema.optional(TrimmedNonEmptyString),\n    failure: Schema.optional(ProjectFileFailure),\n    resolvedPath: Schema.optional(TrimmedNonEmptyString),\n    resolvedWorkspaceRoot: Schema.optional(TrimmedNonEmptyString),\n    operation: Schema.optional(ProjectFileOperation),\n    operationPath: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(props: ProjectFileFailureContext) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ??\n        `Failed to read workspace file '${props.relativePath}' in '${props.cwd}'.`,\n    } as any);\n  }\n}\n\nexport const ProjectWriteFileInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  relativePath: TrimmedNonEmptyString.check(Schema.isMaxLength(PROJECT_WRITE_FILE_PATH_MAX_LENGTH)),\n  contents: Schema.String,\n});\nexport type ProjectWriteFileInput = typeof ProjectWriteFileInput.Type;\n\nexport const ProjectWriteFileResult = Schema.Struct({\n  relativePath: TrimmedNonEmptyString,\n});\nexport type ProjectWriteFileResult = typeof ProjectWriteFileResult.Type;\n\nexport class ProjectWriteFileError extends Schema.TaggedErrorClass<ProjectWriteFileError>()(\n  \"ProjectWriteFileError\",\n  {\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    relativePath: Schema.optional(TrimmedNonEmptyString),\n    failure: Schema.optional(ProjectFileFailure),\n    resolvedPath: Schema.optional(TrimmedNonEmptyString),\n    resolvedWorkspaceRoot: Schema.optional(TrimmedNonEmptyString),\n    operation: Schema.optional(ProjectFileOperation),\n    operationPath: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(props: ProjectFileFailureContext) {\n    super({\n      ...props,\n      message:\n        decodedProjectErrorMessage(props) ??\n        `Failed to write workspace file '${props.relativePath}' in '${props.cwd}'.`,\n    } as any);\n  }\n}\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nconst FILESYSTEM_PATH_MAX_LENGTH = 512;\n\nexport const FilesystemBrowseInput = Schema.Struct({\n  partialPath: TrimmedNonEmptyString.check(Schema.isMaxLength(FILESYSTEM_PATH_MAX_LENGTH)),\n  cwd: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(FILESYSTEM_PATH_MAX_LENGTH))),\n});\nexport type FilesystemBrowseInput = typeof FilesystemBrowseInput.Type;\n\nexport const FilesystemBrowseEntry = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  fullPath: TrimmedNonEmptyString,\n});\nexport type FilesystemBrowseEntry = typeof FilesystemBrowseEntry.Type;\n\nexport const FilesystemBrowseResult = Schema.Struct({\n  parentPath: TrimmedNonEmptyString,\n  entries: Schema.Array(FilesystemBrowseEntry),\n});\nexport type FilesystemBrowseResult = typeof FilesystemBrowseResult.Type;\n\nexport const FilesystemBrowseFailure = Schema.Literals([\n  \"windows_path_unsupported\",\n  \"current_project_required\",\n  \"read_directory_failed\",\n]);\nexport type FilesystemBrowseFailure = typeof FilesystemBrowseFailure.Type;\n\nfunction decodedFilesystemBrowseErrorMessage(props: object): string | undefined {\n  if (!(\"message\" in props)) return undefined;\n  return typeof props.message === \"string\" ? props.message : undefined;\n}\n\nexport class FilesystemBrowseError extends Schema.TaggedErrorClass<FilesystemBrowseError>()(\n  \"FilesystemBrowseError\",\n  {\n    partialPath: Schema.optional(TrimmedNonEmptyString),\n    cwd: Schema.optional(TrimmedNonEmptyString),\n    failure: Schema.optional(FilesystemBrowseFailure),\n    parentPath: Schema.optional(TrimmedNonEmptyString),\n    platform: Schema.optional(TrimmedNonEmptyString),\n    message: TrimmedNonEmptyString,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  // Structured diagnostics stay optional for rolling compatibility with legacy message-only\n  // payloads, while new call sites must provide the request context and failure classification.\n  // @effect-diagnostics-next-line overriddenSchemaConstructor:off\n  constructor(props: {\n    readonly partialPath: string;\n    readonly cwd?: string | undefined;\n    readonly failure: FilesystemBrowseFailure;\n    readonly parentPath?: string;\n    readonly platform?: string;\n    readonly cause?: unknown;\n  }) {\n    const cwd = props.cwd === undefined ? \"\" : ` from '${props.cwd}'`;\n    super({\n      ...props,\n      message:\n        decodedFilesystemBrowseErrorMessage(props) ??\n        `Failed to browse filesystem path '${props.partialPath}'${cwd}.`,\n    } as any);\n  }\n}\n","import * as Schema from \"effect/Schema\";\n\nimport { ThreadId, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\nconst ASSET_PATH_MAX_LENGTH = 1024;\n\nexport const AssetResource = Schema.Union([\n  Schema.TaggedStruct(\"workspace-file\", {\n    threadId: ThreadId,\n    path: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),\n  }),\n  Schema.TaggedStruct(\"attachment\", {\n    attachmentId: TrimmedNonEmptyString.check(Schema.isMaxLength(256)),\n  }),\n  Schema.TaggedStruct(\"project-favicon\", {\n    cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)),\n  }),\n]);\nexport type AssetResource = typeof AssetResource.Type;\n\nexport const AssetCreateUrlInput = Schema.Struct({\n  resource: AssetResource,\n});\nexport type AssetCreateUrlInput = typeof AssetCreateUrlInput.Type;\n\nexport const AssetCreateUrlResult = Schema.Struct({\n  relativeUrl: TrimmedNonEmptyString.check(Schema.isMaxLength(4096)),\n  expiresAt: Schema.Number,\n});\nexport type AssetCreateUrlResult = typeof AssetCreateUrlResult.Type;\n\nexport class AssetWorkspaceContextNotFoundError extends Schema.TaggedErrorClass<AssetWorkspaceContextNotFoundError>()(\n  \"AssetWorkspaceContextNotFoundError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Workspace context was not found.\";\n  }\n}\n\nexport class AssetWorkspaceContextResolutionError extends Schema.TaggedErrorClass<AssetWorkspaceContextResolutionError>()(\n  \"AssetWorkspaceContextResolutionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to resolve workspace context.\";\n  }\n}\n\nexport class AssetWorkspaceRootNormalizationError extends Schema.TaggedErrorClass<AssetWorkspaceRootNormalizationError>()(\n  \"AssetWorkspaceRootNormalizationError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to normalize the workspace root.\";\n  }\n}\n\nexport class AssetWorkspacePathValidationError extends Schema.TaggedErrorClass<AssetWorkspacePathValidationError>()(\n  \"AssetWorkspacePathValidationError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Workspace file path must be relative to the project root.\";\n  }\n}\n\nexport class AssetPreviewTypeValidationError extends Schema.TaggedErrorClass<AssetPreviewTypeValidationError>()(\n  \"AssetPreviewTypeValidationError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Only browser documents and images can be previewed.\";\n  }\n}\n\nexport class AssetWorkspaceAssetInspectionError extends Schema.TaggedErrorClass<AssetWorkspaceAssetInspectionError>()(\n  \"AssetWorkspaceAssetInspectionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to inspect the workspace asset.\";\n  }\n}\n\nexport class AssetWorkspaceAssetNotFoundError extends Schema.TaggedErrorClass<AssetWorkspaceAssetNotFoundError>()(\n  \"AssetWorkspaceAssetNotFoundError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Workspace asset was not found.\";\n  }\n}\n\nexport class AssetWorkspaceResolutionError extends Schema.TaggedErrorClass<AssetWorkspaceResolutionError>()(\n  \"AssetWorkspaceResolutionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to resolve workspace.\";\n  }\n}\n\nexport class AssetAttachmentNotFoundError extends Schema.TaggedErrorClass<AssetAttachmentNotFoundError>()(\n  \"AssetAttachmentNotFoundError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Attachment was not found.\";\n  }\n}\n\nexport class AssetProjectFaviconResolutionError extends Schema.TaggedErrorClass<AssetProjectFaviconResolutionError>()(\n  \"AssetProjectFaviconResolutionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to resolve project favicon.\";\n  }\n}\n\nexport class AssetProjectFaviconInspectionError extends Schema.TaggedErrorClass<AssetProjectFaviconInspectionError>()(\n  \"AssetProjectFaviconInspectionError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to inspect the project favicon.\";\n  }\n}\n\nexport class AssetProjectFaviconNotFoundError extends Schema.TaggedErrorClass<AssetProjectFaviconNotFoundError>()(\n  \"AssetProjectFaviconNotFoundError\",\n  {\n    resource: AssetResource,\n  },\n) {\n  override get message(): string {\n    return \"Project favicon was not found.\";\n  }\n}\n\nexport class AssetSigningKeyLoadError extends Schema.TaggedErrorClass<AssetSigningKeyLoadError>()(\n  \"AssetSigningKeyLoadError\",\n  {\n    resource: AssetResource,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to load the asset signing key.\";\n  }\n}\n\nexport const AssetAccessError = Schema.Union([\n  AssetWorkspaceContextNotFoundError,\n  AssetWorkspaceContextResolutionError,\n  AssetWorkspaceRootNormalizationError,\n  AssetWorkspacePathValidationError,\n  AssetPreviewTypeValidationError,\n  AssetWorkspaceAssetInspectionError,\n  AssetWorkspaceAssetNotFoundError,\n  AssetWorkspaceResolutionError,\n  AssetAttachmentNotFoundError,\n  AssetProjectFaviconResolutionError,\n  AssetProjectFaviconInspectionError,\n  AssetProjectFaviconNotFoundError,\n  AssetSigningKeyLoadError,\n]);\nexport type AssetAccessError = typeof AssetAccessError.Type;\n","import * as Schema from \"effect/Schema\";\nimport { TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { GitCommandError } from \"./git.ts\";\nimport { VcsError } from \"./vcs.ts\";\n\nexport const ReviewDiffPreviewInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  baseRef: Schema.optional(TrimmedNonEmptyString),\n  ignoreWhitespace: Schema.optionalKey(Schema.Boolean),\n});\nexport type ReviewDiffPreviewInput = typeof ReviewDiffPreviewInput.Type;\n\nexport const ReviewDiffPreviewSourceKind = Schema.Literals([\"working-tree\", \"branch-range\"]);\nexport type ReviewDiffPreviewSourceKind = typeof ReviewDiffPreviewSourceKind.Type;\n\nexport const ReviewDiffPreviewSource = Schema.Struct({\n  id: TrimmedNonEmptyString,\n  kind: ReviewDiffPreviewSourceKind,\n  title: TrimmedNonEmptyString,\n  baseRef: Schema.NullOr(TrimmedNonEmptyString),\n  headRef: Schema.NullOr(TrimmedNonEmptyString),\n  diff: Schema.String,\n  diffHash: TrimmedNonEmptyString,\n  truncated: Schema.Boolean,\n});\nexport type ReviewDiffPreviewSource = typeof ReviewDiffPreviewSource.Type;\n\nexport const ReviewDiffFileContentsInput = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  sourceKind: ReviewDiffPreviewSourceKind,\n  changeType: Schema.Literals([\"change\", \"rename-pure\", \"rename-changed\", \"new\", \"deleted\"]),\n  baseRef: Schema.NullOr(TrimmedNonEmptyString),\n  headRef: Schema.NullOr(TrimmedNonEmptyString),\n  oldPath: TrimmedNonEmptyString,\n  newPath: TrimmedNonEmptyString,\n});\nexport type ReviewDiffFileContentsInput = typeof ReviewDiffFileContentsInput.Type;\n\nexport const ReviewDiffFileContentsResult = Schema.Struct({\n  oldContents: Schema.String,\n  newContents: Schema.String,\n});\nexport type ReviewDiffFileContentsResult = typeof ReviewDiffFileContentsResult.Type;\n\nexport const ReviewDiffPreviewResult = Schema.Struct({\n  cwd: TrimmedNonEmptyString,\n  generatedAt: Schema.DateTimeUtc,\n  sources: Schema.Array(ReviewDiffPreviewSource),\n});\nexport type ReviewDiffPreviewResult = typeof ReviewDiffPreviewResult.Type;\n\nexport const ReviewDiffPreviewError = Schema.Union([VcsError, GitCommandError]);\nexport type ReviewDiffPreviewError = typeof ReviewDiffPreviewError.Type;\n","import * as Schema from \"effect/Schema\";\n\nimport { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\nimport { HostPowerSnapshot } from \"./background.ts\";\n\nexport const RESOURCE_MONITOR_PROTOCOL_VERSION = 2 as const;\n\nexport const ResourceTelemetryIoSemantics = Schema.Literals([\n  \"storage\",\n  \"logical\",\n  \"all-io\",\n  \"unavailable\",\n]);\nexport type ResourceTelemetryIoSemantics = typeof ResourceTelemetryIoSemantics.Type;\n\nexport const ResourceTelemetryProcessCategory = Schema.Literals([\n  \"server\",\n  \"server-child\",\n  \"provider-root\",\n  \"terminal-root\",\n  \"electron-main\",\n  \"electron-renderer\",\n  \"electron-gpu\",\n  \"electron-utility\",\n  \"resource-monitor\",\n  \"unknown-t3\",\n]);\nexport type ResourceTelemetryProcessCategory = typeof ResourceTelemetryProcessCategory.Type;\n\nexport const ResourceTelemetrySourceStatus = Schema.Literals([\n  \"starting\",\n  \"healthy\",\n  \"degraded\",\n  \"unavailable\",\n  \"stopped\",\n]);\nexport type ResourceTelemetrySourceStatus = typeof ResourceTelemetrySourceStatus.Type;\n\nexport const ResourceTelemetryProcessIdentity = Schema.Struct({\n  pid: PositiveInt,\n  startTimeMs: NonNegativeInt,\n});\nexport type ResourceTelemetryProcessIdentity = typeof ResourceTelemetryProcessIdentity.Type;\n\nexport const ResourceMonitorExternalProcess = Schema.Struct({\n  pid: PositiveInt,\n  startTimeMs: Schema.optionalKey(NonNegativeInt),\n});\nexport type ResourceMonitorExternalProcess = typeof ResourceMonitorExternalProcess.Type;\n\nexport const ResourceMonitorCapabilities = Schema.Struct({\n  cumulativeCpuTime: Schema.Boolean,\n  currentCpuPercent: Schema.Boolean,\n  residentMemory: Schema.Boolean,\n  virtualMemory: Schema.Boolean,\n  ioBytes: Schema.Boolean,\n  processStartTime: Schema.Boolean,\n  processTree: Schema.Boolean,\n});\nexport type ResourceMonitorCapabilities = typeof ResourceMonitorCapabilities.Type;\n\nexport const ResourceMonitorProcessSample = Schema.Struct({\n  pid: PositiveInt,\n  ppid: NonNegativeInt,\n  startTimeMs: NonNegativeInt,\n  runTimeMs: NonNegativeInt,\n  name: Schema.String,\n  command: Schema.String,\n  status: Schema.String,\n  cpuPercent: Schema.Number,\n  cpuTimeMs: NonNegativeInt,\n  residentBytes: NonNegativeInt,\n  virtualBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  ioSemantics: Schema.Literals([\"storage\", \"all-io\"]),\n});\nexport type ResourceMonitorProcessSample = typeof ResourceMonitorProcessSample.Type;\n\nexport const ResourceMonitorConfigureCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"configure\"),\n  rootPid: PositiveInt,\n  sampleIntervalMs: NonNegativeInt,\n  externalProcesses: Schema.Array(ResourceMonitorExternalProcess),\n});\nexport type ResourceMonitorConfigureCommand = typeof ResourceMonitorConfigureCommand.Type;\n\nexport const ResourceMonitorSetExternalProcessesCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"setExternalProcesses\"),\n  processes: Schema.Array(ResourceMonitorExternalProcess),\n});\nexport type ResourceMonitorSetExternalProcessesCommand =\n  typeof ResourceMonitorSetExternalProcessesCommand.Type;\n\nexport const ResourceMonitorSampleNowCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"sampleNow\"),\n  requestId: TrimmedNonEmptyString,\n});\nexport type ResourceMonitorSampleNowCommand = typeof ResourceMonitorSampleNowCommand.Type;\n\nexport const ResourceMonitorSetSampleIntervalCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"setSampleInterval\"),\n  sampleIntervalMs: NonNegativeInt,\n});\nexport type ResourceMonitorSetSampleIntervalCommand =\n  typeof ResourceMonitorSetSampleIntervalCommand.Type;\n\nexport const ResourceMonitorSetStreamingCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"setStreaming\"),\n  enabled: Schema.Boolean,\n});\nexport type ResourceMonitorSetStreamingCommand = typeof ResourceMonitorSetStreamingCommand.Type;\n\nexport const ResourceMonitorReadHistoryCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"readHistory\"),\n  requestId: TrimmedNonEmptyString,\n  windowMs: NonNegativeInt,\n});\nexport type ResourceMonitorReadHistoryCommand = typeof ResourceMonitorReadHistoryCommand.Type;\n\nexport const ResourceMonitorShutdownCommand = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"shutdown\"),\n});\nexport type ResourceMonitorShutdownCommand = typeof ResourceMonitorShutdownCommand.Type;\n\nexport const ResourceMonitorCommand = Schema.Union([\n  ResourceMonitorConfigureCommand,\n  ResourceMonitorSetExternalProcessesCommand,\n  ResourceMonitorSetSampleIntervalCommand,\n  ResourceMonitorSetStreamingCommand,\n  ResourceMonitorSampleNowCommand,\n  ResourceMonitorReadHistoryCommand,\n  ResourceMonitorShutdownCommand,\n]);\nexport type ResourceMonitorCommand = typeof ResourceMonitorCommand.Type;\n\nexport const ResourceMonitorHelloEvent = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"hello\"),\n  sidecarVersion: TrimmedNonEmptyString,\n  sidecarPid: PositiveInt,\n  platform: TrimmedNonEmptyString,\n  arch: TrimmedNonEmptyString,\n  capabilities: ResourceMonitorCapabilities,\n});\nexport type ResourceMonitorHelloEvent = typeof ResourceMonitorHelloEvent.Type;\n\nexport const ResourceMonitorSnapshotEvent = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"snapshot\"),\n  sequence: NonNegativeInt,\n  sampledAtUnixMs: NonNegativeInt,\n  collectionDurationMicros: NonNegativeInt,\n  scannedProcessCount: NonNegativeInt,\n  retainedProcessCount: NonNegativeInt,\n  inaccessibleProcessCount: NonNegativeInt,\n  requestId: Schema.optionalKey(TrimmedNonEmptyString),\n  externalProcesses: Schema.optionalKey(Schema.Array(ResourceMonitorExternalProcess)),\n  processes: Schema.Array(ResourceMonitorProcessSample),\n});\nexport type ResourceMonitorSnapshotEvent = typeof ResourceMonitorSnapshotEvent.Type;\n\nexport const ResourceMonitorHistoryChunkEvent = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"historyChunk\"),\n  requestId: TrimmedNonEmptyString,\n  done: Schema.Boolean,\n  snapshots: Schema.Array(ResourceMonitorSnapshotEvent),\n});\nexport type ResourceMonitorHistoryChunkEvent = typeof ResourceMonitorHistoryChunkEvent.Type;\n\nexport const ResourceMonitorErrorEvent = Schema.Struct({\n  version: Schema.Literal(RESOURCE_MONITOR_PROTOCOL_VERSION),\n  type: Schema.Literal(\"error\"),\n  code: TrimmedNonEmptyString,\n  message: TrimmedNonEmptyString,\n  recoverable: Schema.Boolean,\n});\nexport type ResourceMonitorErrorEvent = typeof ResourceMonitorErrorEvent.Type;\n\nexport const ResourceMonitorEvent = Schema.Union([\n  ResourceMonitorHelloEvent,\n  ResourceMonitorSnapshotEvent,\n  ResourceMonitorHistoryChunkEvent,\n  ResourceMonitorErrorEvent,\n]);\nexport type ResourceMonitorEvent = typeof ResourceMonitorEvent.Type;\n\nexport const DesktopElectronProcessType = Schema.Literals([\n  \"Browser\",\n  \"Tab\",\n  \"Utility\",\n  \"Zygote\",\n  \"Sandbox helper\",\n  \"GPU\",\n  \"Pepper Plugin\",\n  \"Pepper Plugin Broker\",\n  \"Unknown\",\n]);\nexport type DesktopElectronProcessType = typeof DesktopElectronProcessType.Type;\n\nexport const DesktopElectronProcessMetric = Schema.Struct({\n  pid: PositiveInt,\n  creationTimeMs: NonNegativeInt,\n  type: DesktopElectronProcessType,\n  name: Schema.optionalKey(Schema.String),\n  serviceName: Schema.optionalKey(Schema.String),\n  cpuPercent: Schema.Number,\n  cumulativeCpuSeconds: Schema.optionalKey(Schema.Number),\n  idleWakeupsPerSecond: Schema.Number,\n  workingSetBytes: NonNegativeInt,\n  peakWorkingSetBytes: NonNegativeInt,\n});\nexport type DesktopElectronProcessMetric = typeof DesktopElectronProcessMetric.Type;\n\nconst DesktopHostPowerSnapshot = Schema.Struct({\n  ...HostPowerSnapshot.fields,\n  updatedAt: Schema.DateTimeUtcFromString,\n});\n\nexport const DesktopHostTelemetrySnapshot = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"desktopTelemetry\"),\n  sequence: NonNegativeInt,\n  sampledAtUnixMs: NonNegativeInt,\n  electronPid: PositiveInt,\n  power: DesktopHostPowerSnapshot,\n  speedLimitPercent: Schema.OptionFromNullOr(Schema.Number),\n  electronProcesses: Schema.Array(DesktopElectronProcessMetric),\n});\nexport type DesktopHostTelemetrySnapshot = typeof DesktopHostTelemetrySnapshot.Type;\n\nexport const DesktopHostTelemetryHello = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"desktopTelemetryHello\"),\n  electronPid: PositiveInt,\n});\nexport type DesktopHostTelemetryHello = typeof DesktopHostTelemetryHello.Type;\n\nexport const DesktopHostTelemetryMessage = Schema.Union([\n  DesktopHostTelemetryHello,\n  DesktopHostTelemetrySnapshot,\n]);\nexport type DesktopHostTelemetryMessage = typeof DesktopHostTelemetryMessage.Type;\n\nexport const DesktopTelemetrySetDiagnosticsDemand = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"setDiagnosticsDemand\"),\n  enabled: Schema.Boolean,\n});\nexport type DesktopTelemetrySetDiagnosticsDemand = typeof DesktopTelemetrySetDiagnosticsDemand.Type;\n\nexport const DesktopTelemetrySetHostPowerIntervals = Schema.Struct({\n  version: Schema.Literal(1),\n  type: Schema.Literal(\"setHostPowerIntervals\"),\n  activeIntervalMs: PositiveInt,\n  idleIntervalMs: PositiveInt,\n});\nexport type DesktopTelemetrySetHostPowerIntervals =\n  typeof DesktopTelemetrySetHostPowerIntervals.Type;\n\nexport const DesktopTelemetryControlMessage = Schema.Union([\n  DesktopTelemetrySetDiagnosticsDemand,\n  DesktopTelemetrySetHostPowerIntervals,\n]);\nexport type DesktopTelemetryControlMessage = typeof DesktopTelemetryControlMessage.Type;\n\nexport const ResourceTelemetryProcess = Schema.Struct({\n  identity: ResourceTelemetryProcessIdentity,\n  ppid: NonNegativeInt,\n  childPids: Schema.Array(PositiveInt),\n  depth: NonNegativeInt,\n  name: Schema.String,\n  command: Schema.String,\n  status: Schema.String,\n  category: ResourceTelemetryProcessCategory,\n  electronType: Schema.optionalKey(DesktopElectronProcessType),\n  electronServiceName: Schema.optionalKey(Schema.String),\n  cpuPercent: Schema.Number,\n  cpuTimeMs: NonNegativeInt,\n  residentBytes: NonNegativeInt,\n  peakResidentBytes: NonNegativeInt,\n  virtualBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  ioReadBytesPerSecond: Schema.Number,\n  ioWriteBytesPerSecond: Schema.Number,\n  ioSemantics: ResourceTelemetryIoSemantics,\n  idleWakeupsPerSecond: Schema.optionalKey(Schema.Number),\n  runTimeMs: NonNegativeInt,\n  firstSeenAt: Schema.DateTimeUtc,\n  lastSeenAt: Schema.DateTimeUtc,\n});\nexport type ResourceTelemetryProcess = typeof ResourceTelemetryProcess.Type;\n\nexport const ResourceTelemetryAggregate = Schema.Struct({\n  processCount: NonNegativeInt,\n  currentCpuPercent: Schema.Number,\n  cpuTimeMs: NonNegativeInt,\n  currentRssBytes: NonNegativeInt,\n  peakRssBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  ioReadBytesPerSecond: Schema.Number,\n  ioWriteBytesPerSecond: Schema.Number,\n  processStarts: NonNegativeInt,\n  processExits: NonNegativeInt,\n});\nexport type ResourceTelemetryAggregate = typeof ResourceTelemetryAggregate.Type;\n\nexport const ResourceTelemetryGroups = Schema.Struct({\n  backend: ResourceTelemetryAggregate,\n  electron: ResourceTelemetryAggregate,\n  monitor: ResourceTelemetryAggregate,\n  allT3: ResourceTelemetryAggregate,\n});\nexport type ResourceTelemetryGroups = typeof ResourceTelemetryGroups.Type;\n\nexport const ResourceTelemetrySourceHealth = Schema.Struct({\n  status: ResourceTelemetrySourceStatus,\n  lastSampleAt: Schema.Option(Schema.DateTimeUtc),\n  lastError: Schema.Option(TrimmedNonEmptyString),\n});\nexport type ResourceTelemetrySourceHealth = typeof ResourceTelemetrySourceHealth.Type;\n\nexport const ResourceTelemetryHealth = Schema.Struct({\n  native: ResourceTelemetrySourceHealth,\n  desktop: ResourceTelemetrySourceHealth,\n  sidecarVersion: Schema.Option(TrimmedNonEmptyString),\n  sidecarPid: Schema.Option(PositiveInt),\n  restartCount: NonNegativeInt,\n  collectionDurationMicros: NonNegativeInt,\n  scannedProcessCount: NonNegativeInt,\n  retainedProcessCount: NonNegativeInt,\n  inaccessibleProcessCount: NonNegativeInt,\n});\nexport type ResourceTelemetryHealth = typeof ResourceTelemetryHealth.Type;\n\nexport const ResourceAttributionEntry = Schema.Struct({\n  component: TrimmedNonEmptyString,\n  operation: TrimmedNonEmptyString,\n  logicalReadBytes: NonNegativeInt,\n  logicalWriteBytes: NonNegativeInt,\n  count: NonNegativeInt,\n  durationMs: NonNegativeInt,\n});\nexport type ResourceAttributionEntry = typeof ResourceAttributionEntry.Type;\n\nexport const ResourceAttributionSnapshot = Schema.Struct({\n  readAt: Schema.DateTimeUtc,\n  entries: Schema.Array(ResourceAttributionEntry),\n});\nexport type ResourceAttributionSnapshot = typeof ResourceAttributionSnapshot.Type;\n\nexport const ResourceTelemetrySnapshot = Schema.Struct({\n  readAt: Schema.DateTimeUtc,\n  sampleIntervalMs: NonNegativeInt,\n  processes: Schema.Array(ResourceTelemetryProcess),\n  groups: ResourceTelemetryGroups,\n  power: HostPowerSnapshot,\n  speedLimitPercent: Schema.Option(Schema.Number),\n  attribution: ResourceAttributionSnapshot,\n  health: ResourceTelemetryHealth,\n});\nexport type ResourceTelemetrySnapshot = typeof ResourceTelemetrySnapshot.Type;\n\nexport const ResourceTelemetryHistoryInput = Schema.Struct({\n  windowMs: NonNegativeInt,\n  bucketMs: NonNegativeInt,\n});\nexport type ResourceTelemetryHistoryInput = typeof ResourceTelemetryHistoryInput.Type;\n\nexport const ResourceTelemetryHistoryBucket = Schema.Struct({\n  startedAt: Schema.DateTimeUtc,\n  endedAt: Schema.DateTimeUtc,\n  avgCpuPercent: Schema.Number,\n  maxCpuPercent: Schema.Number,\n  maxRssBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  maxProcessCount: NonNegativeInt,\n});\nexport type ResourceTelemetryHistoryBucket = typeof ResourceTelemetryHistoryBucket.Type;\n\nexport const ResourceTelemetryProcessSummary = Schema.Struct({\n  identity: ResourceTelemetryProcessIdentity,\n  ppid: NonNegativeInt,\n  depth: NonNegativeInt,\n  name: Schema.String,\n  command: Schema.String,\n  category: ResourceTelemetryProcessCategory,\n  firstSeenAt: Schema.DateTimeUtc,\n  lastSeenAt: Schema.DateTimeUtc,\n  currentCpuPercent: Schema.Number,\n  avgCpuPercent: Schema.Number,\n  maxCpuPercent: Schema.Number,\n  cpuTimeMs: NonNegativeInt,\n  currentRssBytes: NonNegativeInt,\n  peakRssBytes: NonNegativeInt,\n  ioReadBytes: NonNegativeInt,\n  ioWriteBytes: NonNegativeInt,\n  ioSemantics: ResourceTelemetryIoSemantics,\n  sampleCount: NonNegativeInt,\n});\nexport type ResourceTelemetryProcessSummary = typeof ResourceTelemetryProcessSummary.Type;\n\nexport const ResourceTelemetryHistory = Schema.Struct({\n  readAt: Schema.DateTimeUtc,\n  windowMs: NonNegativeInt,\n  bucketMs: NonNegativeInt,\n  sampleIntervalMs: NonNegativeInt,\n  retainedSampleCount: NonNegativeInt,\n  buckets: Schema.Array(ResourceTelemetryHistoryBucket),\n  topProcesses: Schema.Array(ResourceTelemetryProcessSummary),\n  health: ResourceTelemetryHealth,\n});\nexport type ResourceTelemetryHistory = typeof ResourceTelemetryHistory.Type;\n\nexport const ResourceTelemetryRetryResult = Schema.Struct({\n  accepted: Schema.Boolean,\n  snapshot: ResourceTelemetrySnapshot,\n});\nexport type ResourceTelemetryRetryResult = typeof ResourceTelemetryRetryResult.Type;\n","/**\n * Usage reporting contract.\n *\n * Each environment scans the provider CLIs' own on-disk session transcripts\n * (`~/.claude/projects/**\\/*.jsonl`, `~/.codex/sessions/**\\/*.jsonl`) rather than\n * relying on Synaptic Code's own orchestration projections, so usage stays\n * complete even for turns that were never driven through Synaptic Code. This\n * mirrors the approach `ccusage` takes.\n *\n * Environments return pre-aggregated `(day, provider, model)` buckets. Raw\n * transcript records never cross the wire.\n *\n * @module usage\n */\nimport * as Schema from \"effect/Schema\";\n\nimport { NonNegativeInt, TrimmedNonEmptyString } from \"./baseSchemas.ts\";\n\n/**\n * Bumped whenever the shape of {@link UsageSummary} changes incompatibly. The\n * client renders partial coverage when an environment reports an older version\n * rather than failing the whole page.\n */\nexport const USAGE_CONTRACT_VERSION = 3 as const;\n\nexport const UsageProviderKind = Schema.Literals([\"claude\", \"codex\"]);\nexport type UsageProviderKind = typeof UsageProviderKind.Type;\n\n/**\n * A calendar day in the reporting time zone, formatted `YYYY-MM-DD`.\n *\n * Days are bucketed server-side so that a turn always lands on the day the user\n * experienced it, not the UTC day.\n */\nconst USAGE_DAY_PATTERN = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nexport const UsageDay = TrimmedNonEmptyString.check(Schema.isPattern(USAGE_DAY_PATTERN)).pipe(\n  Schema.brand(\"UsageDay\"),\n);\nexport type UsageDay = typeof UsageDay.Type;\n\n/**\n * Why a bucket's cost is what it is.\n *\n * - `providerReported` - the transcript carried an explicit cost figure.\n * - `modelPriced` - we matched the model against the LiteLLM rate table.\n * - `unpriced` - tokens are known, rates are not. Counted in totals, excluded\n *   from cost.\n */\nexport const UsageCostSource = Schema.Literals([\"providerReported\", \"modelPriced\", \"unpriced\"]);\nexport type UsageCostSource = typeof UsageCostSource.Type;\n\n/**\n * Token counts for a bucket.\n *\n * `cachedInputTokens` and `cacheCreationTokens` are disjoint from\n * `uncachedInputTokens`; summing all three gives total input. `reasoningTokens`\n * is a *subset* of `outputTokens` (Codex reports it that way, and Anthropic\n * folds thinking into output), so it must never be added on top.\n */\nexport const UsageTokenTotals = Schema.Struct({\n  uncachedInputTokens: NonNegativeInt,\n  cachedInputTokens: NonNegativeInt,\n  cacheCreationTokens: NonNegativeInt,\n  outputTokens: NonNegativeInt,\n  reasoningTokens: NonNegativeInt,\n});\nexport type UsageTokenTotals = typeof UsageTokenTotals.Type;\n\n/**\n * One `(day, provider, model)` cell.\n *\n * `costUsd` is the raw API-equivalent cost of these tokens. It is not money\n * spent: subscription plans bill separately. `unpricedRecords` counts records\n * whose tokens are included in the token totals but which contributed nothing\n * to `costUsd`.\n */\nexport const UsageBucket = Schema.Struct({\n  day: UsageDay,\n  provider: UsageProviderKind,\n  model: TrimmedNonEmptyString,\n  totals: UsageTokenTotals,\n  costUsd: Schema.Number,\n  /**\n   * What the cached input would have cost at full input rates minus what it\n   * actually cost. Requires the rate table, so it is computed alongside cost\n   * rather than derived on the client.\n   */\n  cacheSavingsUsd: Schema.Number,\n  costSource: UsageCostSource,\n  /** Distinct assistant responses, after de-duplication. */\n  records: NonNegativeInt,\n  unpricedRecords: NonNegativeInt,\n  /** Distinct transcript sessions that contributed to this cell. */\n  sessions: NonNegativeInt,\n});\nexport type UsageBucket = typeof UsageBucket.Type;\n\n/**\n * Identifies the physical transcript directory a source read from.\n *\n * Two environments on the same machine (worktree servers, for example) resolve\n * the same provider home and would otherwise double count. The client drops\n * duplicate fingerprints before merging.\n */\nexport const UsageSourceFingerprint = Schema.Struct({\n  hostId: TrimmedNonEmptyString,\n  provider: UsageProviderKind,\n  resolvedHomePath: TrimmedNonEmptyString,\n  /**\n   * Filesystem identity of the transcript directory, as `device:inode`.\n   *\n   * Hostname and path alone are not enough: every Mac in a fleet resolves\n   * `/Users/<user>/.claude`, so two machines that happen to share a hostname\n   * would look like one source and have their usage silently dropped. The\n   * device/inode pair is stable for two servers reading the same directory and\n   * effectively never collides across machines. Empty when it cannot be read.\n   */\n  volumeId: Schema.String,\n});\nexport type UsageSourceFingerprint = typeof UsageSourceFingerprint.Type;\n\nexport const UsageSourceStatus = Schema.Literals([\"ok\", \"missing\", \"partial\", \"failed\"]);\nexport type UsageSourceStatus = typeof UsageSourceStatus.Type;\n\nexport const UsageSource = Schema.Struct({\n  fingerprint: UsageSourceFingerprint,\n  status: UsageSourceStatus,\n  scannedFiles: NonNegativeInt,\n  skippedFiles: NonNegativeInt,\n  /** Records that parsed but carried no recognisable usage payload. */\n  malformedRecords: NonNegativeInt,\n  /**\n   * Distinct transcript sessions seen under this directory. Buckets also carry\n   * per-bucket session counts, but a session spans days and models, so summing\n   * those overcounts; this is the figure clients should total.\n   */\n  distinctSessions: NonNegativeInt,\n  message: Schema.NullOr(TrimmedNonEmptyString),\n});\nexport type UsageSource = typeof UsageSource.Type;\n\nexport const UsagePricingStatus = Schema.Literals([\"fresh\", \"cached\", \"unavailable\"]);\nexport type UsagePricingStatus = typeof UsagePricingStatus.Type;\n\n/**\n * Provenance for the rate table, so the UI can be honest about how good the\n * cost figures are.\n */\nexport const UsagePricing = Schema.Struct({\n  status: UsagePricingStatus,\n  source: TrimmedNonEmptyString,\n  fetchedAt: Schema.NullOr(Schema.String),\n  knownModels: NonNegativeInt,\n});\nexport type UsagePricing = typeof UsagePricing.Type;\n\nexport const UsageSummaryInput = Schema.Struct({\n  /** Inclusive first day of the window, in `timeZone`. */\n  sinceDay: UsageDay,\n  /** Inclusive last day of the window, in `timeZone`. */\n  untilDay: UsageDay,\n  /**\n   * IANA zone the client wants days bucketed in. An offset would be wrong for\n   * any window that crosses a DST boundary.\n   */\n  timeZone: TrimmedNonEmptyString,\n});\nexport type UsageSummaryInput = typeof UsageSummaryInput.Type;\n\nexport const UsageSummary = Schema.Struct({\n  contractVersion: Schema.Number,\n  readAt: Schema.String,\n  timeZone: TrimmedNonEmptyString,\n  sinceDay: UsageDay,\n  untilDay: UsageDay,\n  buckets: Schema.Array(UsageBucket),\n  sources: Schema.Array(UsageSource),\n  pricing: UsagePricing,\n  /** Wall-clock cost of the scan, surfaced in diagnostics. */\n  scanDurationMs: NonNegativeInt,\n});\nexport type UsageSummary = typeof UsageSummary.Type;\n\nexport class UsageReadError extends Schema.TaggedErrorClass<UsageReadError>()(\"UsageReadError\", {\n  reason: Schema.Literals([\"scanFailed\", \"invalidWindow\"]),\n  /** Stable, bounded description. The underlying failure travels in `cause`. */\n  detail: TrimmedNonEmptyString,\n  cause: Schema.optional(Schema.Defect()),\n}) {\n  override get message(): string {\n    return `Usage read failed (${this.reason}): ${this.detail}`;\n  }\n}\n","import * as Schema from \"effect/Schema\";\nimport * as Rpc from \"effect/unstable/rpc/Rpc\";\nimport * as RpcGroup from \"effect/unstable/rpc/RpcGroup\";\n\nimport { ExternalLauncherError, LaunchEditorInput } from \"./editor.ts\";\nimport {\n  AuthAccessStreamError,\n  AuthAccessStreamEvent,\n  EnvironmentAuthorizationError,\n} from \"./auth.ts\";\nimport {\n  BackgroundPolicySnapshot,\n  ClientActivityReportInput,\n  HostPowerSnapshot,\n} from \"./background.ts\";\nimport {\n  FilesystemBrowseInput,\n  FilesystemBrowseResult,\n  FilesystemBrowseError,\n} from \"./filesystem.ts\";\nimport { AssetAccessError, AssetCreateUrlInput, AssetCreateUrlResult } from \"./assets.ts\";\nimport {\n  GitActionProgressEvent,\n  VcsSwitchRefInput,\n  VcsSwitchRefResult,\n  GitCommandError,\n  VcsCreateRefInput,\n  VcsCreateRefResult,\n  VcsCreateWorktreeInput,\n  VcsCreateWorktreeResult,\n  VcsInitInput,\n  VcsListRefsInput,\n  VcsListRefsResult,\n  GitManagerServiceError,\n  GitPreparePullRequestThreadInput,\n  GitPreparePullRequestThreadResult,\n  VcsPullInput,\n  GitPullRequestRefInput,\n  VcsPullResult,\n  VcsRemoveWorktreeInput,\n  GitResolvePullRequestResult,\n  GitRunStackedActionInput,\n  VcsStatusInput,\n  VcsStatusResult,\n  VcsStatusStreamEvent,\n} from \"./git.ts\";\nimport {\n  ReviewDiffFileContentsInput,\n  ReviewDiffFileContentsResult,\n  ReviewDiffPreviewError,\n  ReviewDiffPreviewInput,\n  ReviewDiffPreviewResult,\n} from \"./review.ts\";\nimport { KeybindingsConfigError } from \"./keybindings.ts\";\nimport {\n  ClientOrchestrationCommand,\n  ORCHESTRATION_WS_METHODS,\n  OrchestrationDispatchCommandError,\n  OrchestrationGetFullThreadDiffError,\n  OrchestrationGetFullThreadDiffInput,\n  OrchestrationGetSnapshotError,\n  OrchestrationSearchThreadsError,\n  OrchestrationSearchThreadsInput,\n  OrchestrationGetTurnDiffError,\n  OrchestrationGetTurnDiffInput,\n  OrchestrationRpcSchemas,\n  OrchestrationGetWorkflowScriptError,\n} from \"./orchestration.ts\";\nimport { ProviderInstanceId } from \"./providerInstance.ts\";\nimport {\n  RelayClientInstallFailedError,\n  RelayClientInstallProgressEventSchema,\n  RelayClientStatusSchema,\n} from \"./relayClient.ts\";\nimport {\n  ProjectListEntriesError,\n  ProjectListEntriesInput,\n  ProjectListEntriesResult,\n  ProjectReadFileError,\n  ProjectReadFileInput,\n  ProjectReadFileResult,\n  ProjectSearchContentsError,\n  ProjectSearchContentsInput,\n  ProjectSearchContentsResult,\n  ProjectSearchEntriesError,\n  ProjectSearchEntriesInput,\n  ProjectSearchEntriesResult,\n  ProjectWriteFileError,\n  ProjectWriteFileInput,\n  ProjectWriteFileResult,\n} from \"./project.ts\";\nimport {\n  TerminalAttachInput,\n  TerminalAttachStreamEvent,\n  TerminalClearInput,\n  TerminalCloseInput,\n  TerminalError,\n  TerminalEvent,\n  TerminalMetadataStreamEvent,\n  TerminalOpenInput,\n  TerminalResizeInput,\n  TerminalRestartInput,\n  TerminalSessionSnapshot,\n  TerminalWriteInput,\n} from \"./terminal.ts\";\nimport {\n  DiscoveredLocalServerList,\n  PreviewCloseInput,\n  PreviewError,\n  PreviewEvent,\n  PreviewListInput,\n  PreviewListResult,\n  PreviewNavigateInput,\n  PreviewOpenInput,\n  PreviewRefreshInput,\n  PreviewReportStatusInput,\n  PreviewResizeInput,\n  PreviewSessionSnapshot,\n} from \"./preview.ts\";\nimport {\n  PreviewAutomationError,\n  PreviewAutomationHost,\n  PreviewAutomationHostFocus,\n  PreviewAutomationResponse,\n  PreviewAutomationStreamEvent,\n} from \"./previewAutomation.ts\";\nimport {\n  ServerConfigStreamEvent,\n  ServerConfig,\n  ServerProviderUpdateError,\n  ServerProviderUpdateInput,\n  ServerLifecycleStreamEvent,\n  ServerRemoveKeybindingInput,\n  ServerRemoveKeybindingResult,\n  ServerProviderUpdatedPayload,\n  ServerSelfUpdateError,\n  ServerSelfUpdateInput,\n  ServerSelfUpdateProgressEvent,\n  ServerSelfUpdateResult,\n  ServerTraceDiagnosticsResult,\n  ServerProcessDiagnosticsResult,\n  ServerProcessResourceHistoryInput,\n  ServerProcessResourceHistoryResult,\n  ServerSignalProcessInput,\n  ServerSignalProcessResult,\n  ServerUpsertKeybindingInput,\n  ServerUpsertKeybindingResult,\n} from \"./server.ts\";\nimport {\n  ResourceTelemetryHistory,\n  ResourceTelemetryHistoryInput,\n  ResourceTelemetryRetryResult,\n  ResourceTelemetrySnapshot,\n} from \"./resourceTelemetry.ts\";\nimport { UsageReadError, UsageSummary, UsageSummaryInput } from \"./usage.ts\";\nimport { ServerSettings, ServerSettingsError, ServerSettingsPatch } from \"./settings.ts\";\nimport {\n  SourceControlCloneRepositoryInput,\n  SourceControlCloneRepositoryResult,\n  SourceControlDiscoveryResult,\n  SourceControlPublishRepositoryInput,\n  SourceControlPublishRepositoryResult,\n  SourceControlRepositoryError,\n  SourceControlRepositoryInfo,\n  SourceControlRepositoryLookupInput,\n} from \"./sourceControl.ts\";\nimport { VcsError } from \"./vcs.ts\";\n\nexport const WS_METHODS = {\n  // Project registry methods\n  projectsList: \"projects.list\",\n  projectsAdd: \"projects.add\",\n  projectsRemove: \"projects.remove\",\n  projectsListEntries: \"projects.listEntries\",\n  projectsReadFile: \"projects.readFile\",\n  projectsSearchContents: \"projects.searchContents\",\n  projectsSearchEntries: \"projects.searchEntries\",\n  projectsWriteFile: \"projects.writeFile\",\n\n  // Shell methods\n  shellOpenInEditor: \"shell.openInEditor\",\n\n  // Filesystem methods\n  filesystemBrowse: \"filesystem.browse\",\n  assetsCreateUrl: \"assets.createUrl\",\n\n  // VCS methods\n  vcsPull: \"vcs.pull\",\n  vcsRefreshStatus: \"vcs.refreshStatus\",\n  vcsListRefs: \"vcs.listRefs\",\n  vcsCreateWorktree: \"vcs.createWorktree\",\n  vcsRemoveWorktree: \"vcs.removeWorktree\",\n  vcsCreateRef: \"vcs.createRef\",\n  vcsSwitchRef: \"vcs.switchRef\",\n  vcsInit: \"vcs.init\",\n\n  // Git workflow methods\n  gitRunStackedAction: \"git.runStackedAction\",\n  gitResolvePullRequest: \"git.resolvePullRequest\",\n  gitPreparePullRequestThread: \"git.preparePullRequestThread\",\n\n  // Review methods\n  reviewGetDiffPreview: \"review.getDiffPreview\",\n  reviewGetDiffFileContents: \"review.getDiffFileContents\",\n\n  // Terminal methods\n  terminalOpen: \"terminal.open\",\n  terminalAttach: \"terminal.attach\",\n  terminalWrite: \"terminal.write\",\n  terminalResize: \"terminal.resize\",\n  terminalClear: \"terminal.clear\",\n  terminalRestart: \"terminal.restart\",\n  terminalClose: \"terminal.close\",\n\n  // Preview methods\n  previewOpen: \"preview.open\",\n  previewNavigate: \"preview.navigate\",\n  previewResize: \"preview.resize\",\n  previewRefresh: \"preview.refresh\",\n  previewClose: \"preview.close\",\n  previewList: \"preview.list\",\n  previewReportStatus: \"preview.reportStatus\",\n  previewAutomationConnect: \"previewAutomation.connect\",\n  previewAutomationRespond: \"previewAutomation.respond\",\n  previewAutomationFocusHost: \"previewAutomation.focusHost\",\n\n  // Server meta\n  serverProbe: \"server.probe\",\n  serverGetConfig: \"server.getConfig\",\n  serverRefreshProviders: \"server.refreshProviders\",\n  serverUpdateProvider: \"server.updateProvider\",\n  serverUpdateServer: \"server.updateServer\",\n  serverUpdateServerWithProgress: \"server.updateServerWithProgress\",\n  serverUpsertKeybinding: \"server.upsertKeybinding\",\n  serverRemoveKeybinding: \"server.removeKeybinding\",\n  serverGetSettings: \"server.getSettings\",\n  serverUpdateSettings: \"server.updateSettings\",\n  serverDiscoverSourceControl: \"server.discoverSourceControl\",\n  serverGetTraceDiagnostics: \"server.getTraceDiagnostics\",\n  serverGetProcessDiagnostics: \"server.getProcessDiagnostics\",\n  serverGetProcessResourceHistory: \"server.getProcessResourceHistory\",\n  serverGetResourceTelemetryHistory: \"server.getResourceTelemetryHistory\",\n  serverRetryResourceTelemetry: \"server.retryResourceTelemetry\",\n  serverSignalProcess: \"server.signalProcess\",\n  serverReportClientActivity: \"server.reportClientActivity\",\n  serverReportHostPowerState: \"server.reportHostPowerState\",\n  serverGetBackgroundPolicy: \"server.getBackgroundPolicy\",\n  serverGetUsageSummary: \"server.getUsageSummary\",\n\n  // Cloud environment methods\n  cloudGetRelayClientStatus: \"cloud.getRelayClientStatus\",\n  cloudInstallRelayClient: \"cloud.installRelayClient\",\n\n  // Source control methods\n  sourceControlLookupRepository: \"sourceControl.lookupRepository\",\n  sourceControlCloneRepository: \"sourceControl.cloneRepository\",\n  sourceControlPublishRepository: \"sourceControl.publishRepository\",\n\n  // Streaming subscriptions\n  subscribeVcsStatus: \"subscribeVcsStatus\",\n  subscribeTerminalEvents: \"subscribeTerminalEvents\",\n  subscribeTerminalMetadata: \"subscribeTerminalMetadata\",\n  subscribePreviewEvents: \"subscribePreviewEvents\",\n  subscribeDiscoveredLocalServers: \"subscribeDiscoveredLocalServers\",\n  subscribeServerConfig: \"subscribeServerConfig\",\n  subscribeServerLifecycle: \"subscribeServerLifecycle\",\n  subscribeAuthAccess: \"subscribeAuthAccess\",\n  subscribeBackgroundPolicy: \"subscribeBackgroundPolicy\",\n  subscribeResourceTelemetry: \"subscribeResourceTelemetry\",\n} as const;\n\nexport const WsServerUpsertKeybindingRpc = Rpc.make(WS_METHODS.serverUpsertKeybinding, {\n  payload: ServerUpsertKeybindingInput,\n  success: ServerUpsertKeybindingResult,\n  error: Schema.Union([KeybindingsConfigError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerRemoveKeybindingRpc = Rpc.make(WS_METHODS.serverRemoveKeybinding, {\n  payload: ServerRemoveKeybindingInput,\n  success: ServerRemoveKeybindingResult,\n  error: Schema.Union([KeybindingsConfigError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerProbeRpc = Rpc.make(WS_METHODS.serverProbe, {\n  payload: Schema.Struct({}),\n  success: Schema.Struct({}),\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetConfigRpc = Rpc.make(WS_METHODS.serverGetConfig, {\n  payload: Schema.Struct({}),\n  success: ServerConfig,\n  error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerRefreshProvidersRpc = Rpc.make(WS_METHODS.serverRefreshProviders, {\n  payload: Schema.Struct({\n    /**\n     * When supplied, only refresh this specific provider instance. When\n     * omitted, refresh all configured instances — the legacy `refresh()`\n     * behaviour retained for transports that still dispatch untargeted\n     * refreshes.\n     */\n    instanceId: Schema.optional(ProviderInstanceId),\n  }),\n  success: ServerProviderUpdatedPayload,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerUpdateProviderRpc = Rpc.make(WS_METHODS.serverUpdateProvider, {\n  payload: ServerProviderUpdateInput,\n  success: ServerProviderUpdatedPayload,\n  error: Schema.Union([ServerProviderUpdateError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerUpdateServerRpc = Rpc.make(WS_METHODS.serverUpdateServer, {\n  payload: ServerSelfUpdateInput,\n  success: ServerSelfUpdateResult,\n  error: Schema.Union([ServerSelfUpdateError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerUpdateServerWithProgressRpc = Rpc.make(\n  WS_METHODS.serverUpdateServerWithProgress,\n  {\n    payload: ServerSelfUpdateInput,\n    success: ServerSelfUpdateProgressEvent,\n    error: Schema.Union([ServerSelfUpdateError, EnvironmentAuthorizationError]),\n    stream: true,\n  },\n);\n\nexport const WsServerGetSettingsRpc = Rpc.make(WS_METHODS.serverGetSettings, {\n  payload: Schema.Struct({}),\n  success: ServerSettings,\n  error: Schema.Union([ServerSettingsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSettings, {\n  payload: Schema.Struct({ patch: ServerSettingsPatch }),\n  success: ServerSettings,\n  error: Schema.Union([ServerSettingsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsServerDiscoverSourceControlRpc = Rpc.make(WS_METHODS.serverDiscoverSourceControl, {\n  payload: Schema.Struct({}),\n  success: SourceControlDiscoveryResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetTraceDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetTraceDiagnostics, {\n  payload: Schema.Struct({}),\n  success: ServerTraceDiagnosticsResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetProcessDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetProcessDiagnostics, {\n  payload: Schema.Struct({}),\n  success: ServerProcessDiagnosticsResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetProcessResourceHistoryRpc = Rpc.make(\n  WS_METHODS.serverGetProcessResourceHistory,\n  {\n    payload: ServerProcessResourceHistoryInput,\n    success: ServerProcessResourceHistoryResult,\n    error: EnvironmentAuthorizationError,\n  },\n);\n\nexport const WsServerGetResourceTelemetryHistoryRpc = Rpc.make(\n  WS_METHODS.serverGetResourceTelemetryHistory,\n  {\n    payload: ResourceTelemetryHistoryInput,\n    success: ResourceTelemetryHistory,\n    error: EnvironmentAuthorizationError,\n  },\n);\n\nexport const WsServerRetryResourceTelemetryRpc = Rpc.make(WS_METHODS.serverRetryResourceTelemetry, {\n  payload: Schema.Struct({}),\n  success: ResourceTelemetryRetryResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetUsageSummaryRpc = Rpc.make(WS_METHODS.serverGetUsageSummary, {\n  payload: UsageSummaryInput,\n  success: UsageSummary,\n  error: Schema.Union([EnvironmentAuthorizationError, UsageReadError]),\n});\n\nexport const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess, {\n  payload: ServerSignalProcessInput,\n  success: ServerSignalProcessResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsCloudGetRelayClientStatusRpc = Rpc.make(WS_METHODS.cloudGetRelayClientStatus, {\n  payload: Schema.Struct({}),\n  success: RelayClientStatusSchema,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsCloudInstallRelayClientRpc = Rpc.make(WS_METHODS.cloudInstallRelayClient, {\n  payload: Schema.Struct({}),\n  success: RelayClientInstallProgressEventSchema,\n  error: Schema.Union([RelayClientInstallFailedError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsServerReportClientActivityRpc = Rpc.make(WS_METHODS.serverReportClientActivity, {\n  payload: ClientActivityReportInput,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerReportHostPowerStateRpc = Rpc.make(WS_METHODS.serverReportHostPowerState, {\n  payload: HostPowerSnapshot,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsServerGetBackgroundPolicyRpc = Rpc.make(WS_METHODS.serverGetBackgroundPolicy, {\n  payload: Schema.Struct({}),\n  success: BackgroundPolicySnapshot,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsSourceControlLookupRepositoryRpc = Rpc.make(\n  WS_METHODS.sourceControlLookupRepository,\n  {\n    payload: SourceControlRepositoryLookupInput,\n    success: SourceControlRepositoryInfo,\n    error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsSourceControlCloneRepositoryRpc = Rpc.make(WS_METHODS.sourceControlCloneRepository, {\n  payload: SourceControlCloneRepositoryInput,\n  success: SourceControlCloneRepositoryResult,\n  error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),\n});\n\nexport const WsSourceControlPublishRepositoryRpc = Rpc.make(\n  WS_METHODS.sourceControlPublishRepository,\n  {\n    payload: SourceControlPublishRepositoryInput,\n    success: SourceControlPublishRepositoryResult,\n    error: Schema.Union([SourceControlRepositoryError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsProjectsSearchEntriesRpc = Rpc.make(WS_METHODS.projectsSearchEntries, {\n  payload: ProjectSearchEntriesInput,\n  success: ProjectSearchEntriesResult,\n  error: Schema.Union([ProjectSearchEntriesError, EnvironmentAuthorizationError]),\n});\n\nexport const WsProjectsSearchContentsRpc = Rpc.make(WS_METHODS.projectsSearchContents, {\n  payload: ProjectSearchContentsInput,\n  success: ProjectSearchContentsResult,\n  error: Schema.Union([ProjectSearchContentsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsProjectsListEntriesRpc = Rpc.make(WS_METHODS.projectsListEntries, {\n  payload: ProjectListEntriesInput,\n  success: ProjectListEntriesResult,\n  error: Schema.Union([ProjectListEntriesError, EnvironmentAuthorizationError]),\n});\n\nexport const WsProjectsReadFileRpc = Rpc.make(WS_METHODS.projectsReadFile, {\n  payload: ProjectReadFileInput,\n  success: ProjectReadFileResult,\n  error: Schema.Union([ProjectReadFileError, EnvironmentAuthorizationError]),\n});\n\nexport const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, {\n  payload: ProjectWriteFileInput,\n  success: ProjectWriteFileResult,\n  error: Schema.Union([ProjectWriteFileError, EnvironmentAuthorizationError]),\n});\n\nexport const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {\n  payload: LaunchEditorInput,\n  error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),\n});\n\nexport const WsFilesystemBrowseRpc = Rpc.make(WS_METHODS.filesystemBrowse, {\n  payload: FilesystemBrowseInput,\n  success: FilesystemBrowseResult,\n  error: Schema.Union([FilesystemBrowseError, EnvironmentAuthorizationError]),\n});\n\nexport const WsAssetsCreateUrlRpc = Rpc.make(WS_METHODS.assetsCreateUrl, {\n  payload: AssetCreateUrlInput,\n  success: AssetCreateUrlResult,\n  error: Schema.Union([AssetAccessError, EnvironmentAuthorizationError]),\n});\n\nexport const WsSubscribeVcsStatusRpc = Rpc.make(WS_METHODS.subscribeVcsStatus, {\n  payload: VcsStatusInput,\n  success: VcsStatusStreamEvent,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsVcsPullRpc = Rpc.make(WS_METHODS.vcsPull, {\n  payload: VcsPullInput,\n  success: VcsPullResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsRefreshStatusRpc = Rpc.make(WS_METHODS.vcsRefreshStatus, {\n  payload: VcsStatusInput,\n  success: VcsStatusResult,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n});\n\nexport const WsGitRunStackedActionRpc = Rpc.make(WS_METHODS.gitRunStackedAction, {\n  payload: GitRunStackedActionInput,\n  success: GitActionProgressEvent,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsGitResolvePullRequestRpc = Rpc.make(WS_METHODS.gitResolvePullRequest, {\n  payload: GitPullRequestRefInput,\n  success: GitResolvePullRequestResult,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n});\n\nexport const WsGitPreparePullRequestThreadRpc = Rpc.make(WS_METHODS.gitPreparePullRequestThread, {\n  payload: GitPreparePullRequestThreadInput,\n  success: GitPreparePullRequestThreadResult,\n  error: Schema.Union([GitManagerServiceError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsListRefsRpc = Rpc.make(WS_METHODS.vcsListRefs, {\n  payload: VcsListRefsInput,\n  success: VcsListRefsResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsCreateWorktreeRpc = Rpc.make(WS_METHODS.vcsCreateWorktree, {\n  payload: VcsCreateWorktreeInput,\n  success: VcsCreateWorktreeResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsRemoveWorktreeRpc = Rpc.make(WS_METHODS.vcsRemoveWorktree, {\n  payload: VcsRemoveWorktreeInput,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsCreateRefRpc = Rpc.make(WS_METHODS.vcsCreateRef, {\n  payload: VcsCreateRefInput,\n  success: VcsCreateRefResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsSwitchRefRpc = Rpc.make(WS_METHODS.vcsSwitchRef, {\n  payload: VcsSwitchRefInput,\n  success: VcsSwitchRefResult,\n  error: Schema.Union([GitCommandError, EnvironmentAuthorizationError]),\n});\n\nexport const WsVcsInitRpc = Rpc.make(WS_METHODS.vcsInit, {\n  payload: VcsInitInput,\n  error: Schema.Union([VcsError, EnvironmentAuthorizationError]),\n});\n\n/**\n * Ephemeral live diff preview for compact/mobile surfaces.\n * Not the persisted T3 Review model. Future review sessions should use\n * review.open* + review.getSnapshot.\n */\nexport const WsReviewGetDiffPreviewRpc = Rpc.make(WS_METHODS.reviewGetDiffPreview, {\n  payload: ReviewDiffPreviewInput,\n  success: ReviewDiffPreviewResult,\n  error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsReviewGetDiffFileContentsRpc = Rpc.make(WS_METHODS.reviewGetDiffFileContents, {\n  payload: ReviewDiffFileContentsInput,\n  success: ReviewDiffFileContentsResult,\n  error: Schema.Union([ReviewDiffPreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalOpenRpc = Rpc.make(WS_METHODS.terminalOpen, {\n  payload: TerminalOpenInput,\n  success: TerminalSessionSnapshot,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalAttachRpc = Rpc.make(WS_METHODS.terminalAttach, {\n  payload: TerminalAttachInput,\n  success: TerminalAttachStreamEvent,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsTerminalWriteRpc = Rpc.make(WS_METHODS.terminalWrite, {\n  payload: TerminalWriteInput,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalResizeRpc = Rpc.make(WS_METHODS.terminalResize, {\n  payload: TerminalResizeInput,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalClearRpc = Rpc.make(WS_METHODS.terminalClear, {\n  payload: TerminalClearInput,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalRestartRpc = Rpc.make(WS_METHODS.terminalRestart, {\n  payload: TerminalRestartInput,\n  success: TerminalSessionSnapshot,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsTerminalCloseRpc = Rpc.make(WS_METHODS.terminalClose, {\n  payload: TerminalCloseInput,\n  error: Schema.Union([TerminalError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewOpenRpc = Rpc.make(WS_METHODS.previewOpen, {\n  payload: PreviewOpenInput,\n  success: PreviewSessionSnapshot,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewNavigateRpc = Rpc.make(WS_METHODS.previewNavigate, {\n  payload: PreviewNavigateInput,\n  success: PreviewSessionSnapshot,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewResizeRpc = Rpc.make(WS_METHODS.previewResize, {\n  payload: PreviewResizeInput,\n  success: PreviewSessionSnapshot,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewRefreshRpc = Rpc.make(WS_METHODS.previewRefresh, {\n  payload: PreviewRefreshInput,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewCloseRpc = Rpc.make(WS_METHODS.previewClose, {\n  payload: PreviewCloseInput,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewListRpc = Rpc.make(WS_METHODS.previewList, {\n  payload: PreviewListInput,\n  success: PreviewListResult,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsPreviewReportStatusRpc = Rpc.make(WS_METHODS.previewReportStatus, {\n  payload: PreviewReportStatusInput,\n  error: Schema.Union([PreviewError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewAutomationConnectRpc = Rpc.make(WS_METHODS.previewAutomationConnect, {\n  payload: PreviewAutomationHost,\n  success: PreviewAutomationStreamEvent,\n  error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsPreviewAutomationRespondRpc = Rpc.make(WS_METHODS.previewAutomationRespond, {\n  payload: PreviewAutomationResponse,\n  error: Schema.Union([PreviewAutomationError, EnvironmentAuthorizationError]),\n});\n\nexport const WsPreviewAutomationFocusHostRpc = Rpc.make(WS_METHODS.previewAutomationFocusHost, {\n  payload: PreviewAutomationHostFocus,\n  error: EnvironmentAuthorizationError,\n});\n\nexport const WsSubscribePreviewEventsRpc = Rpc.make(WS_METHODS.subscribePreviewEvents, {\n  payload: Schema.Struct({}),\n  success: PreviewEvent,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeDiscoveredLocalServersRpc = Rpc.make(\n  WS_METHODS.subscribeDiscoveredLocalServers,\n  {\n    payload: Schema.Struct({}),\n    success: DiscoveredLocalServerList,\n    error: EnvironmentAuthorizationError,\n    stream: true,\n  },\n);\n\nexport const WsOrchestrationDispatchCommandRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.dispatchCommand,\n  {\n    payload: ClientOrchestrationCommand,\n    success: OrchestrationRpcSchemas.dispatchCommand.output,\n    error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsOrchestrationGetWorkflowScriptRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.getWorkflowScript,\n  {\n    payload: OrchestrationRpcSchemas.getWorkflowScript.input,\n    success: OrchestrationRpcSchemas.getWorkflowScript.output,\n    error: Schema.Union([OrchestrationGetWorkflowScriptError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsOrchestrationGetTurnDiffRpc = Rpc.make(ORCHESTRATION_WS_METHODS.getTurnDiff, {\n  payload: OrchestrationGetTurnDiffInput,\n  success: OrchestrationRpcSchemas.getTurnDiff.output,\n  error: Schema.Union([OrchestrationGetTurnDiffError, EnvironmentAuthorizationError]),\n});\n\nexport const WsOrchestrationGetFullThreadDiffRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.getFullThreadDiff,\n  {\n    payload: OrchestrationGetFullThreadDiffInput,\n    success: OrchestrationRpcSchemas.getFullThreadDiff.output,\n    error: Schema.Union([OrchestrationGetFullThreadDiffError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsOrchestrationSearchThreadsRpc = Rpc.make(ORCHESTRATION_WS_METHODS.searchThreads, {\n  payload: OrchestrationSearchThreadsInput,\n  success: OrchestrationRpcSchemas.searchThreads.output,\n  error: Schema.Union([OrchestrationSearchThreadsError, EnvironmentAuthorizationError]),\n});\n\nexport const WsOrchestrationGetArchivedShellSnapshotRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,\n  {\n    payload: OrchestrationRpcSchemas.getArchivedShellSnapshot.input,\n    success: OrchestrationRpcSchemas.getArchivedShellSnapshot.output,\n    error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),\n  },\n);\n\nexport const WsOrchestrationSubscribeShellRpc = Rpc.make(ORCHESTRATION_WS_METHODS.subscribeShell, {\n  payload: OrchestrationRpcSchemas.subscribeShell.input,\n  success: OrchestrationRpcSchemas.subscribeShell.output,\n  error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsOrchestrationSubscribeThreadRpc = Rpc.make(\n  ORCHESTRATION_WS_METHODS.subscribeThread,\n  {\n    payload: OrchestrationRpcSchemas.subscribeThread.input,\n    success: OrchestrationRpcSchemas.subscribeThread.output,\n    error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),\n    stream: true,\n  },\n);\n\nexport const WsSubscribeTerminalEventsRpc = Rpc.make(WS_METHODS.subscribeTerminalEvents, {\n  payload: Schema.Struct({}),\n  success: TerminalEvent,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeTerminalMetadataRpc = Rpc.make(WS_METHODS.subscribeTerminalMetadata, {\n  payload: Schema.Struct({}),\n  success: TerminalMetadataStreamEvent,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeServerConfigRpc = Rpc.make(WS_METHODS.subscribeServerConfig, {\n  payload: Schema.Struct({}),\n  success: ServerConfigStreamEvent,\n  error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsSubscribeServerLifecycleRpc = Rpc.make(WS_METHODS.subscribeServerLifecycle, {\n  payload: Schema.Struct({}),\n  success: ServerLifecycleStreamEvent,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeAuthAccessRpc = Rpc.make(WS_METHODS.subscribeAuthAccess, {\n  payload: Schema.Struct({}),\n  success: AuthAccessStreamEvent,\n  error: Schema.Union([AuthAccessStreamError, EnvironmentAuthorizationError]),\n  stream: true,\n});\n\nexport const WsSubscribeBackgroundPolicyRpc = Rpc.make(WS_METHODS.subscribeBackgroundPolicy, {\n  payload: Schema.Struct({}),\n  success: BackgroundPolicySnapshot,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsSubscribeResourceTelemetryRpc = Rpc.make(WS_METHODS.subscribeResourceTelemetry, {\n  payload: Schema.Struct({}),\n  success: ResourceTelemetrySnapshot,\n  error: EnvironmentAuthorizationError,\n  stream: true,\n});\n\nexport const WsRpcGroup = RpcGroup.make(\n  WsServerProbeRpc,\n  WsServerGetConfigRpc,\n  WsServerRefreshProvidersRpc,\n  WsServerUpdateProviderRpc,\n  WsServerUpdateServerRpc,\n  WsServerUpdateServerWithProgressRpc,\n  WsServerUpsertKeybindingRpc,\n  WsServerRemoveKeybindingRpc,\n  WsServerGetSettingsRpc,\n  WsServerUpdateSettingsRpc,\n  WsServerDiscoverSourceControlRpc,\n  WsServerGetTraceDiagnosticsRpc,\n  WsServerGetProcessDiagnosticsRpc,\n  WsServerGetProcessResourceHistoryRpc,\n  WsServerGetResourceTelemetryHistoryRpc,\n  WsServerRetryResourceTelemetryRpc,\n  WsServerGetUsageSummaryRpc,\n  WsServerSignalProcessRpc,\n  WsServerReportClientActivityRpc,\n  WsServerReportHostPowerStateRpc,\n  WsServerGetBackgroundPolicyRpc,\n  WsCloudGetRelayClientStatusRpc,\n  WsCloudInstallRelayClientRpc,\n  WsSourceControlLookupRepositoryRpc,\n  WsSourceControlCloneRepositoryRpc,\n  WsSourceControlPublishRepositoryRpc,\n  WsProjectsListEntriesRpc,\n  WsProjectsReadFileRpc,\n  WsProjectsSearchContentsRpc,\n  WsProjectsSearchEntriesRpc,\n  WsProjectsWriteFileRpc,\n  WsShellOpenInEditorRpc,\n  WsFilesystemBrowseRpc,\n  WsAssetsCreateUrlRpc,\n  WsSubscribeVcsStatusRpc,\n  WsVcsPullRpc,\n  WsVcsRefreshStatusRpc,\n  WsGitRunStackedActionRpc,\n  WsGitResolvePullRequestRpc,\n  WsGitPreparePullRequestThreadRpc,\n  WsVcsListRefsRpc,\n  WsVcsCreateWorktreeRpc,\n  WsVcsRemoveWorktreeRpc,\n  WsVcsCreateRefRpc,\n  WsVcsSwitchRefRpc,\n  WsVcsInitRpc,\n  WsReviewGetDiffPreviewRpc,\n  WsReviewGetDiffFileContentsRpc,\n  WsTerminalOpenRpc,\n  WsTerminalAttachRpc,\n  WsTerminalWriteRpc,\n  WsTerminalResizeRpc,\n  WsTerminalClearRpc,\n  WsTerminalRestartRpc,\n  WsTerminalCloseRpc,\n  WsSubscribeTerminalEventsRpc,\n  WsSubscribeTerminalMetadataRpc,\n  WsPreviewOpenRpc,\n  WsPreviewNavigateRpc,\n  WsPreviewResizeRpc,\n  WsPreviewRefreshRpc,\n  WsPreviewCloseRpc,\n  WsPreviewListRpc,\n  WsPreviewReportStatusRpc,\n  WsPreviewAutomationConnectRpc,\n  WsPreviewAutomationRespondRpc,\n  WsPreviewAutomationFocusHostRpc,\n  WsSubscribePreviewEventsRpc,\n  WsSubscribeDiscoveredLocalServersRpc,\n  WsSubscribeServerConfigRpc,\n  WsSubscribeServerLifecycleRpc,\n  WsSubscribeAuthAccessRpc,\n  WsSubscribeBackgroundPolicyRpc,\n  WsSubscribeResourceTelemetryRpc,\n  WsOrchestrationDispatchCommandRpc,\n  WsOrchestrationGetWorkflowScriptRpc,\n  WsOrchestrationGetTurnDiffRpc,\n  WsOrchestrationGetFullThreadDiffRpc,\n  WsOrchestrationSearchThreadsRpc,\n  WsOrchestrationGetArchivedShellSnapshotRpc,\n  WsOrchestrationSubscribeShellRpc,\n  WsOrchestrationSubscribeThreadRpc,\n);\n","import * as Schema from \"effect/Schema\";\n\nconst OAUTH_SCOPE_TOKEN = /^[\\u0021\\u0023-\\u005b\\u005d-\\u007e]+$/u;\n\nexport class OAuthScopeEncodingError extends Schema.TaggedErrorClass<OAuthScopeEncodingError>()(\n  \"OAuthScopeEncodingError\",\n  {\n    scopes: Schema.Array(Schema.String),\n    invalidScopes: Schema.Array(Schema.String),\n    duplicateScopes: Schema.Array(Schema.String),\n  },\n) {\n  override get message(): string {\n    return \"OAuth scopes must be non-empty, syntactically valid, and unique.\";\n  }\n}\n\n/**\n * Decodes an RFC 6749 `scope` value as a set while preserving its first-seen\n * order for canonical responses and logs.\n */\nexport function parseOAuthScope(value: string): ReadonlyArray<string> | null {\n  if (value.length === 0) {\n    return null;\n  }\n\n  const scopes = value.split(\" \");\n  if (scopes.some((scope) => !OAUTH_SCOPE_TOKEN.test(scope))) {\n    return null;\n  }\n\n  return [...new Set(scopes)];\n}\n\nexport function encodeOAuthScope(scopes: ReadonlyArray<string>): string {\n  const invalidScopes = scopes.filter((scope) => !OAUTH_SCOPE_TOKEN.test(scope));\n  const seen = new Set<string>();\n  const duplicateScopes = new Set<string>();\n  for (const scope of scopes) {\n    if (seen.has(scope)) duplicateScopes.add(scope);\n    seen.add(scope);\n  }\n\n  if (scopes.length === 0 || invalidScopes.length > 0 || duplicateScopes.size > 0) {\n    throw new OAuthScopeEncodingError({\n      scopes,\n      invalidScopes,\n      duplicateScopes: [...duplicateScopes],\n    });\n  }\n  return scopes.join(\" \");\n}\n\nexport function oauthScopeSetEquals(value: string, expectedScopes: ReadonlyArray<string>): boolean {\n  const scopes = parseOAuthScope(value);\n  return (\n    scopes !== null &&\n    scopes.length === new Set(expectedScopes).size &&\n    scopes.every((scope) => expectedScopes.includes(scope))\n  );\n}\n\nexport function parseAllowedOAuthScope<Scope extends string>(input: {\n  readonly value: string;\n  readonly allowedScopes: ReadonlySet<Scope>;\n}): ReadonlyArray<Scope> | null {\n  const scopes = parseOAuthScope(input.value);\n  if (\n    scopes === null ||\n    !scopes.every((scope): scope is Scope => input.allowedScopes.has(scope as Scope))\n  ) {\n    return null;\n  }\n  return scopes;\n}\n","/**\n * ServerConfig - Runtime configuration services.\n *\n * Defines process-level server configuration and networking helpers used by\n * startup and runtime layers.\n *\n * @module ServerConfig\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as LogLevel from \"effect/LogLevel\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nexport const DEFAULT_PORT = 3773;\n\nexport const RuntimeMode = Schema.Literals([\"web\", \"desktop\"]);\nexport type RuntimeMode = typeof RuntimeMode.Type;\n\nexport const StartupPresentation = Schema.Literals([\"browser\", \"headless\"]);\nexport type StartupPresentation = typeof StartupPresentation.Type;\n\n/**\n * ServerDerivedPaths - Derived paths from the base directory.\n */\nexport interface ServerDerivedPaths {\n  readonly stateDir: string;\n  readonly dbPath: string;\n  readonly keybindingsConfigPath: string;\n  readonly settingsPath: string;\n  readonly providerStatusCacheDir: string;\n  readonly worktreesDir: string;\n  readonly attachmentsDir: string;\n  readonly logsDir: string;\n  readonly serverLogPath: string;\n  readonly serverTracePath: string;\n  readonly providerLogsDir: string;\n  readonly providerEventLogPath: string;\n  readonly terminalLogsDir: string;\n  readonly anonymousIdPath: string;\n  readonly environmentIdPath: string;\n  readonly serverRuntimeStatePath: string;\n  readonly secretsDir: string;\n}\n\nexport interface DeriveServerPathsOptions {\n  readonly baseDirIsExplicit?: boolean;\n}\n\n/**\n * ServerConfig - Service tag for server runtime configuration.\n */\nexport class ServerConfig extends Context.Service<\n  ServerConfig,\n  ServerDerivedPaths & {\n    readonly logLevel: LogLevel.LogLevel;\n    readonly traceMinLevel: LogLevel.LogLevel;\n    readonly traceTimingEnabled: boolean;\n    readonly traceBatchWindowMs: number;\n    readonly traceMaxBytes: number;\n    readonly traceMaxFiles: number;\n    readonly otlpTracesUrl: string | undefined;\n    readonly otlpMetricsUrl: string | undefined;\n    readonly otlpExportIntervalMs: number;\n    readonly otlpServiceName: string;\n    readonly mode: RuntimeMode;\n    readonly port: number;\n    readonly host: string | undefined;\n    readonly cwd: string;\n    readonly baseDir: string;\n    readonly staticDir: string | undefined;\n    readonly devUrl: URL | undefined;\n    readonly devAllowedOrigins: ReadonlyArray<string>;\n    readonly noBrowser: boolean;\n    readonly startupPresentation: StartupPresentation;\n    readonly desktopBootstrapToken: string | undefined;\n    readonly desktopTelemetryFd?: number | undefined;\n    readonly desktopTelemetryControlFd?: number | undefined;\n    readonly resourceMonitorPath?: string | undefined;\n    readonly autoBootstrapProjectFromCwd: boolean;\n    readonly logWebSocketEvents: boolean;\n    readonly tailscaleServeEnabled: boolean;\n    readonly tailscaleServePort: number;\n  }\n>()(\"t3/config/ServerConfig\") {\n  /** @deprecated Import and use `layerTest` from this module. */\n  static readonly layerTest = (\n    cwd: string,\n    baseDirOrPrefix: string | { readonly prefix: string },\n  ) => layerTest(cwd, baseDirOrPrefix);\n}\n\nexport const make = (config: ServerConfig[\"Service\"]) => ServerConfig.of(config);\n\nexport const layer = (config: ServerConfig[\"Service\"]) => Layer.succeed(ServerConfig, make(config));\n\nexport const deriveServerPaths = Effect.fn(function* (\n  baseDir: ServerConfig[\"Service\"][\"baseDir\"],\n  devUrl: ServerConfig[\"Service\"][\"devUrl\"],\n  options: DeriveServerPathsOptions = {},\n): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {\n  const { join } = yield* Path.Path;\n  const stateDir = join(\n    baseDir,\n    devUrl !== undefined && !options.baseDirIsExplicit ? \"dev\" : \"userdata\",\n  );\n  const dbPath = join(stateDir, \"state.sqlite\");\n  const attachmentsDir = join(stateDir, \"attachments\");\n  const logsDir = join(stateDir, \"logs\");\n  const providerLogsDir = join(logsDir, \"provider\");\n  const providerStatusCacheDir = join(baseDir, \"caches\");\n  return {\n    stateDir,\n    dbPath,\n    keybindingsConfigPath: join(stateDir, \"keybindings.json\"),\n    settingsPath: join(stateDir, \"settings.json\"),\n    providerStatusCacheDir,\n    worktreesDir: join(baseDir, \"worktrees\"),\n    attachmentsDir,\n    logsDir,\n    serverLogPath: join(logsDir, \"server.log\"),\n    serverTracePath: join(logsDir, \"server.trace.ndjson\"),\n    providerLogsDir,\n    providerEventLogPath: join(providerLogsDir, \"events.log\"),\n    terminalLogsDir: join(logsDir, \"terminals\"),\n    anonymousIdPath: join(stateDir, \"anonymous-id\"),\n    environmentIdPath: join(stateDir, \"environment-id\"),\n    serverRuntimeStatePath: join(stateDir, \"server-runtime.json\"),\n    secretsDir: join(stateDir, \"secrets\"),\n  };\n});\n\nexport const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  yield* Effect.all(\n    [\n      fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),\n      fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),\n      fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),\n      fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),\n      fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),\n      fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),\n      fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),\n    ],\n    { concurrency: \"unbounded\" },\n  );\n});\n\nconst makeTest = Effect.fn(\"ServerConfig.makeTest\")(function* (\n  cwd: string,\n  baseDirOrPrefix: string | { readonly prefix: string },\n) {\n  const devUrl = undefined;\n  const fs = yield* FileSystem.FileSystem;\n  const baseDir =\n    typeof baseDirOrPrefix === \"string\"\n      ? baseDirOrPrefix\n      : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });\n  const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);\n  yield* ensureServerDirectories(derivedPaths);\n\n  return ServerConfig.of({\n    logLevel: \"Error\",\n    traceMinLevel: \"Info\",\n    traceTimingEnabled: true,\n    traceBatchWindowMs: 200,\n    traceMaxBytes: 10 * 1024 * 1024,\n    traceMaxFiles: 10,\n    otlpTracesUrl: undefined,\n    otlpMetricsUrl: undefined,\n    otlpExportIntervalMs: 10_000,\n    otlpServiceName: \"t3-server\",\n    cwd,\n    baseDir,\n    ...derivedPaths,\n    mode: \"web\",\n    autoBootstrapProjectFromCwd: false,\n    logWebSocketEvents: false,\n    tailscaleServeEnabled: false,\n    tailscaleServePort: 443,\n    port: 0,\n    host: undefined,\n    desktopBootstrapToken: undefined,\n    desktopTelemetryFd: undefined,\n    desktopTelemetryControlFd: undefined,\n    resourceMonitorPath: undefined,\n    staticDir: undefined,\n    devUrl,\n    devAllowedOrigins: [],\n    noBrowser: false,\n    startupPresentation: \"browser\",\n  });\n});\n\nexport const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>\n  Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));\n\nexport const resolveStaticDir = Effect.fn(function* () {\n  const { join, resolve } = yield* Path.Path;\n  const { exists } = yield* FileSystem.FileSystem;\n  const bundledClient = resolve(join(import.meta.dirname, \"client\"));\n  const bundledStat = yield* exists(join(bundledClient, \"index.html\")).pipe(\n    Effect.orElseSucceed(() => false),\n  );\n  if (bundledStat) {\n    return bundledClient;\n  }\n\n  const monorepoClient = resolve(join(import.meta.dirname, \"../../web/dist\"));\n  const monorepoStat = yield* exists(join(monorepoClient, \"index.html\")).pipe(\n    Effect.orElseSucceed(() => false),\n  );\n  if (monorepoStat) {\n    return monorepoClient;\n  }\n  return undefined;\n});\n","import type {\n  AuthClientMetadata,\n  AuthClientMetadataDeviceType,\n  AuthClientPresentationMetadata,\n} from \"@t3tools/contracts\";\nimport type * as HttpServerRequest from \"effect/unstable/http/HttpServerRequest\";\nimport * as NodeCrypto from \"node:crypto\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as Result from \"effect/Result\";\n\nconst SESSION_COOKIE_NAME = \"t3_session\";\n\n/**\n * Cookies are scoped by host but *not* by port, so any two servers that can be\n * live on one hostname at once need separate names — otherwise the second\n * clobbers the first's session and both sides see \"Invalid session token\n * signature\" until someone clears cookies by hand.\n *\n * Two populations qualify, for the same reason but from different causes:\n *\n * - **Dev servers** (`devUrl` set), which run several at a time across worktrees.\n * - **Desktop**, which scans upward from 3773 for a free port and binds\n *   127.0.0.1, so a second instance lands on a different port and the same host.\n *\n * Hosted deployments keep the stable production name: their public port can\n * change between releases, and scoping it would log every user out.\n */\nexport function resolveSessionCookieName(input: {\n  readonly mode: \"web\" | \"desktop\";\n  readonly port: number;\n  readonly host: string | undefined;\n  readonly instanceKey: string;\n  readonly development: boolean;\n}): string {\n  if (input.mode === \"desktop\") {\n    return `${SESSION_COOKIE_NAME}_${input.port}`;\n  }\n\n  if (!input.development && isRemoteReachableHost(input.host)) {\n    return SESSION_COOKIE_NAME;\n  }\n\n  // Cookies are scoped by host, not port. Loopback development servers need an\n  // instance-specific name or parallel agents overwrite each other's session,\n  // and a server that later reuses the port receives a token signed elsewhere.\n  const instanceHash = NodeCrypto.createHash(\"sha256\")\n    .update(input.instanceKey)\n    .digest(\"hex\")\n    .slice(0, 12);\n  return `${SESSION_COOKIE_NAME}_${input.port}_${instanceHash}`;\n}\n\nexport function isRemoteReachableHost(host: string | undefined): boolean {\n  if (host === \"0.0.0.0\" || host === \"::\" || host === \"[::]\") {\n    return true;\n  }\n  if (!host || host.length === 0) {\n    return false;\n  }\n  return !(\n    host === \"localhost\" ||\n    host === \"127.0.0.1\" ||\n    host === \"::1\" ||\n    host === \"[::1]\" ||\n    host.startsWith(\"127.\")\n  );\n}\n\nexport function base64UrlEncode(input: string | Uint8Array): string {\n  return typeof input === \"string\"\n    ? Encoding.encodeBase64Url(new TextEncoder().encode(input))\n    : Encoding.encodeBase64Url(input);\n}\n\nexport function base64UrlDecodeUtf8(input: string): string {\n  return Result.getOrThrow(Encoding.decodeBase64UrlString(input));\n}\n\nexport function signPayload(payload: string, secret: Uint8Array): string {\n  return NodeCrypto.createHmac(\"sha256\", Buffer.from(secret)).update(payload).digest(\"base64url\");\n}\n\nexport function timingSafeEqualBase64Url(left: string, right: string): boolean {\n  const leftBuffer = Buffer.from(left, \"base64url\");\n  const rightBuffer = Buffer.from(right, \"base64url\");\n  if (leftBuffer.length !== rightBuffer.length) {\n    return false;\n  }\n  return NodeCrypto.timingSafeEqual(leftBuffer, rightBuffer);\n}\n\nfunction normalizeNonEmptyString(value: string | null | undefined): string | undefined {\n  if (typeof value !== \"string\") {\n    return undefined;\n  }\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizeIpAddress(value: string | null | undefined): string | undefined {\n  const normalized = normalizeNonEmptyString(value);\n  if (!normalized) {\n    return undefined;\n  }\n  return normalized.startsWith(\"::ffff:\") ? normalized.slice(\"::ffff:\".length) : normalized;\n}\n\nfunction inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType {\n  if (!userAgent) {\n    return \"unknown\";\n  }\n\n  const normalized = userAgent.toLowerCase();\n  if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) {\n    return \"bot\";\n  }\n  if (/ipad|tablet/.test(normalized)) {\n    return \"tablet\";\n  }\n  if (/iphone|android.+mobile|mobile/.test(normalized)) {\n    return \"mobile\";\n  }\n  return \"desktop\";\n}\n\nfunction inferBrowser(userAgent: string | undefined): string | undefined {\n  if (!userAgent) {\n    return undefined;\n  }\n  const normalized = userAgent.toLowerCase();\n  if (/edg\\//.test(normalized)) return \"Edge\";\n  if (/opr\\//.test(normalized)) return \"Opera\";\n  if (/firefox\\//.test(normalized)) return \"Firefox\";\n  if (/electron\\//.test(normalized)) return \"Electron\";\n  if (/chrome\\//.test(normalized) || /crios\\//.test(normalized)) return \"Chrome\";\n  if (/safari\\//.test(normalized) && !/chrome\\//.test(normalized)) return \"Safari\";\n  return undefined;\n}\n\nfunction inferOs(userAgent: string | undefined): string | undefined {\n  if (!userAgent) {\n    return undefined;\n  }\n  const normalized = userAgent.toLowerCase();\n  if (/iphone|ipad|ipod/.test(normalized)) return \"iOS\";\n  if (/android/.test(normalized)) return \"Android\";\n  if (/mac os x|macintosh/.test(normalized)) return \"macOS\";\n  if (/windows nt/.test(normalized)) return \"Windows\";\n  if (/linux/.test(normalized)) return \"Linux\";\n  return undefined;\n}\n\nfunction readRemoteAddressFromSource(source: unknown): string | undefined {\n  if (!source || typeof source !== \"object\") {\n    return undefined;\n  }\n\n  const candidate = source as {\n    readonly remoteAddress?: string | null;\n    readonly socket?: {\n      readonly remoteAddress?: string | null;\n    };\n  };\n\n  return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress);\n}\n\nexport function deriveAuthClientMetadata(input: {\n  readonly request: HttpServerRequest.HttpServerRequest;\n  readonly presented?: AuthClientPresentationMetadata;\n}): AuthClientMetadata {\n  const userAgent = normalizeNonEmptyString(input.request.headers[\"user-agent\"]);\n  const ipAddress = readRemoteAddressFromSource(input.request.source);\n  const os = input.presented?.os ?? inferOs(userAgent);\n  const browser = inferBrowser(userAgent);\n  return {\n    ...(input.presented?.label ? { label: input.presented.label } : {}),\n    ...(ipAddress ? { ipAddress } : {}),\n    ...(userAgent ? { userAgent } : {}),\n    deviceType: input.presented?.deviceType ?? inferDeviceType(userAgent),\n    ...(os ? { os } : {}),\n    ...(browser ? { browser } : {}),\n  };\n}\n","import type { ServerAuthDescriptor } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport { isRemoteReachableHost, resolveSessionCookieName } from \"./utils.ts\";\n\nexport class EnvironmentAuthPolicy extends Context.Service<\n  EnvironmentAuthPolicy,\n  {\n    readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;\n  }\n>()(\"t3/auth/EnvironmentAuthPolicy\") {}\n\nexport const make = Effect.gen(function* () {\n  const config = yield* ServerConfig.ServerConfig;\n  const isRemoteReachable = isRemoteReachableHost(config.host);\n\n  const policy =\n    config.mode === \"desktop\"\n      ? isRemoteReachable\n        ? \"remote-reachable\"\n        : \"desktop-managed-local\"\n      : isRemoteReachable\n        ? \"remote-reachable\"\n        : \"loopback-browser\";\n\n  const bootstrapMethods: ServerAuthDescriptor[\"bootstrapMethods\"] =\n    policy === \"desktop-managed-local\"\n      ? [\"desktop-bootstrap\"]\n      : config.mode === \"desktop\" && policy === \"remote-reachable\"\n        ? [\"desktop-bootstrap\", \"one-time-token\"]\n        : [\"one-time-token\"];\n\n  const descriptor: ServerAuthDescriptor = {\n    policy,\n    bootstrapMethods,\n    sessionMethods: [\"browser-session-cookie\", \"bearer-access-token\", \"dpop-access-token\"],\n    sessionCookieName: resolveSessionCookieName({\n      mode: config.mode,\n      port: config.port,\n      host: config.host,\n      instanceKey: config.stateDir,\n      development: config.devUrl !== undefined,\n    }),\n  };\n\n  return EnvironmentAuthPolicy.of({\n    getDescriptor: () =>\n      Effect.succeed(descriptor).pipe(Effect.withSpan(\"EnvironmentAuthPolicy.getDescriptor\")),\n  });\n});\n\nexport const layer = Layer.effect(EnvironmentAuthPolicy, make);\n","import * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\n\nfunction summarizeSchemaIssue(issue: SchemaIssue.Issue): string {\n  switch (issue._tag) {\n    case \"Filter\":\n    case \"Encoding\":\n    case \"Pointer\":\n      return `${issue._tag}(${summarizeSchemaIssue(issue.issue)})`;\n    case \"Composite\":\n    case \"AnyOf\":\n      return `${issue._tag}(${issue.issues.map(summarizeSchemaIssue).join(\",\")})`;\n    default:\n      return issue._tag;\n  }\n}\n\n// ===============================\n// Core Persistence Errors\n// ===============================\n\nexport const PersistenceErrorCorrelation = Schema.Union([\n  Schema.Struct({ sessionId: Schema.String }),\n  Schema.Struct({ currentSessionId: Schema.String }),\n  Schema.Struct({ pairingLinkId: Schema.String }),\n  Schema.Struct({ threadId: Schema.String }),\n]);\nexport type PersistenceErrorCorrelation = typeof PersistenceErrorCorrelation.Type;\n\nexport class PersistenceSqlError extends Schema.TaggedErrorClass<PersistenceSqlError>()(\n  \"PersistenceSqlError\",\n  {\n    operation: Schema.String,\n    detail: Schema.optional(Schema.String),\n    correlation: Schema.optional(PersistenceErrorCorrelation),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return this.detail === undefined\n      ? `SQL error in ${this.operation}`\n      : `SQL error in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceDecodeError>()(\n  \"PersistenceDecodeError\",\n  {\n    operation: Schema.String,\n    issue: Schema.String,\n    correlation: Schema.optional(PersistenceErrorCorrelation),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  static fromSchemaError(\n    operation: string,\n    cause: Schema.SchemaError,\n    correlation?: PersistenceErrorCorrelation,\n  ): PersistenceDecodeError {\n    return new PersistenceDecodeError({\n      operation,\n      issue: summarizeSchemaIssue(cause.issue),\n      ...(correlation === undefined ? {} : { correlation }),\n      cause,\n    });\n  }\n\n  override get message(): string {\n    return `Decode error in ${this.operation}: ${this.issue}`;\n  }\n}\nconst isPersistenceSqlError = Schema.is(PersistenceSqlError);\nconst isPersistenceDecodeError = Schema.is(PersistenceDecodeError);\n\n// Kept for orchestration/projection call sites, which are being revamped separately.\nexport function toPersistenceSqlError(operation: string) {\n  return (cause: unknown): PersistenceSqlError =>\n    new PersistenceSqlError({\n      operation,\n      detail: `Failed to execute ${operation}`,\n      cause,\n    });\n}\n\n// Kept for orchestration/projection call sites, which are being revamped separately.\nexport function toPersistenceDecodeError(operation: string) {\n  return (cause: Schema.SchemaError): PersistenceDecodeError =>\n    PersistenceDecodeError.fromSchemaError(operation, cause);\n}\n\nexport const isPersistenceError = (u: unknown) =>\n  isPersistenceSqlError(u) || isPersistenceDecodeError(u);\n\n// ===============================\n// Provider Session Repository Errors\n// ===============================\n\nexport class ProviderSessionRepositoryValidationError extends Schema.TaggedErrorClass<ProviderSessionRepositoryValidationError>()(\n  \"ProviderSessionRepositoryValidationError\",\n  {\n    operation: Schema.String,\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider session repository validation failed in ${this.operation}: ${this.issue}`;\n  }\n}\n\nexport class ProviderSessionRepositoryPersistenceError extends Schema.TaggedErrorClass<ProviderSessionRepositoryPersistenceError>()(\n  \"ProviderSessionRepositoryPersistenceError\",\n  {\n    operation: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider session repository persistence error in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport type OrchestrationEventStoreError = PersistenceSqlError | PersistenceDecodeError;\n\nexport type ProviderSessionRepositoryError =\n  | ProviderSessionRepositoryValidationError\n  | ProviderSessionRepositoryPersistenceError;\n\nexport type OrchestrationCommandReceiptRepositoryError =\n  | PersistenceSqlError\n  | PersistenceDecodeError;\n\nexport type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError;\nexport type AuthPairingLinkRepositoryError = PersistenceSqlError | PersistenceDecodeError;\nexport type AuthSessionRepositoryError = PersistenceSqlError | PersistenceDecodeError;\n\nexport type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError;\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport { AuthEnvironmentScopes } from \"@t3tools/contracts\";\n\nimport {\n  type AuthPairingLinkRepositoryError,\n  PersistenceDecodeError,\n  type PersistenceErrorCorrelation,\n  PersistenceSqlError,\n} from \"./Errors.ts\";\n\nexport const AuthPairingLinkRecord = Schema.Struct({\n  id: Schema.String,\n  credential: Schema.String,\n  method: Schema.Literals([\"desktop-bootstrap\", \"one-time-token\"]),\n  scopes: Schema.fromJsonString(AuthEnvironmentScopes),\n  subject: Schema.String,\n  label: Schema.NullOr(Schema.String),\n  proofKeyThumbprint: Schema.NullOr(Schema.String),\n  createdAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n  consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n  revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n});\nexport type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type;\n\nexport const CreateAuthPairingLinkInput = Schema.Struct({\n  id: Schema.String,\n  credential: Schema.String,\n  method: Schema.Literals([\"desktop-bootstrap\", \"one-time-token\"]),\n  scopes: AuthEnvironmentScopes,\n  subject: Schema.String,\n  label: Schema.NullOr(Schema.String),\n  proofKeyThumbprint: Schema.NullOr(Schema.String),\n  createdAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n});\nexport type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type;\n\nexport const ConsumeAuthPairingLinkInput = Schema.Struct({\n  credential: Schema.String,\n  proofKeyThumbprint: Schema.NullOr(Schema.String),\n  consumedAt: Schema.DateTimeUtcFromString,\n  now: Schema.DateTimeUtcFromString,\n});\nexport type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type;\n\nexport const ListActiveAuthPairingLinksInput = Schema.Struct({\n  now: Schema.DateTimeUtcFromString,\n});\nexport type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type;\n\nexport const RevokeAuthPairingLinkInput = Schema.Struct({\n  id: Schema.String,\n  revokedAt: Schema.DateTimeUtcFromString,\n});\nexport type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type;\n\nexport const GetAuthPairingLinkByCredentialInput = Schema.Struct({\n  credential: Schema.String,\n});\nexport type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type;\n\nconst AuthPairingLinkRawDbRow = Schema.Struct({\n  id: Schema.String,\n  credential: Schema.Unknown,\n  method: Schema.Unknown,\n  scopes: Schema.Unknown,\n  subject: Schema.Unknown,\n  label: Schema.Unknown,\n  proofKeyThumbprint: Schema.Unknown,\n  createdAt: Schema.Unknown,\n  expiresAt: Schema.Unknown,\n  consumedAt: Schema.Unknown,\n  revokedAt: Schema.Unknown,\n});\n\nconst decodeAuthPairingLinkDbRow = Schema.decodeUnknownEffect(AuthPairingLinkRecord);\n\nexport class AuthPairingLinkRepository extends Context.Service<\n  AuthPairingLinkRepository,\n  {\n    readonly create: (\n      input: CreateAuthPairingLinkInput,\n    ) => Effect.Effect<void, AuthPairingLinkRepositoryError>;\n    readonly consumeAvailable: (\n      input: ConsumeAuthPairingLinkInput,\n    ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;\n    readonly listActive: (\n      input: ListActiveAuthPairingLinksInput,\n    ) => Effect.Effect<ReadonlyArray<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;\n    readonly revoke: (\n      input: RevokeAuthPairingLinkInput,\n    ) => Effect.Effect<boolean, AuthPairingLinkRepositoryError>;\n    readonly getByCredential: (\n      input: GetAuthPairingLinkByCredentialInput,\n    ) => Effect.Effect<Option.Option<AuthPairingLinkRecord>, AuthPairingLinkRepositoryError>;\n  }\n>()(\"t3/persistence/AuthPairingLinks/AuthPairingLinkRepository\") {}\n\nfunction toPersistenceSqlOrDecodeError(\n  sqlOperation: string,\n  decodeOperation: string,\n  correlation?: PersistenceErrorCorrelation,\n) {\n  return (cause: unknown): AuthPairingLinkRepositoryError =>\n    Schema.isSchemaError(cause)\n      ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)\n      : new PersistenceSqlError({\n          operation: sqlOperation,\n          ...(correlation === undefined ? {} : { correlation }),\n          cause,\n        });\n}\n\nexport const make = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const createPairingLinkRow = SqlSchema.void({\n    Request: CreateAuthPairingLinkInput,\n    execute: (input) =>\n      sql`\n        INSERT INTO auth_pairing_links (\n          id,\n          credential,\n          method,\n          scopes,\n          subject,\n          label,\n          proof_key_thumbprint,\n          created_at,\n          expires_at,\n          consumed_at,\n          revoked_at\n        )\n        VALUES (\n          ${input.id},\n          ${input.credential},\n          ${input.method},\n          ${JSON.stringify(input.scopes)},\n          ${input.subject},\n          ${input.label},\n          ${input.proofKeyThumbprint},\n          ${input.createdAt},\n          ${input.expiresAt},\n          NULL,\n          NULL\n        )\n      `,\n  });\n\n  const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({\n    Request: ConsumeAuthPairingLinkInput,\n    Result: AuthPairingLinkRawDbRow,\n    execute: ({ credential, proofKeyThumbprint, consumedAt, now }) =>\n      sql`\n        UPDATE auth_pairing_links\n        SET consumed_at = ${consumedAt}\n        WHERE credential = ${credential}\n          AND revoked_at IS NULL\n          AND consumed_at IS NULL\n          AND expires_at > ${now}\n          AND (\n            proof_key_thumbprint IS NULL\n            OR proof_key_thumbprint = ${proofKeyThumbprint}\n          )\n        RETURNING\n          id AS \"id\",\n          credential AS \"credential\",\n          method AS \"method\",\n          scopes AS \"scopes\",\n          subject AS \"subject\",\n          label AS \"label\",\n          proof_key_thumbprint AS \"proofKeyThumbprint\",\n          created_at AS \"createdAt\",\n          expires_at AS \"expiresAt\",\n          consumed_at AS \"consumedAt\",\n          revoked_at AS \"revokedAt\"\n      `,\n  });\n\n  const listActivePairingLinkRows = SqlSchema.findAll({\n    Request: ListActiveAuthPairingLinksInput,\n    Result: AuthPairingLinkRawDbRow,\n    execute: ({ now }) =>\n      sql`\n        SELECT\n          id AS \"id\",\n          credential AS \"credential\",\n          method AS \"method\",\n          scopes AS \"scopes\",\n          subject AS \"subject\",\n          label AS \"label\",\n          proof_key_thumbprint AS \"proofKeyThumbprint\",\n          created_at AS \"createdAt\",\n          expires_at AS \"expiresAt\",\n          consumed_at AS \"consumedAt\",\n          revoked_at AS \"revokedAt\"\n        FROM auth_pairing_links\n        WHERE revoked_at IS NULL\n          AND consumed_at IS NULL\n          AND expires_at > ${now}\n        ORDER BY created_at DESC, id DESC\n      `,\n  });\n\n  const revokePairingLinkRow = SqlSchema.findAll({\n    Request: RevokeAuthPairingLinkInput,\n    Result: Schema.Struct({ id: Schema.String }),\n    execute: ({ id, revokedAt }) =>\n      sql`\n        UPDATE auth_pairing_links\n        SET revoked_at = ${revokedAt}\n        WHERE id = ${id}\n          AND revoked_at IS NULL\n          AND consumed_at IS NULL\n        RETURNING id AS \"id\"\n      `,\n  });\n\n  const getPairingLinkRowByCredential = SqlSchema.findOneOption({\n    Request: GetAuthPairingLinkByCredentialInput,\n    Result: AuthPairingLinkRawDbRow,\n    execute: ({ credential }) =>\n      sql`\n        SELECT\n          id AS \"id\",\n          credential AS \"credential\",\n          method AS \"method\",\n          scopes AS \"scopes\",\n          subject AS \"subject\",\n          label AS \"label\",\n          proof_key_thumbprint AS \"proofKeyThumbprint\",\n          created_at AS \"createdAt\",\n          expires_at AS \"expiresAt\",\n          consumed_at AS \"consumedAt\",\n          revoked_at AS \"revokedAt\"\n        FROM auth_pairing_links\n        WHERE credential = ${credential}\n      `,\n  });\n\n  const create: AuthPairingLinkRepository[\"Service\"][\"create\"] = (input) =>\n    createPairingLinkRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.create:query\",\n          \"AuthPairingLinkRepository.create:encodeRequest\",\n          { pairingLinkId: input.id },\n        ),\n      ),\n    );\n\n  const consumeAvailable: AuthPairingLinkRepository[\"Service\"][\"consumeAvailable\"] = (input) =>\n    consumeAvailablePairingLinkRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.consumeAvailable:query\",\n          \"AuthPairingLinkRepository.consumeAvailable:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((rowOption) =>\n        Option.match(rowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            decodeAuthPairingLinkDbRow(row).pipe(\n              Effect.mapError((cause) =>\n                PersistenceDecodeError.fromSchemaError(\n                  \"AuthPairingLinkRepository.consumeAvailable:decodeRow\",\n                  cause,\n                  { pairingLinkId: row.id },\n                ),\n              ),\n              Effect.map(Option.some),\n            ),\n        }),\n      ),\n    );\n\n  const listActive: AuthPairingLinkRepository[\"Service\"][\"listActive\"] = (input) =>\n    listActivePairingLinkRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.listActive:query\",\n          \"AuthPairingLinkRepository.listActive:decodeRows\",\n        ),\n      ),\n      Effect.flatMap((rows) =>\n        Effect.forEach(rows, (row) =>\n          decodeAuthPairingLinkDbRow(row).pipe(\n            Effect.mapError((cause) =>\n              PersistenceDecodeError.fromSchemaError(\n                \"AuthPairingLinkRepository.listActive:decodeRows\",\n                cause,\n                { pairingLinkId: row.id },\n              ),\n            ),\n          ),\n        ),\n      ),\n    );\n\n  const revoke: AuthPairingLinkRepository[\"Service\"][\"revoke\"] = (input) =>\n    revokePairingLinkRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.revoke:query\",\n          \"AuthPairingLinkRepository.revoke:decodeRows\",\n          { pairingLinkId: input.id },\n        ),\n      ),\n      Effect.map((rows) => rows.length > 0),\n    );\n\n  const getByCredential: AuthPairingLinkRepository[\"Service\"][\"getByCredential\"] = (input) =>\n    getPairingLinkRowByCredential(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthPairingLinkRepository.getByCredential:query\",\n          \"AuthPairingLinkRepository.getByCredential:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((rowOption) =>\n        Option.match(rowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            decodeAuthPairingLinkDbRow(row).pipe(\n              Effect.mapError((cause) =>\n                PersistenceDecodeError.fromSchemaError(\n                  \"AuthPairingLinkRepository.getByCredential:decodeRow\",\n                  cause,\n                  { pairingLinkId: row.id },\n                ),\n              ),\n              Effect.map(Option.some),\n            ),\n        }),\n      ),\n    );\n\n  return {\n    create,\n    consumeAvailable,\n    listActive,\n    revoke,\n    getByCredential,\n  } satisfies AuthPairingLinkRepository[\"Service\"];\n});\n\nexport const layer = Layer.effect(AuthPairingLinkRepository, make);\n","import {\n  AuthAdministrativeScopes,\n  AuthStandardClientScopes,\n  type AuthEnvironmentScope,\n  type AuthPairingLink,\n  type ServerAuthBootstrapMethod,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport * as AuthPairingLinks from \"../persistence/AuthPairingLinks.ts\";\n\nexport interface BootstrapGrant {\n  readonly method: ServerAuthBootstrapMethod;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly subject: string;\n  readonly label?: string;\n  readonly proofKeyThumbprint?: string;\n  readonly expiresAt: DateTime.DateTime;\n}\n\nexport class UnknownBootstrapCredentialError extends Schema.TaggedErrorClass<UnknownBootstrapCredentialError>()(\n  \"UnknownBootstrapCredentialError\",\n  {},\n) {\n  override get message(): string {\n    return \"Unknown bootstrap credential.\";\n  }\n}\n\nexport class ExpiredBootstrapCredentialError extends Schema.TaggedErrorClass<ExpiredBootstrapCredentialError>()(\n  \"ExpiredBootstrapCredentialError\",\n  {},\n) {\n  override get message(): string {\n    return \"Bootstrap credential expired.\";\n  }\n}\n\nexport class BootstrapCredentialProofKeyMismatchError extends Schema.TaggedErrorClass<BootstrapCredentialProofKeyMismatchError>()(\n  \"BootstrapCredentialProofKeyMismatchError\",\n  {},\n) {\n  override get message(): string {\n    return \"Bootstrap credential proof key mismatch.\";\n  }\n}\n\nexport class UnavailableBootstrapCredentialError extends Schema.TaggedErrorClass<UnavailableBootstrapCredentialError>()(\n  \"UnavailableBootstrapCredentialError\",\n  {},\n) {\n  override get message(): string {\n    return \"Bootstrap credential is no longer available.\";\n  }\n}\n\nexport const BootstrapCredentialInvalidError = Schema.Union([\n  UnknownBootstrapCredentialError,\n  ExpiredBootstrapCredentialError,\n  BootstrapCredentialProofKeyMismatchError,\n  UnavailableBootstrapCredentialError,\n]);\nexport type BootstrapCredentialInvalidError = typeof BootstrapCredentialInvalidError.Type;\nexport const isBootstrapCredentialInvalidError = Schema.is(BootstrapCredentialInvalidError);\n\nexport class ActivePairingLinksLoadError extends Schema.TaggedErrorClass<ActivePairingLinksLoadError>()(\n  \"ActivePairingLinksLoadError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to load active pairing links.\";\n  }\n}\n\nexport class PairingLinkRevokeError extends Schema.TaggedErrorClass<PairingLinkRevokeError>()(\n  \"PairingLinkRevokeError\",\n  {\n    pairingLinkId: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to revoke pairing link '${this.pairingLinkId}'.`;\n  }\n}\n\nexport class PairingCredentialIssueError extends Schema.TaggedErrorClass<PairingCredentialIssueError>()(\n  \"PairingCredentialIssueError\",\n  {\n    pairingLinkId: Schema.String,\n    subject: Schema.String,\n    label: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to issue pairing credential '${this.pairingLinkId}' for '${this.subject}'.`;\n  }\n}\n\nexport class PairingCredentialRandomGenerationError extends Schema.TaggedErrorClass<PairingCredentialRandomGenerationError>()(\n  \"PairingCredentialRandomGenerationError\",\n  {\n    operation: Schema.Literals([\"generate-id\", \"generate-token\"]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to generate pairing credential data during '${this.operation}'.`;\n  }\n}\n\nexport class BootstrapCredentialConsumeError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeError>()(\n  \"BootstrapCredentialConsumeError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to consume bootstrap credential.\";\n  }\n}\n\nexport class BootstrapCredentialConsumeAvailableError extends Schema.TaggedErrorClass<BootstrapCredentialConsumeAvailableError>()(\n  \"BootstrapCredentialConsumeAvailableError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to atomically consume an available bootstrap credential.\";\n  }\n}\n\nexport class BootstrapCredentialLookupError extends Schema.TaggedErrorClass<BootstrapCredentialLookupError>()(\n  \"BootstrapCredentialLookupError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to look up bootstrap credential state.\";\n  }\n}\n\nexport const BootstrapCredentialInternalError = Schema.Union([\n  ActivePairingLinksLoadError,\n  PairingLinkRevokeError,\n  PairingCredentialIssueError,\n  PairingCredentialRandomGenerationError,\n  BootstrapCredentialConsumeError,\n  BootstrapCredentialConsumeAvailableError,\n  BootstrapCredentialLookupError,\n]);\nexport type BootstrapCredentialInternalError = typeof BootstrapCredentialInternalError.Type;\nexport const isBootstrapCredentialInternalError = Schema.is(BootstrapCredentialInternalError);\n\nexport const BootstrapCredentialError = Schema.Union([\n  BootstrapCredentialInvalidError,\n  BootstrapCredentialInternalError,\n]);\nexport type BootstrapCredentialError = typeof BootstrapCredentialError.Type;\nexport const isBootstrapCredentialError = Schema.is(BootstrapCredentialError);\n\nexport interface IssuedBootstrapCredential {\n  readonly id: string;\n  readonly credential: string;\n  readonly label?: string;\n  readonly proofKeyThumbprint?: string;\n  readonly expiresAt: DateTime.Utc;\n}\n\nexport type BootstrapCredentialChange =\n  | {\n      readonly type: \"pairingLinkUpserted\";\n      readonly pairingLink: AuthPairingLink;\n    }\n  | {\n      readonly type: \"pairingLinkRemoved\";\n      readonly id: string;\n    };\n\nexport class PairingGrantStore extends Context.Service<\n  PairingGrantStore,\n  {\n    readonly issueOneTimeToken: (input?: {\n      readonly ttl?: Duration.Duration;\n      readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;\n      readonly subject?: string;\n      readonly label?: string;\n      readonly proofKeyThumbprint?: string;\n      /**\n       * \"startup\" marks the credential the server mints for itself at boot,\n       * which gets the long dev TTL when a dev URL is configured.\n       */\n      readonly purpose?: \"startup\";\n    }) => Effect.Effect<IssuedBootstrapCredential, BootstrapCredentialInternalError>;\n    readonly listActive: () => Effect.Effect<\n      ReadonlyArray<AuthPairingLink>,\n      BootstrapCredentialInternalError\n    >;\n    readonly streamChanges: Stream.Stream<BootstrapCredentialChange>;\n    readonly revoke: (id: string) => Effect.Effect<boolean, BootstrapCredentialInternalError>;\n    readonly consume: (\n      credential: string,\n      input?: {\n        readonly proofKeyThumbprint?: string;\n      },\n    ) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;\n  }\n>()(\"t3/auth/PairingGrantStore\") {}\n\ninterface StoredBootstrapGrant extends BootstrapGrant {\n  readonly remainingUses: number | \"unbounded\";\n}\n\ntype ConsumeResult =\n  | {\n      readonly _tag: \"error\";\n      readonly reason: \"not-found\" | \"expired\";\n      readonly error: BootstrapCredentialError;\n    }\n  | {\n      readonly _tag: \"success\";\n      readonly grant: BootstrapGrant;\n    };\n\nconst DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);\n// The desktop-bootstrap grant rides on a trusted IPC channel (fd3 or\n// stdin) at backend launch, so it doesn't have to be short-lived the\n// way a user-facing pairing link does. Letting it live for the\n// lifetime of the backend process (24h is more than long enough for\n// practical desktop use, and well under \"forever\" in case the seed\n// gets logged anywhere by accident) means a page reload past the 5-min\n// window can still recover by re-bootstrapping rather than locking\n// the user out of the backend.\nconst DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);\n// A dev server's startup token is read off a log by whoever (or whatever) is\n// driving the session, often minutes later — after a `node --watch` restart, a\n// detour into another task, or a hand-off to the person actually doing the\n// testing. Five minutes turns that into a restart-the-server loop for no\n// security benefit: the token only unlocks a local dev backend, and its holder\n// could read the log anyway. Same reasoning (and duration) as the desktop\n// bootstrap grant above. Only applies when a dev URL is configured; user-issued\n// pairing links and real servers keep the 5-minute default.\nconst DEV_STARTUP_TTL_HOURS = Duration.hours(24);\nconst PAIRING_TOKEN_ALPHABET = \"23456789ABCDEFGHJKLMNPQRSTUVWXYZ\";\nconst PAIRING_TOKEN_LENGTH = 12;\nconst PAIRING_TOKEN_REJECTION_LIMIT =\n  Math.floor(256 / PAIRING_TOKEN_ALPHABET.length) * PAIRING_TOKEN_ALPHABET.length;\n\nexport const make = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const config = yield* ServerConfig.ServerConfig;\n  const pairingLinks = yield* AuthPairingLinks.AuthPairingLinkRepository;\n  const seededGrantsRef = yield* Ref.make(new Map<string, StoredBootstrapGrant>());\n  const changesPubSub = yield* PubSub.unbounded<BootstrapCredentialChange>();\n  const generatePairingToken = Effect.gen(function* () {\n    let credential = \"\";\n    while (credential.length < PAIRING_TOKEN_LENGTH) {\n      const bytes = yield* crypto\n        .randomBytes(PAIRING_TOKEN_LENGTH)\n        .pipe(\n          Effect.mapError(\n            (cause) =>\n              new PairingCredentialRandomGenerationError({ operation: \"generate-token\", cause }),\n          ),\n        );\n      for (const byte of bytes) {\n        if (byte >= PAIRING_TOKEN_REJECTION_LIMIT) {\n          continue;\n        }\n        credential += PAIRING_TOKEN_ALPHABET[byte % PAIRING_TOKEN_ALPHABET.length]!;\n        if (credential.length === PAIRING_TOKEN_LENGTH) {\n          return credential;\n        }\n      }\n    }\n    return credential;\n  });\n\n  const seedGrant = (credential: string, grant: StoredBootstrapGrant) =>\n    Ref.update(seededGrantsRef, (current) => {\n      const next = new Map(current);\n      next.set(credential, grant);\n      return next;\n    });\n\n  const emitUpsert = (pairingLink: AuthPairingLink) =>\n    PubSub.publish(changesPubSub, {\n      type: \"pairingLinkUpserted\",\n      pairingLink,\n    }).pipe(Effect.asVoid);\n\n  const emitRemoved = (id: string) =>\n    PubSub.publish(changesPubSub, {\n      type: \"pairingLinkRemoved\",\n      id,\n    }).pipe(Effect.asVoid);\n\n  if (config.desktopBootstrapToken) {\n    const now = yield* DateTime.now;\n    yield* seedGrant(config.desktopBootstrapToken, {\n      method: \"desktop-bootstrap\",\n      scopes: AuthAdministrativeScopes,\n      subject: \"desktop-bootstrap\",\n      expiresAt: DateTime.add(now, {\n        milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),\n      }),\n      // Unbounded uses so the renderer can re-exchange the seed for a\n      // fresh bearer session after a page reload (or after the prior\n      // bearer expires). The seed itself stays inside the desktop\n      // process and the rendered page, both of which the user already\n      // implicitly trusts.\n      remainingUses: \"unbounded\",\n    });\n  }\n\n  const listActive: PairingGrantStore[\"Service\"][\"listActive\"] = Effect.fn(\n    \"PairingGrantStore.listActive\",\n  )(\n    function* () {\n      const now = yield* DateTime.now;\n      const rows = yield* pairingLinks.listActive({ now });\n\n      return rows.map((row) =>\n        row.label\n          ? ({\n              id: row.id,\n              credential: row.credential,\n              scopes: row.scopes,\n              subject: row.subject,\n              label: row.label,\n              createdAt: row.createdAt,\n              expiresAt: row.expiresAt,\n            } satisfies AuthPairingLink)\n          : ({\n              id: row.id,\n              credential: row.credential,\n              scopes: row.scopes,\n              subject: row.subject,\n              createdAt: row.createdAt,\n              expiresAt: row.expiresAt,\n            } satisfies AuthPairingLink),\n      );\n    },\n    Effect.mapError((cause) => new ActivePairingLinksLoadError({ cause })),\n  );\n\n  const revoke: PairingGrantStore[\"Service\"][\"revoke\"] = Effect.fn(\"PairingGrantStore.revoke\")(\n    function* (id) {\n      const revokedAt = yield* DateTime.now;\n      const revoked = yield* pairingLinks\n        .revoke({\n          id,\n          revokedAt,\n        })\n        .pipe(Effect.mapError((cause) => new PairingLinkRevokeError({ pairingLinkId: id, cause })));\n      if (revoked) {\n        yield* emitRemoved(id);\n      }\n      return revoked;\n    },\n  );\n\n  const issueOneTimeToken: PairingGrantStore[\"Service\"][\"issueOneTimeToken\"] = Effect.fn(\n    \"PairingGrantStore.issueOneTimeToken\",\n  )(function* (input) {\n    const id = yield* crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) => new PairingCredentialRandomGenerationError({ operation: \"generate-id\", cause }),\n      ),\n    );\n    const credential = yield* generatePairingToken;\n    const isDevStartupToken = config.devUrl !== undefined && input?.purpose === \"startup\";\n    const ttl =\n      input?.ttl ??\n      (isDevStartupToken ? DEV_STARTUP_TTL_HOURS : DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES);\n    const now = yield* DateTime.now;\n    const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) });\n    const issued: IssuedBootstrapCredential = {\n      id,\n      credential,\n      ...(input?.label ? { label: input.label } : {}),\n      ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),\n      expiresAt,\n    };\n    const subject = input?.subject ?? \"one-time-token\";\n    yield* pairingLinks\n      .create({\n        id,\n        credential,\n        method: \"one-time-token\",\n        scopes: input?.scopes ?? AuthStandardClientScopes,\n        subject,\n        label: input?.label ?? null,\n        proofKeyThumbprint: input?.proofKeyThumbprint ?? null,\n        createdAt: now,\n        expiresAt: expiresAt,\n      })\n      .pipe(\n        Effect.mapError(\n          (cause) =>\n            new PairingCredentialIssueError({\n              pairingLinkId: id,\n              subject,\n              ...(input?.label ? { label: input.label } : {}),\n              cause,\n            }),\n        ),\n      );\n    yield* emitUpsert({\n      id,\n      credential,\n      scopes: input?.scopes ?? AuthStandardClientScopes,\n      subject: input?.subject ?? \"one-time-token\",\n      ...(input?.label ? { label: input.label } : {}),\n      createdAt: now,\n      expiresAt,\n    });\n    return issued;\n  });\n\n  const consume: PairingGrantStore[\"Service\"][\"consume\"] = Effect.fn(\"PairingGrantStore.consume\")(\n    function* (credential, input) {\n      const now = yield* DateTime.now;\n      const seededResult: ConsumeResult = yield* Ref.modify(\n        seededGrantsRef,\n        (current): readonly [ConsumeResult, Map<string, StoredBootstrapGrant>] => {\n          const grant = current.get(credential);\n          if (!grant) {\n            return [\n              {\n                _tag: \"error\",\n                reason: \"not-found\",\n                error: new UnknownBootstrapCredentialError({}),\n              },\n              current,\n            ];\n          }\n\n          const next = new Map(current);\n          if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) {\n            next.delete(credential);\n            return [\n              {\n                _tag: \"error\",\n                reason: \"expired\",\n                error: new ExpiredBootstrapCredentialError({}),\n              },\n              next,\n            ];\n          }\n\n          if (grant.proofKeyThumbprint && grant.proofKeyThumbprint !== input?.proofKeyThumbprint) {\n            return [\n              {\n                _tag: \"error\",\n                reason: \"not-found\",\n                error: new BootstrapCredentialProofKeyMismatchError({}),\n              },\n              next,\n            ];\n          }\n\n          const remainingUses = grant.remainingUses;\n          if (typeof remainingUses === \"number\") {\n            if (remainingUses <= 1) {\n              next.delete(credential);\n            } else {\n              next.set(credential, {\n                ...grant,\n                remainingUses: remainingUses - 1,\n              });\n            }\n          }\n\n          return [\n            {\n              _tag: \"success\",\n              grant: {\n                method: grant.method,\n                scopes: grant.scopes,\n                subject: grant.subject,\n                ...(grant.label ? { label: grant.label } : {}),\n                ...(grant.proofKeyThumbprint\n                  ? { proofKeyThumbprint: grant.proofKeyThumbprint }\n                  : {}),\n                expiresAt: grant.expiresAt,\n              } satisfies BootstrapGrant,\n            },\n            next,\n          ];\n        },\n      );\n\n      if (seededResult._tag === \"success\") {\n        return seededResult.grant;\n      }\n      if (seededResult.reason !== \"not-found\") {\n        return yield* seededResult.error;\n      }\n\n      const consumed = yield* pairingLinks\n        .consumeAvailable({\n          credential,\n          proofKeyThumbprint: input?.proofKeyThumbprint ?? null,\n          consumedAt: now,\n          now,\n        })\n        .pipe(Effect.mapError((cause) => new BootstrapCredentialConsumeAvailableError({ cause })));\n\n      if (Option.isSome(consumed)) {\n        yield* emitRemoved(consumed.value.id);\n        return {\n          method: consumed.value.method,\n          scopes: consumed.value.scopes,\n          subject: consumed.value.subject,\n          ...(consumed.value.label ? { label: consumed.value.label } : {}),\n          ...(consumed.value.proofKeyThumbprint\n            ? { proofKeyThumbprint: consumed.value.proofKeyThumbprint }\n            : {}),\n          expiresAt: consumed.value.expiresAt,\n        } satisfies BootstrapGrant;\n      }\n\n      const matching = yield* pairingLinks\n        .getByCredential({ credential })\n        .pipe(Effect.mapError((cause) => new BootstrapCredentialLookupError({ cause })));\n      if (Option.isNone(matching)) {\n        return yield* new UnknownBootstrapCredentialError({});\n      }\n\n      if (matching.value.revokedAt !== null) {\n        return yield* new UnavailableBootstrapCredentialError({});\n      }\n\n      if (matching.value.consumedAt !== null) {\n        return yield* new UnknownBootstrapCredentialError({});\n      }\n\n      if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) {\n        return yield* new ExpiredBootstrapCredentialError({});\n      }\n\n      if (\n        matching.value.proofKeyThumbprint !== null &&\n        matching.value.proofKeyThumbprint !== input?.proofKeyThumbprint\n      ) {\n        return yield* new BootstrapCredentialProofKeyMismatchError({});\n      }\n\n      return yield* new UnavailableBootstrapCredentialError({});\n    },\n  );\n\n  return PairingGrantStore.of({\n    issueOneTimeToken,\n    listActive,\n    get streamChanges() {\n      return Stream.fromPubSub(changesPubSub);\n    },\n    revoke,\n    consume,\n  });\n});\n\nexport const layer = Layer.effect(PairingGrantStore, make).pipe(\n  Layer.provideMerge(AuthPairingLinks.layer),\n);\n","import * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ServerConfig from \"../config.ts\";\n\nconst secretStoreErrorContext = {\n  resource: Schema.String,\n  cause: Schema.Defect(),\n};\n\nexport class SecretStoreSecureError extends Schema.TaggedErrorClass<SecretStoreSecureError>()(\n  \"SecretStoreSecureError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to secure ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreReadError extends Schema.TaggedErrorClass<SecretStoreReadError>()(\n  \"SecretStoreReadError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to read ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreTemporaryPathError extends Schema.TaggedErrorClass<SecretStoreTemporaryPathError>()(\n  \"SecretStoreTemporaryPathError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to create temporary path for ${this.resource}.`;\n  }\n}\n\nexport class SecretStorePersistError extends Schema.TaggedErrorClass<SecretStorePersistError>()(\n  \"SecretStorePersistError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to persist ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreRandomGenerationError extends Schema.TaggedErrorClass<SecretStoreRandomGenerationError>()(\n  \"SecretStoreRandomGenerationError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to generate random bytes for ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreConcurrentReadError extends Schema.TaggedErrorClass<SecretStoreConcurrentReadError>()(\n  \"SecretStoreConcurrentReadError\",\n  {\n    resource: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Failed to read ${this.resource} after concurrent creation.`;\n  }\n}\n\nexport class SecretStoreRemoveError extends Schema.TaggedErrorClass<SecretStoreRemoveError>()(\n  \"SecretStoreRemoveError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to remove ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreDecodeError extends Schema.TaggedErrorClass<SecretStoreDecodeError>()(\n  \"SecretStoreDecodeError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to decode ${this.resource}.`;\n  }\n}\n\nexport class SecretStoreEncodeError extends Schema.TaggedErrorClass<SecretStoreEncodeError>()(\n  \"SecretStoreEncodeError\",\n  {\n    ...secretStoreErrorContext,\n  },\n) {\n  override get message(): string {\n    return `Failed to encode ${this.resource}.`;\n  }\n}\n\nexport const SecretStoreError = Schema.Union([\n  SecretStoreSecureError,\n  SecretStoreReadError,\n  SecretStoreTemporaryPathError,\n  SecretStorePersistError,\n  SecretStoreRandomGenerationError,\n  SecretStoreConcurrentReadError,\n  SecretStoreRemoveError,\n  SecretStoreDecodeError,\n  SecretStoreEncodeError,\n]);\nexport type SecretStoreError = typeof SecretStoreError.Type;\nexport const isSecretStoreError = Schema.is(SecretStoreError);\n\nconst isPlatformError = (value: unknown): value is PlatformError.PlatformError =>\n  Predicate.isTagged(value, \"PlatformError\");\n\nexport const isSecretAlreadyExistsError = (error: SecretStoreError): boolean =>\n  \"cause\" in error && isPlatformError(error.cause) && error.cause.reason._tag === \"AlreadyExists\";\n\nexport class ServerSecretStore extends Context.Service<\n  ServerSecretStore,\n  {\n    readonly get: (name: string) => Effect.Effect<Option.Option<Uint8Array>, SecretStoreError>;\n    readonly set: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;\n    readonly create: (name: string, value: Uint8Array) => Effect.Effect<void, SecretStoreError>;\n    readonly getOrCreateRandom: (\n      name: string,\n      bytes: number,\n    ) => Effect.Effect<Uint8Array, SecretStoreError>;\n    readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;\n  }\n>()(\"t3/auth/ServerSecretStore\") {}\n\nexport const make = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n\n  yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true });\n  yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe(\n    Effect.mapError(\n      (cause) =>\n        new SecretStoreSecureError({\n          resource: `secrets directory ${serverConfig.secretsDir}`,\n          cause,\n        }),\n    ),\n  );\n\n  const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);\n\n  const get: ServerSecretStore[\"Service\"][\"get\"] = (name) =>\n    fileSystem.readFile(resolveSecretPath(name)).pipe(\n      Effect.map((bytes) => Option.some(Uint8Array.from(bytes))),\n      Effect.catch((cause) =>\n        cause.reason._tag === \"NotFound\"\n          ? Effect.succeed(Option.none())\n          : Effect.fail(\n              new SecretStoreReadError({\n                resource: `secret ${name}`,\n                cause,\n              }),\n            ),\n      ),\n      Effect.withSpan(\"ServerSecretStore.get\"),\n    );\n\n  const set: ServerSecretStore[\"Service\"][\"set\"] = (name, value) => {\n    const secretPath = resolveSecretPath(name);\n    return crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new SecretStoreTemporaryPathError({\n            resource: `secret ${name}`,\n            cause,\n          }),\n      ),\n      Effect.flatMap((uuid) => {\n        const tempPath = `${secretPath}.${uuid}.tmp`;\n        return Effect.gen(function* () {\n          yield* fileSystem.writeFile(tempPath, value);\n          yield* fileSystem.chmod(tempPath, 0o600);\n          yield* fileSystem.rename(tempPath, secretPath);\n          yield* fileSystem.chmod(secretPath, 0o600);\n        }).pipe(\n          Effect.catch((cause) =>\n            fileSystem.remove(tempPath).pipe(\n              Effect.ignore,\n              Effect.flatMap(() =>\n                Effect.fail(\n                  new SecretStorePersistError({\n                    resource: `secret ${name}`,\n                    cause,\n                  }),\n                ),\n              ),\n            ),\n          ),\n        );\n      }),\n      Effect.withSpan(\"ServerSecretStore.set\"),\n    );\n  };\n\n  const create: ServerSecretStore[\"Service\"][\"create\"] = (name, value) => {\n    const secretPath = resolveSecretPath(name);\n    return Effect.scoped(\n      Effect.gen(function* () {\n        const file = yield* fileSystem.open(secretPath, {\n          flag: \"wx\",\n          mode: 0o600,\n        });\n        yield* file.writeAll(value);\n        yield* file.sync;\n        yield* fileSystem.chmod(secretPath, 0o600);\n      }),\n    ).pipe(\n      Effect.mapError(\n        (cause) =>\n          new SecretStorePersistError({\n            resource: `secret ${name}`,\n            cause,\n          }),\n      ),\n    );\n  };\n\n  const getOrCreateRandom: ServerSecretStore[\"Service\"][\"getOrCreateRandom\"] = (name, bytes) =>\n    get(name).pipe(\n      Effect.flatMap(\n        Option.match({\n          onSome: Effect.succeed,\n          onNone: () =>\n            crypto.randomBytes(bytes).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new SecretStoreRandomGenerationError({\n                    resource: `secret ${name}`,\n                    cause,\n                  }),\n              ),\n              Effect.flatMap((generated) =>\n                create(name, generated).pipe(\n                  Effect.as(Uint8Array.from(generated)),\n                  Effect.catchIf(isSecretStoreError, (error) =>\n                    isSecretAlreadyExistsError(error)\n                      ? get(name).pipe(\n                          Effect.flatMap(\n                            Option.match({\n                              onSome: Effect.succeed,\n                              onNone: () =>\n                                Effect.fail(\n                                  new SecretStoreConcurrentReadError({\n                                    resource: `secret ${name}`,\n                                  }),\n                                ),\n                            }),\n                          ),\n                        )\n                      : Effect.fail(error),\n                  ),\n                ),\n              ),\n            ),\n        }),\n      ),\n      Effect.withSpan(\"ServerSecretStore.getOrCreateRandom\"),\n    );\n\n  const remove: ServerSecretStore[\"Service\"][\"remove\"] = (name) =>\n    fileSystem.remove(resolveSecretPath(name)).pipe(\n      Effect.catch((cause) =>\n        cause.reason._tag === \"NotFound\"\n          ? Effect.void\n          : Effect.fail(\n              new SecretStoreRemoveError({\n                resource: `secret ${name}`,\n                cause,\n              }),\n            ),\n      ),\n      Effect.withSpan(\"ServerSecretStore.remove\"),\n    );\n\n  return ServerSecretStore.of({\n    get,\n    set,\n    create,\n    getOrCreateRandom,\n    remove,\n  });\n});\n\nexport const layer = Layer.effect(ServerSecretStore, make);\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport {\n  AuthClientMetadataDeviceType,\n  AuthEnvironmentScopes,\n  AuthSessionId,\n  ServerAuthSessionMethod,\n} from \"@t3tools/contracts\";\n\nimport {\n  type AuthSessionRepositoryError,\n  PersistenceDecodeError,\n  type PersistenceErrorCorrelation,\n  PersistenceSqlError,\n} from \"./Errors.ts\";\n\nexport const AuthSessionClientMetadataRecord = Schema.Struct({\n  label: Schema.NullOr(Schema.String),\n  ipAddress: Schema.NullOr(Schema.String),\n  userAgent: Schema.NullOr(Schema.String),\n  deviceType: AuthClientMetadataDeviceType,\n  os: Schema.NullOr(Schema.String),\n  browser: Schema.NullOr(Schema.String),\n});\nexport type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type;\n\nexport const AuthSessionRecord = Schema.Struct({\n  sessionId: AuthSessionId,\n  subject: Schema.String,\n  scopes: AuthEnvironmentScopes,\n  method: ServerAuthSessionMethod,\n  client: AuthSessionClientMetadataRecord,\n  issuedAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n  lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n  revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n});\nexport type AuthSessionRecord = typeof AuthSessionRecord.Type;\n\nexport const CreateAuthSessionInput = Schema.Struct({\n  sessionId: AuthSessionId,\n  subject: Schema.String,\n  scopes: AuthEnvironmentScopes,\n  method: ServerAuthSessionMethod,\n  client: AuthSessionClientMetadataRecord,\n  issuedAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n});\nexport type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type;\n\nexport const GetAuthSessionByIdInput = Schema.Struct({\n  sessionId: AuthSessionId,\n});\nexport type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type;\n\nexport const ListActiveAuthSessionsInput = Schema.Struct({\n  now: Schema.DateTimeUtcFromString,\n});\nexport type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type;\n\nexport const RevokeAuthSessionInput = Schema.Struct({\n  sessionId: AuthSessionId,\n  revokedAt: Schema.DateTimeUtcFromString,\n});\nexport type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type;\n\nexport const RevokeOtherAuthSessionsInput = Schema.Struct({\n  currentSessionId: AuthSessionId,\n  revokedAt: Schema.DateTimeUtcFromString,\n});\nexport type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type;\n\nexport const SetAuthSessionLastConnectedAtInput = Schema.Struct({\n  sessionId: AuthSessionId,\n  lastConnectedAt: Schema.DateTimeUtcFromString,\n});\nexport type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type;\n\nexport class AuthSessionRepository extends Context.Service<\n  AuthSessionRepository,\n  {\n    readonly create: (\n      input: CreateAuthSessionInput,\n    ) => Effect.Effect<void, AuthSessionRepositoryError>;\n    readonly getById: (\n      input: GetAuthSessionByIdInput,\n    ) => Effect.Effect<Option.Option<AuthSessionRecord>, AuthSessionRepositoryError>;\n    readonly listActive: (\n      input: ListActiveAuthSessionsInput,\n    ) => Effect.Effect<ReadonlyArray<AuthSessionRecord>, AuthSessionRepositoryError>;\n    readonly revoke: (\n      input: RevokeAuthSessionInput,\n    ) => Effect.Effect<boolean, AuthSessionRepositoryError>;\n    readonly revokeAllExcept: (\n      input: RevokeOtherAuthSessionsInput,\n    ) => Effect.Effect<ReadonlyArray<AuthSessionId>, AuthSessionRepositoryError>;\n    readonly setLastConnectedAt: (\n      input: SetAuthSessionLastConnectedAtInput,\n    ) => Effect.Effect<void, AuthSessionRepositoryError>;\n  }\n>()(\"t3/persistence/AuthSessions/AuthSessionRepository\") {}\n\nconst AuthSessionDbRow = Schema.Struct({\n  sessionId: AuthSessionId,\n  subject: Schema.String,\n  scopes: Schema.fromJsonString(AuthEnvironmentScopes),\n  method: ServerAuthSessionMethod,\n  clientLabel: Schema.NullOr(Schema.String),\n  clientIpAddress: Schema.NullOr(Schema.String),\n  clientUserAgent: Schema.NullOr(Schema.String),\n  clientDeviceType: Schema.Literals([\"desktop\", \"mobile\", \"tablet\", \"bot\", \"unknown\"]),\n  clientOs: Schema.NullOr(Schema.String),\n  clientBrowser: Schema.NullOr(Schema.String),\n  issuedAt: Schema.DateTimeUtcFromString,\n  expiresAt: Schema.DateTimeUtcFromString,\n  lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n  revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString),\n});\n\nconst AuthSessionRawDbRow = Schema.Struct({\n  sessionId: Schema.String,\n  subject: Schema.Unknown,\n  scopes: Schema.Unknown,\n  method: Schema.Unknown,\n  clientLabel: Schema.Unknown,\n  clientIpAddress: Schema.Unknown,\n  clientUserAgent: Schema.Unknown,\n  clientDeviceType: Schema.Unknown,\n  clientOs: Schema.Unknown,\n  clientBrowser: Schema.Unknown,\n  issuedAt: Schema.Unknown,\n  expiresAt: Schema.Unknown,\n  lastConnectedAt: Schema.Unknown,\n  revokedAt: Schema.Unknown,\n});\n\nconst decodeAuthSessionDbRow = Schema.decodeUnknownEffect(AuthSessionDbRow);\n\nfunction toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): AuthSessionRecord {\n  return {\n    sessionId: row.sessionId,\n    subject: row.subject,\n    scopes: row.scopes,\n    method: row.method,\n    client: {\n      label: row.clientLabel,\n      ipAddress: row.clientIpAddress,\n      userAgent: row.clientUserAgent,\n      deviceType: row.clientDeviceType,\n      os: row.clientOs,\n      browser: row.clientBrowser,\n    },\n    issuedAt: row.issuedAt,\n    expiresAt: row.expiresAt,\n    lastConnectedAt: row.lastConnectedAt,\n    revokedAt: row.revokedAt,\n  };\n}\n\nfunction toPersistenceSqlOrDecodeError(\n  sqlOperation: string,\n  decodeOperation: string,\n  correlation?: PersistenceErrorCorrelation,\n) {\n  return (cause: unknown): AuthSessionRepositoryError =>\n    Schema.isSchemaError(cause)\n      ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)\n      : new PersistenceSqlError({\n          operation: sqlOperation,\n          ...(correlation === undefined ? {} : { correlation }),\n          cause,\n        });\n}\n\nexport const make = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const createSessionRow = SqlSchema.void({\n    Request: CreateAuthSessionInput,\n    execute: (input) =>\n      sql`\n        INSERT INTO auth_sessions (\n          session_id,\n          subject,\n          scopes,\n          method,\n          client_label,\n          client_ip_address,\n          client_user_agent,\n          client_device_type,\n          client_os,\n          client_browser,\n          issued_at,\n          expires_at,\n          revoked_at\n        )\n        VALUES (\n          ${input.sessionId},\n          ${input.subject},\n          ${JSON.stringify(input.scopes)},\n          ${input.method},\n          ${input.client.label},\n          ${input.client.ipAddress},\n          ${input.client.userAgent},\n          ${input.client.deviceType},\n          ${input.client.os},\n          ${input.client.browser},\n          ${input.issuedAt},\n          ${input.expiresAt},\n          NULL\n        )\n      `,\n  });\n\n  const getSessionRowById = SqlSchema.findOneOption({\n    Request: GetAuthSessionByIdInput,\n    Result: AuthSessionRawDbRow,\n    execute: ({ sessionId }) =>\n      sql`\n        SELECT\n          session_id AS \"sessionId\",\n          subject AS \"subject\",\n          scopes AS \"scopes\",\n          method AS \"method\",\n          client_label AS \"clientLabel\",\n          client_ip_address AS \"clientIpAddress\",\n          client_user_agent AS \"clientUserAgent\",\n          client_device_type AS \"clientDeviceType\",\n          client_os AS \"clientOs\",\n          client_browser AS \"clientBrowser\",\n          issued_at AS \"issuedAt\",\n          expires_at AS \"expiresAt\",\n          last_connected_at AS \"lastConnectedAt\",\n          revoked_at AS \"revokedAt\"\n        FROM auth_sessions\n        WHERE session_id = ${sessionId}\n      `,\n  });\n\n  const listActiveSessionRows = SqlSchema.findAll({\n    Request: ListActiveAuthSessionsInput,\n    Result: AuthSessionRawDbRow,\n    execute: ({ now }) =>\n      sql`\n        SELECT\n          session_id AS \"sessionId\",\n          subject AS \"subject\",\n          scopes AS \"scopes\",\n          method AS \"method\",\n          client_label AS \"clientLabel\",\n          client_ip_address AS \"clientIpAddress\",\n          client_user_agent AS \"clientUserAgent\",\n          client_device_type AS \"clientDeviceType\",\n          client_os AS \"clientOs\",\n          client_browser AS \"clientBrowser\",\n          issued_at AS \"issuedAt\",\n          expires_at AS \"expiresAt\",\n          last_connected_at AS \"lastConnectedAt\",\n          revoked_at AS \"revokedAt\"\n        FROM auth_sessions\n        WHERE revoked_at IS NULL\n          AND expires_at > ${now}\n        ORDER BY issued_at DESC, session_id DESC\n      `,\n  });\n\n  const setLastConnectedAtRow = SqlSchema.void({\n    Request: SetAuthSessionLastConnectedAtInput,\n    execute: ({ sessionId, lastConnectedAt }) =>\n      sql`\n        UPDATE auth_sessions\n        SET last_connected_at = ${lastConnectedAt}\n        WHERE session_id = ${sessionId}\n          AND revoked_at IS NULL\n      `,\n  });\n\n  const revokeSessionRows = SqlSchema.findAll({\n    Request: RevokeAuthSessionInput,\n    Result: Schema.Struct({ sessionId: AuthSessionId }),\n    execute: ({ sessionId, revokedAt }) =>\n      sql`\n        UPDATE auth_sessions\n        SET revoked_at = ${revokedAt}\n        WHERE session_id = ${sessionId}\n          AND revoked_at IS NULL\n        RETURNING session_id AS \"sessionId\"\n      `,\n  });\n\n  const revokeOtherSessionRows = SqlSchema.findAll({\n    Request: RevokeOtherAuthSessionsInput,\n    Result: Schema.Struct({ sessionId: AuthSessionId }),\n    execute: ({ currentSessionId, revokedAt }) =>\n      sql`\n        UPDATE auth_sessions\n        SET revoked_at = ${revokedAt}\n        WHERE session_id <> ${currentSessionId}\n          AND revoked_at IS NULL\n        RETURNING session_id AS \"sessionId\"\n      `,\n  });\n\n  const create: AuthSessionRepository[\"Service\"][\"create\"] = (input) =>\n    createSessionRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.create:query\",\n          \"AuthSessionRepository.create:encodeRequest\",\n          { sessionId: input.sessionId },\n        ),\n      ),\n    );\n\n  const getById: AuthSessionRepository[\"Service\"][\"getById\"] = (input) =>\n    getSessionRowById(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.getById:query\",\n          \"AuthSessionRepository.getById:decodeRow\",\n          { sessionId: input.sessionId },\n        ),\n      ),\n      Effect.flatMap((rowOption) =>\n        Option.match(rowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            decodeAuthSessionDbRow(row).pipe(\n              Effect.mapError((cause) =>\n                PersistenceDecodeError.fromSchemaError(\n                  \"AuthSessionRepository.getById:decodeRow\",\n                  cause,\n                  { sessionId: input.sessionId },\n                ),\n              ),\n              Effect.map((decodedRow) => Option.some(toAuthSessionRecord(decodedRow))),\n            ),\n        }),\n      ),\n    );\n\n  const listActive: AuthSessionRepository[\"Service\"][\"listActive\"] = (input) =>\n    listActiveSessionRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.listActive:query\",\n          \"AuthSessionRepository.listActive:decodeRows\",\n        ),\n      ),\n      Effect.flatMap((rows) =>\n        Effect.forEach(rows, (row) =>\n          decodeAuthSessionDbRow(row).pipe(\n            Effect.mapError((cause) =>\n              PersistenceDecodeError.fromSchemaError(\n                \"AuthSessionRepository.listActive:decodeRows\",\n                cause,\n                { sessionId: row.sessionId },\n              ),\n            ),\n            Effect.map(toAuthSessionRecord),\n          ),\n        ),\n      ),\n    );\n\n  const revoke: AuthSessionRepository[\"Service\"][\"revoke\"] = (input) =>\n    revokeSessionRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.revoke:query\",\n          \"AuthSessionRepository.revoke:decodeRows\",\n          { sessionId: input.sessionId },\n        ),\n      ),\n      Effect.map((rows) => rows.length > 0),\n    );\n\n  const revokeAllExcept: AuthSessionRepository[\"Service\"][\"revokeAllExcept\"] = (input) =>\n    revokeOtherSessionRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.revokeAllExcept:query\",\n          \"AuthSessionRepository.revokeAllExcept:decodeRows\",\n          { currentSessionId: input.currentSessionId },\n        ),\n      ),\n      Effect.map((rows) => rows.map((row) => row.sessionId)),\n    );\n\n  const setLastConnectedAt: AuthSessionRepository[\"Service\"][\"setLastConnectedAt\"] = (input) =>\n    setLastConnectedAtRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"AuthSessionRepository.setLastConnectedAt:query\",\n          \"AuthSessionRepository.setLastConnectedAt:encodeRequest\",\n          { sessionId: input.sessionId },\n        ),\n      ),\n    );\n\n  return {\n    create,\n    getById,\n    listActive,\n    revoke,\n    revokeAllExcept,\n    setLastConnectedAt,\n  } satisfies AuthSessionRepository[\"Service\"];\n});\n\nexport const layer = Layer.effect(AuthSessionRepository, make);\n","import {\n  AuthSessionId,\n  AuthStandardClientScopes,\n  AuthEnvironmentScopes,\n  type AuthClientMetadata,\n  type AuthClientSession,\n  type AuthEnvironmentScope,\n  type ServerAuthSessionMethod,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as Option from \"effect/Option\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport * as AuthSessions from \"../persistence/AuthSessions.ts\";\nimport * as ServerSecretStore from \"./ServerSecretStore.ts\";\nimport {\n  base64UrlDecodeUtf8,\n  base64UrlEncode,\n  resolveSessionCookieName,\n  signPayload,\n  timingSafeEqualBase64Url,\n} from \"./utils.ts\";\n\nexport interface IssuedSession {\n  readonly sessionId: AuthSessionId;\n  readonly token: string;\n  readonly method: ServerAuthSessionMethod;\n  readonly client: AuthClientMetadata;\n  readonly expiresAt: DateTime.DateTime;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly proofKeyThumbprint?: string;\n}\n\nexport interface VerifiedSession {\n  readonly sessionId: AuthSessionId;\n  readonly token: string;\n  readonly method: ServerAuthSessionMethod;\n  readonly client: AuthClientMetadata;\n  readonly expiresAt?: DateTime.DateTime;\n  readonly subject: string;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly proofKeyThumbprint?: string;\n}\n\nexport type SessionCredentialChange =\n  | {\n      readonly type: \"clientUpserted\";\n      readonly clientSession: AuthClientSession;\n    }\n  | {\n      readonly type: \"clientRemoved\";\n      readonly sessionId: AuthSessionId;\n    };\n\nexport class MalformedSessionTokenError extends Schema.TaggedErrorClass<MalformedSessionTokenError>()(\n  \"MalformedSessionTokenError\",\n  {},\n) {\n  override get message(): string {\n    return \"Malformed session token.\";\n  }\n}\n\nexport class InvalidSessionTokenSignatureError extends Schema.TaggedErrorClass<InvalidSessionTokenSignatureError>()(\n  \"InvalidSessionTokenSignatureError\",\n  {},\n) {\n  override get message(): string {\n    return \"Invalid session token signature.\";\n  }\n}\n\nexport class InvalidSessionTokenPayloadError extends Schema.TaggedErrorClass<InvalidSessionTokenPayloadError>()(\n  \"InvalidSessionTokenPayloadError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Invalid session token payload.\";\n  }\n}\n\nexport class SessionTokenExpiredError extends Schema.TaggedErrorClass<SessionTokenExpiredError>()(\n  \"SessionTokenExpiredError\",\n  {\n    sessionId: AuthSessionId,\n    expiresAt: Schema.DateTimeUtc,\n    observedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Session token expired.\";\n  }\n}\n\nexport class UnknownSessionTokenError extends Schema.TaggedErrorClass<UnknownSessionTokenError>()(\n  \"UnknownSessionTokenError\",\n  {\n    sessionId: AuthSessionId,\n  },\n) {\n  override get message(): string {\n    return \"Unknown session token.\";\n  }\n}\n\nexport class SessionTokenRevokedError extends Schema.TaggedErrorClass<SessionTokenRevokedError>()(\n  \"SessionTokenRevokedError\",\n  {\n    sessionId: AuthSessionId,\n    revokedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Session token revoked.\";\n  }\n}\n\nexport class InvalidSessionExpirationClaimError extends Schema.TaggedErrorClass<InvalidSessionExpirationClaimError>()(\n  \"InvalidSessionExpirationClaimError\",\n  {\n    sessionId: AuthSessionId,\n    expirationClaim: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return \"Invalid `exp` claim\";\n  }\n}\n\nexport class MalformedWebSocketTokenError extends Schema.TaggedErrorClass<MalformedWebSocketTokenError>()(\n  \"MalformedWebSocketTokenError\",\n  {},\n) {\n  override get message(): string {\n    return \"Malformed websocket token.\";\n  }\n}\n\nexport class InvalidWebSocketTokenSignatureError extends Schema.TaggedErrorClass<InvalidWebSocketTokenSignatureError>()(\n  \"InvalidWebSocketTokenSignatureError\",\n  {},\n) {\n  override get message(): string {\n    return \"Invalid websocket token signature.\";\n  }\n}\n\nexport class InvalidWebSocketTokenPayloadError extends Schema.TaggedErrorClass<InvalidWebSocketTokenPayloadError>()(\n  \"InvalidWebSocketTokenPayloadError\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Invalid websocket token payload.\";\n  }\n}\n\nexport class WebSocketTokenExpiredError extends Schema.TaggedErrorClass<WebSocketTokenExpiredError>()(\n  \"WebSocketTokenExpiredError\",\n  {\n    sessionId: AuthSessionId,\n    expiresAt: Schema.DateTimeUtc,\n    observedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Websocket token expired.\";\n  }\n}\n\nexport class UnknownWebSocketSessionError extends Schema.TaggedErrorClass<UnknownWebSocketSessionError>()(\n  \"UnknownWebSocketSessionError\",\n  {\n    sessionId: AuthSessionId,\n  },\n) {\n  override get message(): string {\n    return \"Unknown websocket session.\";\n  }\n}\n\nexport class WebSocketSessionExpiredError extends Schema.TaggedErrorClass<WebSocketSessionExpiredError>()(\n  \"WebSocketSessionExpiredError\",\n  {\n    sessionId: AuthSessionId,\n    expiresAt: Schema.DateTimeUtc,\n    observedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Websocket session expired.\";\n  }\n}\n\nexport class WebSocketSessionRevokedError extends Schema.TaggedErrorClass<WebSocketSessionRevokedError>()(\n  \"WebSocketSessionRevokedError\",\n  {\n    sessionId: AuthSessionId,\n    revokedAt: Schema.DateTimeUtc,\n  },\n) {\n  override get message(): string {\n    return \"Websocket session revoked.\";\n  }\n}\n\nexport const SessionCredentialInvalidError = Schema.Union([\n  MalformedSessionTokenError,\n  InvalidSessionTokenSignatureError,\n  InvalidSessionTokenPayloadError,\n  SessionTokenExpiredError,\n  UnknownSessionTokenError,\n  SessionTokenRevokedError,\n  InvalidSessionExpirationClaimError,\n  MalformedWebSocketTokenError,\n  InvalidWebSocketTokenSignatureError,\n  InvalidWebSocketTokenPayloadError,\n  WebSocketTokenExpiredError,\n  UnknownWebSocketSessionError,\n  WebSocketSessionExpiredError,\n  WebSocketSessionRevokedError,\n]);\nexport type SessionCredentialInvalidError = typeof SessionCredentialInvalidError.Type;\nexport const isSessionCredentialInvalidError = Schema.is(SessionCredentialInvalidError);\n\nconst sessionCredentialInternalErrorContext = {\n  cause: Schema.Defect(),\n};\n\nexport class SessionClaimsEncodingError extends Schema.TaggedErrorClass<SessionClaimsEncodingError>()(\n  \"SessionClaimsEncodingError\",\n  {\n    sessionId: AuthSessionId,\n    operation: Schema.Literals([\"encode_session_claims\", \"encode_websocket_claims\"]),\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to encode claims\";\n  }\n}\n\nexport class SessionCredentialIssueError extends Schema.TaggedErrorClass<SessionCredentialIssueError>()(\n  \"SessionCredentialIssueError\",\n  {\n    sessionId: Schema.optional(AuthSessionId),\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue session credential.\";\n  }\n}\n\nexport class SessionCredentialVerificationError extends Schema.TaggedErrorClass<SessionCredentialVerificationError>()(\n  \"SessionCredentialVerificationError\",\n  {\n    sessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to verify session credential.\";\n  }\n}\n\nexport class WebSocketTokenIssueError extends Schema.TaggedErrorClass<WebSocketTokenIssueError>()(\n  \"WebSocketTokenIssueError\",\n  {\n    sessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue websocket token.\";\n  }\n}\n\nexport class WebSocketTokenVerificationError extends Schema.TaggedErrorClass<WebSocketTokenVerificationError>()(\n  \"WebSocketTokenVerificationError\",\n  {\n    sessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to verify websocket token.\";\n  }\n}\n\nexport class ActiveSessionsListError extends Schema.TaggedErrorClass<ActiveSessionsListError>()(\n  \"ActiveSessionsListError\",\n  {\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to list active sessions.\";\n  }\n}\n\nexport class SessionRevocationError extends Schema.TaggedErrorClass<SessionRevocationError>()(\n  \"SessionRevocationError\",\n  {\n    sessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke session.\";\n  }\n}\n\nexport class OtherSessionsRevocationError extends Schema.TaggedErrorClass<OtherSessionsRevocationError>()(\n  \"OtherSessionsRevocationError\",\n  {\n    currentSessionId: AuthSessionId,\n    ...sessionCredentialInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke other sessions.\";\n  }\n}\n\nexport const SessionCredentialInternalError = Schema.Union([\n  SessionClaimsEncodingError,\n  SessionCredentialIssueError,\n  SessionCredentialVerificationError,\n  WebSocketTokenIssueError,\n  WebSocketTokenVerificationError,\n  ActiveSessionsListError,\n  SessionRevocationError,\n  OtherSessionsRevocationError,\n]);\nexport type SessionCredentialInternalError = typeof SessionCredentialInternalError.Type;\nexport const isSessionCredentialInternalError = Schema.is(SessionCredentialInternalError);\n\nexport const SessionCredentialError = Schema.Union([\n  SessionCredentialInvalidError,\n  SessionCredentialInternalError,\n]);\nexport type SessionCredentialError = typeof SessionCredentialError.Type;\nexport const isSessionCredentialError = Schema.is(SessionCredentialError);\n\nexport class SessionStore extends Context.Service<\n  SessionStore,\n  {\n    readonly cookieName: string;\n    readonly issue: (input?: {\n      readonly ttl?: Duration.Duration;\n      readonly subject?: string;\n      readonly method?: ServerAuthSessionMethod;\n      readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;\n      readonly client?: AuthClientMetadata;\n      readonly proofKeyThumbprint?: string;\n    }) => Effect.Effect<IssuedSession, SessionCredentialInternalError>;\n    readonly verify: (token: string) => Effect.Effect<VerifiedSession, SessionCredentialError>;\n    readonly issueWebSocketToken: (\n      sessionId: AuthSessionId,\n      input?: {\n        readonly ttl?: Duration.Duration;\n      },\n    ) => Effect.Effect<\n      {\n        readonly token: string;\n        readonly expiresAt: DateTime.DateTime;\n      },\n      SessionCredentialInternalError\n    >;\n    readonly verifyWebSocketToken: (\n      token: string,\n    ) => Effect.Effect<VerifiedSession, SessionCredentialError>;\n    readonly listActive: () => Effect.Effect<\n      ReadonlyArray<AuthClientSession>,\n      SessionCredentialInternalError\n    >;\n    readonly streamChanges: Stream.Stream<SessionCredentialChange>;\n    readonly revoke: (\n      sessionId: AuthSessionId,\n    ) => Effect.Effect<boolean, SessionCredentialInternalError>;\n    readonly revokeAllExcept: (\n      sessionId: AuthSessionId,\n    ) => Effect.Effect<number, SessionCredentialInternalError>;\n    readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;\n    readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;\n  }\n>()(\"t3/auth/SessionStore\") {}\n\nconst SIGNING_SECRET_NAME = \"server-signing-key\";\nconst DEFAULT_SESSION_TTL = Duration.days(30);\nconst DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5);\n\nconst SessionClaims = Schema.Struct({\n  v: Schema.Literal(1),\n  kind: Schema.Literal(\"session\"),\n  sid: AuthSessionId,\n  sub: Schema.String,\n  scopes: AuthEnvironmentScopes,\n  method: Schema.Literals([\"browser-session-cookie\", \"bearer-access-token\", \"dpop-access-token\"]),\n  jkt: Schema.optionalKey(Schema.String),\n  iat: Schema.Number,\n  exp: Schema.Number,\n});\ntype SessionClaims = typeof SessionClaims.Type;\n\nconst WebSocketClaims = Schema.Struct({\n  v: Schema.Literal(1),\n  kind: Schema.Literal(\"websocket\"),\n  sid: AuthSessionId,\n  iat: Schema.Number,\n  exp: Schema.Number,\n});\ntype WebSocketClaims = typeof WebSocketClaims.Type;\n\nconst decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));\nconst decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));\n\nfunction createDefaultClientMetadata(): AuthClientMetadata {\n  return {\n    deviceType: \"unknown\",\n  };\n}\n\nfunction toClientMetadata(record: {\n  readonly label: string | null;\n  readonly ipAddress: string | null;\n  readonly userAgent: string | null;\n  readonly deviceType: AuthClientMetadata[\"deviceType\"];\n  readonly os: string | null;\n  readonly browser: string | null;\n}): AuthClientMetadata {\n  return {\n    ...(record.label ? { label: record.label } : {}),\n    ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}),\n    ...(record.userAgent ? { userAgent: record.userAgent } : {}),\n    deviceType: record.deviceType,\n    ...(record.os ? { os: record.os } : {}),\n    ...(record.browser ? { browser: record.browser } : {}),\n  };\n}\n\nfunction toAuthClientSession(input: Omit<AuthClientSession, \"current\">): AuthClientSession {\n  return {\n    ...input,\n    current: false,\n  };\n}\n\nexport const make = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const authSessions = yield* AuthSessions.AuthSessionRepository;\n  const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);\n  const connectedSessionsRef = yield* Ref.make(new Map<string, number>());\n  const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();\n  const cookieName = resolveSessionCookieName({\n    mode: serverConfig.mode,\n    port: serverConfig.port,\n    host: serverConfig.host,\n    instanceKey: serverConfig.stateDir,\n    development: serverConfig.devUrl !== undefined,\n  });\n\n  const emitUpsert = (clientSession: AuthClientSession) =>\n    PubSub.publish(changesPubSub, {\n      type: \"clientUpserted\",\n      clientSession,\n    }).pipe(Effect.asVoid);\n\n  const emitRemoved = (sessionId: AuthSessionId) =>\n    PubSub.publish(changesPubSub, {\n      type: \"clientRemoved\",\n      sessionId,\n    }).pipe(Effect.asVoid);\n\n  const loadActiveSession = (sessionId: AuthSessionId) =>\n    Effect.gen(function* () {\n      const row = yield* authSessions.getById({ sessionId });\n      if (Option.isNone(row) || row.value.revokedAt !== null) {\n        return Option.none<AuthClientSession>();\n      }\n\n      const connectedSessions = yield* Ref.get(connectedSessionsRef);\n      return Option.some(\n        toAuthClientSession({\n          sessionId: row.value.sessionId,\n          subject: row.value.subject,\n          scopes: row.value.scopes,\n          method: row.value.method,\n          client: toClientMetadata(row.value.client),\n          issuedAt: row.value.issuedAt,\n          expiresAt: row.value.expiresAt,\n          lastConnectedAt: row.value.lastConnectedAt,\n          connected: connectedSessions.has(row.value.sessionId),\n        }),\n      );\n    });\n\n  const markConnected: SessionStore[\"Service\"][\"markConnected\"] = (sessionId) =>\n    Ref.modify(connectedSessionsRef, (current) => {\n      const next = new Map(current);\n      const wasDisconnected = !next.has(sessionId);\n      next.set(sessionId, (next.get(sessionId) ?? 0) + 1);\n      return [wasDisconnected, next] as const;\n    }).pipe(\n      Effect.flatMap((wasDisconnected) =>\n        wasDisconnected\n          ? DateTime.now.pipe(\n              Effect.flatMap((lastConnectedAt) =>\n                authSessions.setLastConnectedAt({\n                  sessionId,\n                  lastConnectedAt,\n                }),\n              ),\n            )\n          : Effect.void,\n      ),\n      Effect.flatMap(() => loadActiveSession(sessionId)),\n      Effect.flatMap((session) =>\n        Option.isSome(session) ? emitUpsert(session.value) : Effect.void,\n      ),\n      Effect.catchCause((cause) =>\n        Effect.logError(\"Failed to publish connected-session auth update.\").pipe(\n          Effect.annotateLogs({\n            sessionId,\n            cause,\n          }),\n        ),\n      ),\n      Effect.withSpan(\"SessionStore.markConnected\"),\n    );\n\n  const markDisconnected: SessionStore[\"Service\"][\"markDisconnected\"] = (sessionId) =>\n    Ref.update(connectedSessionsRef, (current) => {\n      const next = new Map(current);\n      const remaining = (next.get(sessionId) ?? 0) - 1;\n      if (remaining > 0) {\n        next.set(sessionId, remaining);\n      } else {\n        next.delete(sessionId);\n      }\n      return next;\n    }).pipe(\n      Effect.flatMap(() => loadActiveSession(sessionId)),\n      Effect.flatMap((session) =>\n        Option.isSome(session) ? emitUpsert(session.value) : Effect.void,\n      ),\n      Effect.catchCause((cause) =>\n        Effect.logError(\"Failed to publish disconnected-session auth update.\").pipe(\n          Effect.annotateLogs({\n            sessionId,\n            cause,\n          }),\n        ),\n      ),\n      Effect.withSpan(\"SessionStore.markDisconnected\"),\n    );\n\n  const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));\n  const issue: SessionStore[\"Service\"][\"issue\"] = Effect.fn(\"SessionStore.issue\")(\n    function* (input) {\n      const sessionId = AuthSessionId.make(\n        yield* crypto.randomUUIDv4.pipe(\n          Effect.mapError((cause) => new SessionCredentialIssueError({ cause })),\n        ),\n      );\n      const issuedAt = yield* DateTime.now;\n      const expiresAt = DateTime.add(issuedAt, {\n        milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),\n      });\n      const claims: SessionClaims = {\n        v: 1,\n        kind: \"session\",\n        sid: sessionId,\n        sub: input?.subject ?? \"browser\",\n        scopes: input?.scopes ?? AuthStandardClientScopes,\n        method: input?.method ?? \"browser-session-cookie\",\n        ...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),\n        iat: issuedAt.epochMilliseconds,\n        exp: expiresAt.epochMilliseconds,\n      };\n\n      const encodedPayload = yield* encodeClaims(claims).pipe(\n        Effect.map(base64UrlEncode),\n        Effect.mapError(\n          (cause) =>\n            new SessionCredentialIssueError({\n              sessionId,\n              cause: new SessionClaimsEncodingError({\n                sessionId,\n                operation: \"encode_session_claims\",\n                cause,\n              }),\n            }),\n        ),\n      );\n      const signature = signPayload(encodedPayload, signingSecret);\n      const client = input?.client ?? createDefaultClientMetadata();\n      yield* authSessions\n        .create({\n          sessionId,\n          subject: claims.sub,\n          scopes: claims.scopes,\n          method: claims.method,\n          client: {\n            label: client.label ?? null,\n            ipAddress: client.ipAddress ?? null,\n            userAgent: client.userAgent ?? null,\n            deviceType: client.deviceType,\n            os: client.os ?? null,\n            browser: client.browser ?? null,\n          },\n          issuedAt,\n          expiresAt,\n        })\n        .pipe(Effect.mapError((cause) => new SessionCredentialIssueError({ sessionId, cause })));\n      yield* emitUpsert(\n        toAuthClientSession({\n          sessionId,\n          subject: claims.sub,\n          scopes: claims.scopes,\n          method: claims.method,\n          client,\n          issuedAt,\n          expiresAt,\n          lastConnectedAt: null,\n          connected: false,\n        }),\n      );\n\n      return {\n        sessionId,\n        token: `${encodedPayload}.${signature}`,\n        method: claims.method,\n        client,\n        expiresAt: expiresAt,\n        scopes: claims.scopes,\n        ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),\n      } satisfies IssuedSession;\n    },\n  );\n\n  const verify: SessionStore[\"Service\"][\"verify\"] = Effect.fn(\"SessionStore.verify\")(\n    function* (token) {\n      const [encodedPayload, signature] = token.split(\".\");\n      if (!encodedPayload || !signature) {\n        return yield* new MalformedSessionTokenError({});\n      }\n\n      const expectedSignature = signPayload(encodedPayload, signingSecret);\n      if (!timingSafeEqualBase64Url(signature, expectedSignature)) {\n        return yield* new InvalidSessionTokenSignatureError({});\n      }\n\n      const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(\n        Effect.mapError((cause) => new InvalidSessionTokenPayloadError({ cause })),\n      );\n\n      const observedAt = yield* DateTime.now;\n      const expiresAt = DateTime.make(claims.exp);\n      if (Option.isNone(expiresAt)) {\n        return yield* new InvalidSessionExpirationClaimError({\n          sessionId: claims.sid,\n          expirationClaim: claims.exp,\n        });\n      }\n      if (claims.exp <= observedAt.epochMilliseconds) {\n        return yield* new SessionTokenExpiredError({\n          sessionId: claims.sid,\n          expiresAt: expiresAt.value,\n          observedAt,\n        });\n      }\n\n      const row = yield* authSessions\n        .getById({ sessionId: claims.sid })\n        .pipe(\n          Effect.mapError(\n            (cause) => new SessionCredentialVerificationError({ sessionId: claims.sid, cause }),\n          ),\n        );\n      if (Option.isNone(row)) {\n        return yield* new UnknownSessionTokenError({ sessionId: claims.sid });\n      }\n      if (row.value.revokedAt !== null) {\n        return yield* new SessionTokenRevokedError({\n          sessionId: claims.sid,\n          revokedAt: row.value.revokedAt,\n        });\n      }\n\n      return {\n        sessionId: claims.sid,\n        token,\n        method: claims.method,\n        client: toClientMetadata(row.value.client),\n        expiresAt: expiresAt.value,\n        subject: claims.sub,\n        scopes: claims.scopes,\n        ...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),\n      } satisfies VerifiedSession;\n    },\n  );\n\n  const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));\n  const issueWebSocketToken: SessionStore[\"Service\"][\"issueWebSocketToken\"] = Effect.fn(\n    \"SessionStore.issueWebSocketToken\",\n  )(function* (sessionId, input) {\n    const issuedAt = yield* DateTime.now;\n    const expiresAt = DateTime.add(issuedAt, {\n      milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL),\n    });\n    const claims: WebSocketClaims = {\n      v: 1,\n      kind: \"websocket\",\n      sid: sessionId,\n      iat: issuedAt.epochMilliseconds,\n      exp: expiresAt.epochMilliseconds,\n    };\n    const encodedPayload = yield* encodeWsClaims(claims).pipe(\n      Effect.map(base64UrlEncode),\n      Effect.mapError(\n        (cause) =>\n          new WebSocketTokenIssueError({\n            sessionId,\n            cause: new SessionClaimsEncodingError({\n              sessionId,\n              operation: \"encode_websocket_claims\",\n              cause,\n            }),\n          }),\n      ),\n    );\n    const signature = signPayload(encodedPayload, signingSecret);\n    return {\n      token: `${encodedPayload}.${signature}`,\n      expiresAt,\n    };\n  });\n\n  const verifyWebSocketToken: SessionStore[\"Service\"][\"verifyWebSocketToken\"] = Effect.fn(\n    \"SessionStore.verifyWebSocketToken\",\n  )(function* (token) {\n    const [encodedPayload, signature] = token.split(\".\");\n    if (!encodedPayload || !signature) {\n      return yield* new MalformedWebSocketTokenError({});\n    }\n\n    const expectedSignature = signPayload(encodedPayload, signingSecret);\n    if (!timingSafeEqualBase64Url(signature, expectedSignature)) {\n      return yield* new InvalidWebSocketTokenSignatureError({});\n    }\n\n    const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(\n      Effect.mapError((cause) => new InvalidWebSocketTokenPayloadError({ cause })),\n    );\n\n    const observedAt = yield* DateTime.now;\n    const expiresAt = DateTime.make(claims.exp);\n    if (Option.isNone(expiresAt)) {\n      return yield* new InvalidSessionExpirationClaimError({\n        sessionId: claims.sid,\n        expirationClaim: claims.exp,\n      });\n    }\n    if (claims.exp <= observedAt.epochMilliseconds) {\n      return yield* new WebSocketTokenExpiredError({\n        sessionId: claims.sid,\n        expiresAt: expiresAt.value,\n        observedAt,\n      });\n    }\n\n    const row = yield* authSessions\n      .getById({ sessionId: claims.sid })\n      .pipe(\n        Effect.mapError(\n          (cause) => new WebSocketTokenVerificationError({ sessionId: claims.sid, cause }),\n        ),\n      );\n    if (Option.isNone(row)) {\n      return yield* new UnknownWebSocketSessionError({ sessionId: claims.sid });\n    }\n    if (row.value.expiresAt.epochMilliseconds <= observedAt.epochMilliseconds) {\n      return yield* new WebSocketSessionExpiredError({\n        sessionId: claims.sid,\n        expiresAt: row.value.expiresAt,\n        observedAt,\n      });\n    }\n    if (row.value.revokedAt !== null) {\n      return yield* new WebSocketSessionRevokedError({\n        sessionId: claims.sid,\n        revokedAt: row.value.revokedAt,\n      });\n    }\n\n    return {\n      sessionId: row.value.sessionId,\n      token,\n      method: row.value.method,\n      client: toClientMetadata(row.value.client),\n      expiresAt: row.value.expiresAt,\n      subject: row.value.subject,\n      scopes: row.value.scopes,\n    } satisfies VerifiedSession;\n  });\n\n  const listActive: SessionStore[\"Service\"][\"listActive\"] = Effect.fn(\"SessionStore.listActive\")(\n    function* () {\n      const now = yield* DateTime.now;\n      const connectedSessions = yield* Ref.get(connectedSessionsRef);\n      const rows = yield* authSessions.listActive({ now });\n\n      return rows.map((row) =>\n        toAuthClientSession({\n          sessionId: row.sessionId,\n          subject: row.subject,\n          scopes: row.scopes,\n          method: row.method,\n          client: toClientMetadata(row.client),\n          issuedAt: row.issuedAt,\n          expiresAt: row.expiresAt,\n          lastConnectedAt: row.lastConnectedAt,\n          connected: connectedSessions.has(row.sessionId),\n        }),\n      );\n    },\n    Effect.mapError((cause) => new ActiveSessionsListError({ cause })),\n  );\n\n  const revoke: SessionStore[\"Service\"][\"revoke\"] = Effect.fn(\"SessionStore.revoke\")(\n    function* (sessionId) {\n      const revokedAt = yield* DateTime.now;\n      const revoked = yield* authSessions\n        .revoke({\n          sessionId,\n          revokedAt,\n        })\n        .pipe(Effect.mapError((cause) => new SessionRevocationError({ sessionId, cause })));\n      if (revoked) {\n        yield* Ref.update(connectedSessionsRef, (current) => {\n          const next = new Map(current);\n          next.delete(sessionId);\n          return next;\n        });\n        yield* emitRemoved(sessionId);\n      }\n      return revoked;\n    },\n  );\n\n  const revokeAllExcept: SessionStore[\"Service\"][\"revokeAllExcept\"] = Effect.fn(\n    \"SessionStore.revokeAllExcept\",\n  )(function* (sessionId) {\n    const revokedAt = yield* DateTime.now;\n    const revokedSessionIds = yield* authSessions\n      .revokeAllExcept({\n        currentSessionId: sessionId,\n        revokedAt,\n      })\n      .pipe(\n        Effect.mapError(\n          (cause) => new OtherSessionsRevocationError({ currentSessionId: sessionId, cause }),\n        ),\n      );\n    if (revokedSessionIds.length > 0) {\n      yield* Ref.update(connectedSessionsRef, (current) => {\n        const next = new Map(current);\n        for (const revokedSessionId of revokedSessionIds) {\n          next.delete(revokedSessionId);\n        }\n        return next;\n      });\n      yield* Effect.forEach(\n        revokedSessionIds,\n        (revokedSessionId) => emitRemoved(revokedSessionId),\n        {\n          concurrency: \"unbounded\",\n          discard: true,\n        },\n      );\n    }\n    return revokedSessionIds.length;\n  });\n\n  return SessionStore.of({\n    cookieName,\n    issue,\n    verify,\n    issueWebSocketToken,\n    verifyWebSocketToken,\n    listActive,\n    get streamChanges() {\n      return Stream.fromPubSub(changesPubSub);\n    },\n    revoke,\n    revokeAllExcept,\n    markConnected,\n    markDisconnected,\n  });\n});\n\nexport const layer = Layer.effect(SessionStore, make).pipe(Layer.provideMerge(AuthSessions.layer));\n","/**\n * Internal webcrypto alias.\n * We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.\n * Falls back to Node.js built-in crypto for Node.js <=v14.\n * See utils.ts for details.\n * @module\n */\n// @ts-ignore\nimport * as nc from 'node:crypto';\nexport const crypto = nc && typeof nc === 'object' && 'webcrypto' in nc\n    ? nc.webcrypto\n    : nc && typeof nc === 'object' && 'randomBytes' in nc\n        ? nc\n        : undefined;\n//# sourceMappingURL=cryptoNode.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n    if (!Number.isSafeInteger(n) || n < 0)\n        throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n    if (!isBytes(b))\n        throw new Error('Uint8Array expected');\n    if (lengths.length > 0 && !lengths.includes(b.length))\n        throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n    if (typeof h !== 'function' || typeof h.create !== 'function')\n        throw new Error('Hash should be wrapped by utils.createHasher');\n    anumber(h.outputLen);\n    anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n    if (instance.destroyed)\n        throw new Error('Hash instance has been destroyed');\n    if (checkFinished && instance.finished)\n        throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n    abytes(out);\n    const min = instance.outputLen;\n    if (out.length < min) {\n        throw new Error('digestInto() expects output buffer of length at least ' + min);\n    }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n    return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n    return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n    for (let i = 0; i < arrays.length; i++) {\n        arrays[i].fill(0);\n    }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n    return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n    return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n    return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n    return (((word << 24) & 0xff000000) |\n        ((word << 8) & 0xff0000) |\n        ((word >>> 8) & 0xff00) |\n        ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n    ? (n) => n\n    : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n    for (let i = 0; i < arr.length; i++) {\n        arr[i] = byteSwap(arr[i]);\n    }\n    return arr;\n}\nexport const swap32IfBE = isLE\n    ? (u) => u\n    : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n    abytes(bytes);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return bytes.toHex();\n    // pre-caching improves the speed 6x\n    let hex = '';\n    for (let i = 0; i < bytes.length; i++) {\n        hex += hexes[bytes[i]];\n    }\n    return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n    if (ch >= asciis._0 && ch <= asciis._9)\n        return ch - asciis._0; // '2' => 50-48\n    if (ch >= asciis.A && ch <= asciis.F)\n        return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n    if (ch >= asciis.a && ch <= asciis.f)\n        return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n    return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n    if (typeof hex !== 'string')\n        throw new Error('hex string expected, got ' + typeof hex);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return Uint8Array.fromHex(hex);\n    const hl = hex.length;\n    const al = hl / 2;\n    if (hl % 2)\n        throw new Error('hex string expected, got unpadded hex of length ' + hl);\n    const array = new Uint8Array(al);\n    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n        const n1 = asciiToBase16(hex.charCodeAt(hi));\n        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n        if (n1 === undefined || n2 === undefined) {\n            const char = hex[hi] + hex[hi + 1];\n            throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n        }\n        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n    }\n    return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n    let ts = Date.now();\n    for (let i = 0; i < iters; i++) {\n        cb(i);\n        // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n        const diff = Date.now() - ts;\n        if (diff >= 0 && diff < tick)\n            continue;\n        await nextTick();\n        ts += diff;\n    }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n    if (typeof str !== 'string')\n        throw new Error('string expected');\n    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n    return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n    if (typeof data === 'string')\n        data = utf8ToBytes(data);\n    abytes(data);\n    return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n    if (typeof data === 'string')\n        data = utf8ToBytes(data);\n    abytes(data);\n    return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n    let sum = 0;\n    for (let i = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        abytes(a);\n        sum += a.length;\n    }\n    const res = new Uint8Array(sum);\n    for (let i = 0, pad = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        res.set(a, pad);\n        pad += a.length;\n    }\n    return res;\n}\nexport function checkOpts(defaults, opts) {\n    if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n        throw new Error('options should be object or undefined');\n    const merged = Object.assign(defaults, opts);\n    return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n    const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n    const tmp = hashCons();\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.create = () => hashCons();\n    return hashC;\n}\nexport function createOptHasher(hashCons) {\n    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n    const tmp = hashCons({});\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.create = (opts) => hashCons(opts);\n    return hashC;\n}\nexport function createXOFer(hashCons) {\n    const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n    const tmp = hashCons({});\n    hashC.outputLen = tmp.outputLen;\n    hashC.blockLen = tmp.blockLen;\n    hashC.create = (opts) => hashCons(opts);\n    return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n    if (crypto && typeof crypto.getRandomValues === 'function') {\n        return crypto.getRandomValues(new Uint8Array(bytesLength));\n    }\n    // Legacy Node.js compatibility\n    if (crypto && typeof crypto.randomBytes === 'function') {\n        return Uint8Array.from(crypto.randomBytes(bytesLength));\n    }\n    throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport { Hash, abytes, aexists, aoutput, clean, createView, toBytes } from \"./utils.js\";\n/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */\nexport function setBigUint64(view, byteOffset, value, isLE) {\n    if (typeof view.setBigUint64 === 'function')\n        return view.setBigUint64(byteOffset, value, isLE);\n    const _32n = BigInt(32);\n    const _u32_max = BigInt(0xffffffff);\n    const wh = Number((value >> _32n) & _u32_max);\n    const wl = Number(value & _u32_max);\n    const h = isLE ? 4 : 0;\n    const l = isLE ? 0 : 4;\n    view.setUint32(byteOffset + h, wh, isLE);\n    view.setUint32(byteOffset + l, wl, isLE);\n}\n/** Choice: a ? b : c */\nexport function Chi(a, b, c) {\n    return (a & b) ^ (~a & c);\n}\n/** Majority function, true if any two inputs is true. */\nexport function Maj(a, b, c) {\n    return (a & b) ^ (a & c) ^ (b & c);\n}\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport class HashMD extends Hash {\n    constructor(blockLen, outputLen, padOffset, isLE) {\n        super();\n        this.finished = false;\n        this.length = 0;\n        this.pos = 0;\n        this.destroyed = false;\n        this.blockLen = blockLen;\n        this.outputLen = outputLen;\n        this.padOffset = padOffset;\n        this.isLE = isLE;\n        this.buffer = new Uint8Array(blockLen);\n        this.view = createView(this.buffer);\n    }\n    update(data) {\n        aexists(this);\n        data = toBytes(data);\n        abytes(data);\n        const { view, buffer, blockLen } = this;\n        const len = data.length;\n        for (let pos = 0; pos < len;) {\n            const take = Math.min(blockLen - this.pos, len - pos);\n            // Fast path: we have at least one block in input, cast it to view and process\n            if (take === blockLen) {\n                const dataView = createView(data);\n                for (; blockLen <= len - pos; pos += blockLen)\n                    this.process(dataView, pos);\n                continue;\n            }\n            buffer.set(data.subarray(pos, pos + take), this.pos);\n            this.pos += take;\n            pos += take;\n            if (this.pos === blockLen) {\n                this.process(view, 0);\n                this.pos = 0;\n            }\n        }\n        this.length += data.length;\n        this.roundClean();\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        aoutput(out, this);\n        this.finished = true;\n        // Padding\n        // We can avoid allocation of buffer for padding completely if it\n        // was previously not allocated here. But it won't change performance.\n        const { buffer, view, blockLen, isLE } = this;\n        let { pos } = this;\n        // append the bit '1' to the message\n        buffer[pos++] = 0b10000000;\n        clean(this.buffer.subarray(pos));\n        // we have less than padOffset left in buffer, so we cannot put length in\n        // current block, need process it and pad again\n        if (this.padOffset > blockLen - pos) {\n            this.process(view, 0);\n            pos = 0;\n        }\n        // Pad until full block byte with zeros\n        for (let i = pos; i < blockLen; i++)\n            buffer[i] = 0;\n        // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n        // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n        // So we just write lowest 64 bits of that value.\n        setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n        this.process(view, 0);\n        const oview = createView(out);\n        const len = this.outputLen;\n        // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n        if (len % 4)\n            throw new Error('_sha2: outputLen should be aligned to 32bit');\n        const outLen = len / 4;\n        const state = this.get();\n        if (outLen > state.length)\n            throw new Error('_sha2: outputLen bigger than state');\n        for (let i = 0; i < outLen; i++)\n            oview.setUint32(4 * i, state[i], isLE);\n    }\n    digest() {\n        const { buffer, outputLen } = this;\n        this.digestInto(buffer);\n        const res = buffer.slice(0, outputLen);\n        this.destroy();\n        return res;\n    }\n    _cloneInto(to) {\n        to || (to = new this.constructor());\n        to.set(...this.get());\n        const { blockLen, buffer, length, finished, destroyed, pos } = this;\n        to.destroyed = destroyed;\n        to.finished = finished;\n        to.length = length;\n        to.pos = pos;\n        if (length % blockLen)\n            to.buffer.set(buffer);\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n}\n/**\n * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.\n * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.\n */\n/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */\nexport const SHA256_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\n/** Initial SHA224 state. Bits 32..64 of frac part of sqrt of primes 23..53 */\nexport const SHA224_IV = /* @__PURE__ */ Uint32Array.from([\n    0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\n/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */\nexport const SHA384_IV = /* @__PURE__ */ Uint32Array.from([\n    0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n    0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\n/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */\nexport const SHA512_IV = /* @__PURE__ */ Uint32Array.from([\n    0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n    0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n//# sourceMappingURL=_md.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n    if (le)\n        return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n    return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n    const len = lst.length;\n    let Ah = new Uint32Array(len);\n    let Al = new Uint32Array(len);\n    for (let i = 0; i < len; i++) {\n        const { h, l } = fromBig(lst[i], le);\n        [Ah[i], Al[i]] = [h, l];\n    }\n    return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n    const l = (Al >>> 0) + (Bl >>> 0);\n    return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n    fromBig, split, toBig,\n    shrSH, shrSL,\n    rotrSH, rotrSL, rotrBH, rotrBL,\n    rotr32H, rotr32L,\n    rotlSH, rotlSL, rotlBH, rotlBL,\n    add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.\n * SHA256 is the fastest hash implementable in JS, even faster than Blake3.\n * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and\n * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).\n * @module\n */\nimport { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from \"./_md.js\";\nimport * as u64 from \"./_u64.js\";\nimport { clean, createHasher, rotr } from \"./utils.js\";\n/**\n * Round constants:\n * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)\n */\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ Uint32Array.from([\n    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n    0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n    0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n    0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n    0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n    0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n    0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n/** Reusable temporary buffer. \"W\" comes straight from spec. */\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nexport class SHA256 extends HashMD {\n    constructor(outputLen = 32) {\n        super(64, outputLen, 8, false);\n        // We cannot use array here since array allows indexing by variable\n        // which means optimizer/compiler cannot use registers.\n        this.A = SHA256_IV[0] | 0;\n        this.B = SHA256_IV[1] | 0;\n        this.C = SHA256_IV[2] | 0;\n        this.D = SHA256_IV[3] | 0;\n        this.E = SHA256_IV[4] | 0;\n        this.F = SHA256_IV[5] | 0;\n        this.G = SHA256_IV[6] | 0;\n        this.H = SHA256_IV[7] | 0;\n    }\n    get() {\n        const { A, B, C, D, E, F, G, H } = this;\n        return [A, B, C, D, E, F, G, H];\n    }\n    // prettier-ignore\n    set(A, B, C, D, E, F, G, H) {\n        this.A = A | 0;\n        this.B = B | 0;\n        this.C = C | 0;\n        this.D = D | 0;\n        this.E = E | 0;\n        this.F = F | 0;\n        this.G = G | 0;\n        this.H = H | 0;\n    }\n    process(view, offset) {\n        // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n        for (let i = 0; i < 16; i++, offset += 4)\n            SHA256_W[i] = view.getUint32(offset, false);\n        for (let i = 16; i < 64; i++) {\n            const W15 = SHA256_W[i - 15];\n            const W2 = SHA256_W[i - 2];\n            const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n            const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n            SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n        }\n        // Compression function main loop, 64 rounds\n        let { A, B, C, D, E, F, G, H } = this;\n        for (let i = 0; i < 64; i++) {\n            const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n            const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n            const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n            const T2 = (sigma0 + Maj(A, B, C)) | 0;\n            H = G;\n            G = F;\n            F = E;\n            E = (D + T1) | 0;\n            D = C;\n            C = B;\n            B = A;\n            A = (T1 + T2) | 0;\n        }\n        // Add the compressed chunk to the current hash value\n        A = (A + this.A) | 0;\n        B = (B + this.B) | 0;\n        C = (C + this.C) | 0;\n        D = (D + this.D) | 0;\n        E = (E + this.E) | 0;\n        F = (F + this.F) | 0;\n        G = (G + this.G) | 0;\n        H = (H + this.H) | 0;\n        this.set(A, B, C, D, E, F, G, H);\n    }\n    roundClean() {\n        clean(SHA256_W);\n    }\n    destroy() {\n        this.set(0, 0, 0, 0, 0, 0, 0, 0);\n        clean(this.buffer);\n    }\n}\nexport class SHA224 extends SHA256 {\n    constructor() {\n        super(28);\n        this.A = SHA224_IV[0] | 0;\n        this.B = SHA224_IV[1] | 0;\n        this.C = SHA224_IV[2] | 0;\n        this.D = SHA224_IV[3] | 0;\n        this.E = SHA224_IV[4] | 0;\n        this.F = SHA224_IV[5] | 0;\n        this.G = SHA224_IV[6] | 0;\n        this.H = SHA224_IV[7] | 0;\n    }\n}\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n// Round contants\n// First 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409\n// prettier-ignore\nconst K512 = /* @__PURE__ */ (() => u64.split([\n    '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n    '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n    '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n    '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n    '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n    '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n    '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n    '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n    '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n    '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n    '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n    '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n    '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n    '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n    '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n    '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n    '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n    '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n    '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n    '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\nconst SHA512_Kh = /* @__PURE__ */ (() => K512[0])();\nconst SHA512_Kl = /* @__PURE__ */ (() => K512[1])();\n// Reusable temporary buffers\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends HashMD {\n    constructor(outputLen = 64) {\n        super(128, outputLen, 16, false);\n        // We cannot use array here since array allows indexing by variable\n        // which means optimizer/compiler cannot use registers.\n        // h -- high 32 bits, l -- low 32 bits\n        this.Ah = SHA512_IV[0] | 0;\n        this.Al = SHA512_IV[1] | 0;\n        this.Bh = SHA512_IV[2] | 0;\n        this.Bl = SHA512_IV[3] | 0;\n        this.Ch = SHA512_IV[4] | 0;\n        this.Cl = SHA512_IV[5] | 0;\n        this.Dh = SHA512_IV[6] | 0;\n        this.Dl = SHA512_IV[7] | 0;\n        this.Eh = SHA512_IV[8] | 0;\n        this.El = SHA512_IV[9] | 0;\n        this.Fh = SHA512_IV[10] | 0;\n        this.Fl = SHA512_IV[11] | 0;\n        this.Gh = SHA512_IV[12] | 0;\n        this.Gl = SHA512_IV[13] | 0;\n        this.Hh = SHA512_IV[14] | 0;\n        this.Hl = SHA512_IV[15] | 0;\n    }\n    // prettier-ignore\n    get() {\n        const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n        return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n    }\n    // prettier-ignore\n    set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n        this.Ah = Ah | 0;\n        this.Al = Al | 0;\n        this.Bh = Bh | 0;\n        this.Bl = Bl | 0;\n        this.Ch = Ch | 0;\n        this.Cl = Cl | 0;\n        this.Dh = Dh | 0;\n        this.Dl = Dl | 0;\n        this.Eh = Eh | 0;\n        this.El = El | 0;\n        this.Fh = Fh | 0;\n        this.Fl = Fl | 0;\n        this.Gh = Gh | 0;\n        this.Gl = Gl | 0;\n        this.Hh = Hh | 0;\n        this.Hl = Hl | 0;\n    }\n    process(view, offset) {\n        // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n        for (let i = 0; i < 16; i++, offset += 4) {\n            SHA512_W_H[i] = view.getUint32(offset);\n            SHA512_W_L[i] = view.getUint32((offset += 4));\n        }\n        for (let i = 16; i < 80; i++) {\n            // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n            const W15h = SHA512_W_H[i - 15] | 0;\n            const W15l = SHA512_W_L[i - 15] | 0;\n            const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n            const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n            // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n            const W2h = SHA512_W_H[i - 2] | 0;\n            const W2l = SHA512_W_L[i - 2] | 0;\n            const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n            const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n            // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n            const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n            const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n            SHA512_W_H[i] = SUMh | 0;\n            SHA512_W_L[i] = SUMl | 0;\n        }\n        let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n        // Compression function main loop, 80 rounds\n        for (let i = 0; i < 80; i++) {\n            // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n            const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n            const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n            //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n            const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n            const CHIl = (El & Fl) ^ (~El & Gl);\n            // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n            // prettier-ignore\n            const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n            const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n            const T1l = T1ll | 0;\n            // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n            const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n            const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n            const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n            const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n            Hh = Gh | 0;\n            Hl = Gl | 0;\n            Gh = Fh | 0;\n            Gl = Fl | 0;\n            Fh = Eh | 0;\n            Fl = El | 0;\n            ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n            Dh = Ch | 0;\n            Dl = Cl | 0;\n            Ch = Bh | 0;\n            Cl = Bl | 0;\n            Bh = Ah | 0;\n            Bl = Al | 0;\n            const All = u64.add3L(T1l, sigma0l, MAJl);\n            Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n            Al = All | 0;\n        }\n        // Add the compressed chunk to the current hash value\n        ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n        ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n        ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n        ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n        ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n        ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n        ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n        ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n        this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n    }\n    roundClean() {\n        clean(SHA512_W_H, SHA512_W_L);\n    }\n    destroy() {\n        clean(this.buffer);\n        this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n    }\n}\nexport class SHA384 extends SHA512 {\n    constructor() {\n        super(48);\n        this.Ah = SHA384_IV[0] | 0;\n        this.Al = SHA384_IV[1] | 0;\n        this.Bh = SHA384_IV[2] | 0;\n        this.Bl = SHA384_IV[3] | 0;\n        this.Ch = SHA384_IV[4] | 0;\n        this.Cl = SHA384_IV[5] | 0;\n        this.Dh = SHA384_IV[6] | 0;\n        this.Dl = SHA384_IV[7] | 0;\n        this.Eh = SHA384_IV[8] | 0;\n        this.El = SHA384_IV[9] | 0;\n        this.Fh = SHA384_IV[10] | 0;\n        this.Fl = SHA384_IV[11] | 0;\n        this.Gh = SHA384_IV[12] | 0;\n        this.Gl = SHA384_IV[13] | 0;\n        this.Hh = SHA384_IV[14] | 0;\n        this.Hl = SHA384_IV[15] | 0;\n    }\n}\n/**\n * Truncated SHA512/256 and SHA512/224.\n * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as \"intermediary\" IV of SHA512/t.\n * Then t hashes string to produce result IV.\n * See `test/misc/sha2-gen-iv.js`.\n */\n/** SHA512/224 IV */\nconst T224_IV = /* @__PURE__ */ Uint32Array.from([\n    0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf,\n    0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1,\n]);\n/** SHA512/256 IV */\nconst T256_IV = /* @__PURE__ */ Uint32Array.from([\n    0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd,\n    0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2,\n]);\nexport class SHA512_224 extends SHA512 {\n    constructor() {\n        super(28);\n        this.Ah = T224_IV[0] | 0;\n        this.Al = T224_IV[1] | 0;\n        this.Bh = T224_IV[2] | 0;\n        this.Bl = T224_IV[3] | 0;\n        this.Ch = T224_IV[4] | 0;\n        this.Cl = T224_IV[5] | 0;\n        this.Dh = T224_IV[6] | 0;\n        this.Dl = T224_IV[7] | 0;\n        this.Eh = T224_IV[8] | 0;\n        this.El = T224_IV[9] | 0;\n        this.Fh = T224_IV[10] | 0;\n        this.Fl = T224_IV[11] | 0;\n        this.Gh = T224_IV[12] | 0;\n        this.Gl = T224_IV[13] | 0;\n        this.Hh = T224_IV[14] | 0;\n        this.Hl = T224_IV[15] | 0;\n    }\n}\nexport class SHA512_256 extends SHA512 {\n    constructor() {\n        super(32);\n        this.Ah = T256_IV[0] | 0;\n        this.Al = T256_IV[1] | 0;\n        this.Bh = T256_IV[2] | 0;\n        this.Bl = T256_IV[3] | 0;\n        this.Ch = T256_IV[4] | 0;\n        this.Cl = T256_IV[5] | 0;\n        this.Dh = T256_IV[6] | 0;\n        this.Dl = T256_IV[7] | 0;\n        this.Eh = T256_IV[8] | 0;\n        this.El = T256_IV[9] | 0;\n        this.Fh = T256_IV[10] | 0;\n        this.Fl = T256_IV[11] | 0;\n        this.Gh = T256_IV[12] | 0;\n        this.Gl = T256_IV[13] | 0;\n        this.Hh = T256_IV[14] | 0;\n        this.Hl = T256_IV[15] | 0;\n    }\n}\n/**\n * SHA2-256 hash function from RFC 4634.\n *\n * It is the fastest JS hash, even faster than Blake3.\n * To break sha256 using birthday attack, attackers need to try 2^128 hashes.\n * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.\n */\nexport const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());\n/** SHA2-224 hash function from RFC 4634 */\nexport const sha224 = /* @__PURE__ */ createHasher(() => new SHA224());\n/** SHA2-512 hash function from RFC 4634. */\nexport const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());\n/** SHA2-384 hash function from RFC 4634. */\nexport const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());\n/**\n * SHA2-512/256 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_256 = /* @__PURE__ */ createHasher(() => new SHA512_256());\n/**\n * SHA2-512/224 \"truncated\" hash function, with improved resistance to length extension attacks.\n * See the paper on [truncated SHA512](https://eprint.iacr.org/2010/548.pdf).\n */\nexport const sha512_224 = /* @__PURE__ */ createHasher(() => new SHA512_224());\n//# sourceMappingURL=sha2.js.map","/**\n * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport { abytes, aexists, ahash, clean, Hash, toBytes } from \"./utils.js\";\nexport class HMAC extends Hash {\n    constructor(hash, _key) {\n        super();\n        this.finished = false;\n        this.destroyed = false;\n        ahash(hash);\n        const key = toBytes(_key);\n        this.iHash = hash.create();\n        if (typeof this.iHash.update !== 'function')\n            throw new Error('Expected instance of class which extends utils.Hash');\n        this.blockLen = this.iHash.blockLen;\n        this.outputLen = this.iHash.outputLen;\n        const blockLen = this.blockLen;\n        const pad = new Uint8Array(blockLen);\n        // blockLen can be bigger than outputLen\n        pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n        for (let i = 0; i < pad.length; i++)\n            pad[i] ^= 0x36;\n        this.iHash.update(pad);\n        // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n        this.oHash = hash.create();\n        // Undo internal XOR && apply outer XOR\n        for (let i = 0; i < pad.length; i++)\n            pad[i] ^= 0x36 ^ 0x5c;\n        this.oHash.update(pad);\n        clean(pad);\n    }\n    update(buf) {\n        aexists(this);\n        this.iHash.update(buf);\n        return this;\n    }\n    digestInto(out) {\n        aexists(this);\n        abytes(out, this.outputLen);\n        this.finished = true;\n        this.iHash.digestInto(out);\n        this.oHash.update(out);\n        this.oHash.digestInto(out);\n        this.destroy();\n    }\n    digest() {\n        const out = new Uint8Array(this.oHash.outputLen);\n        this.digestInto(out);\n        return out;\n    }\n    _cloneInto(to) {\n        // Create new instance without calling constructor since key already in state and we don't know it.\n        to || (to = Object.create(Object.getPrototypeOf(this), {}));\n        const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n        to = to;\n        to.finished = finished;\n        to.destroyed = destroyed;\n        to.blockLen = blockLen;\n        to.outputLen = outputLen;\n        to.oHash = oHash._cloneInto(to.oHash);\n        to.iHash = iHash._cloneInto(to.iHash);\n        return to;\n    }\n    clone() {\n        return this._cloneInto();\n    }\n    destroy() {\n        this.destroyed = true;\n        this.oHash.destroy();\n        this.iHash.destroy();\n    }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n * @example\n * import { hmac } from '@noble/hashes/hmac';\n * import { sha256 } from '@noble/hashes/sha2';\n * const mac1 = hmac(sha256, 'key', 'message');\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nexport function isBytes(a) {\n    return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\nexport function abytes(item) {\n    if (!isBytes(item))\n        throw new Error('Uint8Array expected');\n}\nexport function abool(title, value) {\n    if (typeof value !== 'boolean')\n        throw new Error(title + ' boolean expected, got ' + value);\n}\n// Used in weierstrass, der\nexport function numberToHexUnpadded(num) {\n    const hex = num.toString(16);\n    return hex.length & 1 ? '0' + hex : hex;\n}\nexport function hexToNumber(hex) {\n    if (typeof hex !== 'string')\n        throw new Error('hex string expected, got ' + typeof hex);\n    return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n    abytes(bytes);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return bytes.toHex();\n    // pre-caching improves the speed 6x\n    let hex = '';\n    for (let i = 0; i < bytes.length; i++) {\n        hex += hexes[bytes[i]];\n    }\n    return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n    if (ch >= asciis._0 && ch <= asciis._9)\n        return ch - asciis._0; // '2' => 50-48\n    if (ch >= asciis.A && ch <= asciis.F)\n        return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n    if (ch >= asciis.a && ch <= asciis.f)\n        return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n    return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n    if (typeof hex !== 'string')\n        throw new Error('hex string expected, got ' + typeof hex);\n    // @ts-ignore\n    if (hasHexBuiltin)\n        return Uint8Array.fromHex(hex);\n    const hl = hex.length;\n    const al = hl / 2;\n    if (hl % 2)\n        throw new Error('hex string expected, got unpadded hex of length ' + hl);\n    const array = new Uint8Array(al);\n    for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n        const n1 = asciiToBase16(hex.charCodeAt(hi));\n        const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n        if (n1 === undefined || n2 === undefined) {\n            const char = hex[hi] + hex[hi + 1];\n            throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n        }\n        array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n    }\n    return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n    return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n    abytes(bytes);\n    return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n    return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n    return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n    return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n    let res;\n    if (typeof hex === 'string') {\n        try {\n            res = hexToBytes(hex);\n        }\n        catch (e) {\n            throw new Error(title + ' must be hex string or Uint8Array, cause: ' + e);\n        }\n    }\n    else if (isBytes(hex)) {\n        // Uint8Array.from() instead of hash.slice() because node.js Buffer\n        // is instance of Uint8Array, and its slice() creates **mutable** copy\n        res = Uint8Array.from(hex);\n    }\n    else {\n        throw new Error(title + ' must be hex string or Uint8Array');\n    }\n    const len = res.length;\n    if (typeof expectedLength === 'number' && len !== expectedLength)\n        throw new Error(title + ' of length ' + expectedLength + ' expected, got ' + len);\n    return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n    let sum = 0;\n    for (let i = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        abytes(a);\n        sum += a.length;\n    }\n    const res = new Uint8Array(sum);\n    for (let i = 0, pad = 0; i < arrays.length; i++) {\n        const a = arrays[i];\n        res.set(a, pad);\n        pad += a.length;\n    }\n    return res;\n}\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a, b) {\n    if (a.length !== b.length)\n        return false;\n    let diff = 0;\n    for (let i = 0; i < a.length; i++)\n        diff |= a[i] ^ b[i];\n    return diff === 0;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n    if (typeof str !== 'string')\n        throw new Error('string expected');\n    return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Is positive bigint\nconst isPosBig = (n) => typeof n === 'bigint' && _0n <= n;\nexport function inRange(n, min, max) {\n    return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\n/**\n * Asserts min <= n < max. NOTE: It's < max and not <= max.\n * @example\n * aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)\n */\nexport function aInRange(title, n, min, max) {\n    // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)?\n    // consider P=256n, min=0n, max=P\n    // - a for min=0 would require -1:          `inRange('x', x, -1n, P)`\n    // - b would commonly require subtraction:  `inRange('x', x, 0n, P - 1n)`\n    // - our way is the cleanest:               `inRange('x', x, 0n, P)\n    if (!inRange(n, min, max))\n        throw new Error('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n);\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n * TODO: merge with nLength in modular\n */\nexport function bitLen(n) {\n    let len;\n    for (len = 0; n > _0n; n >>= _1n, len += 1)\n        ;\n    return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n    return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport function bitSet(n, pos, value) {\n    return n | ((value ? _1n : _0n) << BigInt(pos));\n}\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_1n << BigInt(n)) - _1n;\n// DRBG\nconst u8n = (len) => new Uint8Array(len); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n *   const drbg = createHmacDRBG<Key>(32, 32, hmac);\n *   drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n    if (typeof hashLen !== 'number' || hashLen < 2)\n        throw new Error('hashLen must be a number');\n    if (typeof qByteLen !== 'number' || qByteLen < 2)\n        throw new Error('qByteLen must be a number');\n    if (typeof hmacFn !== 'function')\n        throw new Error('hmacFn must be a function');\n    // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n    let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n    let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n    let i = 0; // Iterations counter, will throw when over 1000\n    const reset = () => {\n        v.fill(1);\n        k.fill(0);\n        i = 0;\n    };\n    const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n    const reseed = (seed = u8n(0)) => {\n        // HMAC-DRBG reseed() function. Steps D-G\n        k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n        v = h(); // v = hmac(k || v)\n        if (seed.length === 0)\n            return;\n        k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n        v = h(); // v = hmac(k || v)\n    };\n    const gen = () => {\n        // HMAC-DRBG generate() function\n        if (i++ >= 1000)\n            throw new Error('drbg: tried 1000 values');\n        let len = 0;\n        const out = [];\n        while (len < qByteLen) {\n            v = h();\n            const sl = v.slice();\n            out.push(sl);\n            len += v.length;\n        }\n        return concatBytes(...out);\n    };\n    const genUntil = (seed, pred) => {\n        reset();\n        reseed(seed); // Steps D-G\n        let res = undefined; // Step H: grind until k is in [1..n-1]\n        while (!(res = pred(gen())))\n            reseed();\n        reset();\n        return res;\n    };\n    return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n    bigint: (val) => typeof val === 'bigint',\n    function: (val) => typeof val === 'function',\n    boolean: (val) => typeof val === 'boolean',\n    string: (val) => typeof val === 'string',\n    stringOrUint8Array: (val) => typeof val === 'string' || isBytes(val),\n    isSafeInteger: (val) => Number.isSafeInteger(val),\n    array: (val) => Array.isArray(val),\n    field: (val, object) => object.Fp.isValid(val),\n    hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n    const checkField = (fieldName, type, isOptional) => {\n        const checkVal = validatorFns[type];\n        if (typeof checkVal !== 'function')\n            throw new Error('invalid validator function');\n        const val = object[fieldName];\n        if (isOptional && val === undefined)\n            return;\n        if (!checkVal(val, object)) {\n            throw new Error('param ' + String(fieldName) + ' is invalid. Expected ' + type + ', got ' + val);\n        }\n    };\n    for (const [fieldName, type] of Object.entries(validators))\n        checkField(fieldName, type, false);\n    for (const [fieldName, type] of Object.entries(optValidators))\n        checkField(fieldName, type, true);\n    return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n/**\n * throws not implemented error\n */\nexport const notImplemented = () => {\n    throw new Error('not implemented');\n};\n/**\n * Memoizes (caches) computation result.\n * Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.\n */\nexport function memoized(fn) {\n    const map = new WeakMap();\n    return (arg, ...args) => {\n        const val = map.get(arg);\n        if (val !== undefined)\n            return val;\n        const computed = fn(arg, ...args);\n        map.set(arg, computed);\n        return computed;\n    };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Utils for modular division and finite fields.\n * A finite field over 11 is integer number operations `mod 11`.\n * There is no division: it is replaced by modular multiplicative inverse.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { anumber } from '@noble/hashes/utils';\nimport { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from \"./utils.js\";\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3);\n// prettier-ignore\nconst _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8);\n// Calculates a modulo b\nexport function mod(a, b) {\n    const result = a % b;\n    return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * TODO: remove.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\nexport function pow(num, power, modulo) {\n    return FpPow(Field(modulo), num, power);\n}\n/** Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)` */\nexport function pow2(x, power, modulo) {\n    let res = x;\n    while (power-- > _0n) {\n        res *= res;\n        res %= modulo;\n    }\n    return res;\n}\n/**\n * Inverses number over modulo.\n * Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).\n */\nexport function invert(number, modulo) {\n    if (number === _0n)\n        throw new Error('invert: expected non-zero number');\n    if (modulo <= _0n)\n        throw new Error('invert: expected positive modulus, got ' + modulo);\n    // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n    let a = mod(number, modulo);\n    let b = modulo;\n    // prettier-ignore\n    let x = _0n, y = _1n, u = _1n, v = _0n;\n    while (a !== _0n) {\n        // JIT applies optimization if those two lines follow each other\n        const q = b / a;\n        const r = b % a;\n        const m = x - u * q;\n        const n = y - v * q;\n        // prettier-ignore\n        b = a, a = r, x = u, y = v, u = m, v = n;\n    }\n    const gcd = b;\n    if (gcd !== _1n)\n        throw new Error('invert: does not exist');\n    return mod(x, modulo);\n}\n// Not all roots are possible! Example which will throw:\n// const NUM =\n// n = 72057594037927816n;\n// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'));\nfunction sqrt3mod4(Fp, n) {\n    const p1div4 = (Fp.ORDER + _1n) / _4n;\n    const root = Fp.pow(n, p1div4);\n    // Throw if root^2 != n\n    if (!Fp.eql(Fp.sqr(root), n))\n        throw new Error('Cannot find square root');\n    return root;\n}\nfunction sqrt5mod8(Fp, n) {\n    const p5div8 = (Fp.ORDER - _5n) / _8n;\n    const n2 = Fp.mul(n, _2n);\n    const v = Fp.pow(n2, p5div8);\n    const nv = Fp.mul(n, v);\n    const i = Fp.mul(Fp.mul(nv, _2n), v);\n    const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n    if (!Fp.eql(Fp.sqr(root), n))\n        throw new Error('Cannot find square root');\n    return root;\n}\n// TODO: Commented-out for now. Provide test vectors.\n// Tonelli is too slow for extension fields Fp2.\n// That means we can't use sqrt (c1, c2...) even for initialization constants.\n// if (P % _16n === _9n) return sqrt9mod16;\n// // prettier-ignore\n// function sqrt9mod16<T>(Fp: IField<T>, n: T, p7div16?: bigint) {\n//   if (p7div16 === undefined) p7div16 = (Fp.ORDER + BigInt(7)) / _16n;\n//   const c1 = Fp.sqrt(Fp.neg(Fp.ONE)); //  1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n//   const c2 = Fp.sqrt(c1);             //  2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n//   const c3 = Fp.sqrt(Fp.neg(c1));     //  3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n//   const c4 = p7div16;                 //  4. c4 = (q + 7) / 16        # Integer arithmetic\n//   let tv1 = Fp.pow(n, c4);            //  1. tv1 = x^c4\n//   let tv2 = Fp.mul(c1, tv1);          //  2. tv2 = c1 * tv1\n//   const tv3 = Fp.mul(c2, tv1);        //  3. tv3 = c2 * tv1\n//   let tv4 = Fp.mul(c3, tv1);          //  4. tv4 = c3 * tv1\n//   const e1 = Fp.eql(Fp.sqr(tv2), n);  //  5.  e1 = (tv2^2) == x\n//   const e2 = Fp.eql(Fp.sqr(tv3), n);  //  6.  e2 = (tv3^2) == x\n//   tv1 = Fp.cmov(tv1, tv2, e1); //  7. tv1 = CMOV(tv1, tv2, e1)  # Select tv2 if (tv2^2) == x\n//   tv2 = Fp.cmov(tv4, tv3, e2); //  8. tv2 = CMOV(tv4, tv3, e2)  # Select tv3 if (tv3^2) == x\n//   const e3 = Fp.eql(Fp.sqr(tv2), n);  //  9.  e3 = (tv2^2) == x\n//   return Fp.cmov(tv1, tv2, e3); // 10.  z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n// }\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n    // Initialization (precomputation).\n    if (P < BigInt(3))\n        throw new Error('sqrt is not defined for small field');\n    // Factor P - 1 = Q * 2^S, where Q is odd\n    let Q = P - _1n;\n    let S = 0;\n    while (Q % _2n === _0n) {\n        Q /= _2n;\n        S++;\n    }\n    // Find the first quadratic non-residue Z >= 2\n    let Z = _2n;\n    const _Fp = Field(P);\n    while (FpLegendre(_Fp, Z) === 1) {\n        // Basic primality test for P. After x iterations, chance of\n        // not finding quadratic non-residue is 2^x, so 2^1000.\n        if (Z++ > 1000)\n            throw new Error('Cannot find square root: probably non-prime P');\n    }\n    // Fast-path; usually done before Z, but we do \"primality test\".\n    if (S === 1)\n        return sqrt3mod4;\n    // Slow-path\n    // TODO: test on Fp2 and others\n    let cc = _Fp.pow(Z, Q); // c = z^Q\n    const Q1div2 = (Q + _1n) / _2n;\n    return function tonelliSlow(Fp, n) {\n        if (Fp.is0(n))\n            return n;\n        // Check if n is a quadratic residue using Legendre symbol\n        if (FpLegendre(Fp, n) !== 1)\n            throw new Error('Cannot find square root');\n        // Initialize variables for the main loop\n        let M = S;\n        let c = Fp.mul(Fp.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp\n        let t = Fp.pow(n, Q); // t = n^Q, first guess at the fudge factor\n        let R = Fp.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root\n        // Main loop\n        // while t != 1\n        while (!Fp.eql(t, Fp.ONE)) {\n            if (Fp.is0(t))\n                return Fp.ZERO; // if t=0 return R=0\n            let i = 1;\n            // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P)\n            let t_tmp = Fp.sqr(t); // t^(2^1)\n            while (!Fp.eql(t_tmp, Fp.ONE)) {\n                i++;\n                t_tmp = Fp.sqr(t_tmp); // t^(2^2)...\n                if (i === M)\n                    throw new Error('Cannot find square root');\n            }\n            // Calculate the exponent for b: 2^(M - i - 1)\n            const exponent = _1n << BigInt(M - i - 1); // bigint is important\n            const b = Fp.pow(c, exponent); // b = 2^(M - i - 1)\n            // Update variables\n            M = i;\n            c = Fp.sqr(b); // c = b^2\n            t = Fp.mul(t, c); // t = (t * b^2)\n            R = Fp.mul(R, b); // R = R*b\n        }\n        return R;\n    };\n}\n/**\n * Square root for a finite field. Will try optimized versions first:\n *\n * 1. P ≡ 3 (mod 4)\n * 2. P ≡ 5 (mod 8)\n * 3. Tonelli-Shanks algorithm\n *\n * Different algorithms can give different roots, it is up to user to decide which one they want.\n * For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n */\nexport function FpSqrt(P) {\n    // P ≡ 3 (mod 4) => √n = n^((P+1)/4)\n    if (P % _4n === _3n)\n        return sqrt3mod4;\n    // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n    if (P % _8n === _5n)\n        return sqrt5mod8;\n    // P ≡ 9 (mod 16) not implemented, see above\n    // Tonelli-Shanks algorithm\n    return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n    'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n    'eql', 'add', 'sub', 'mul', 'pow', 'div',\n    'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n    const initial = {\n        ORDER: 'bigint',\n        MASK: 'bigint',\n        BYTES: 'isSafeInteger',\n        BITS: 'isSafeInteger',\n    };\n    const opts = FIELD_FIELDS.reduce((map, val) => {\n        map[val] = 'function';\n        return map;\n    }, initial);\n    return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(Fp, num, power) {\n    if (power < _0n)\n        throw new Error('invalid exponent, negatives unsupported');\n    if (power === _0n)\n        return Fp.ONE;\n    if (power === _1n)\n        return num;\n    let p = Fp.ONE;\n    let d = num;\n    while (power > _0n) {\n        if (power & _1n)\n            p = Fp.mul(p, d);\n        d = Fp.sqr(d);\n        power >>= _1n;\n    }\n    return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Will return `undefined` for 0 elements.\n * @param passZero map 0 to 0 (instead of undefined)\n */\nexport function FpInvertBatch(Fp, nums, passZero = false) {\n    const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined);\n    // Walk from first to last, multiply them by each other MOD p\n    const multipliedAcc = nums.reduce((acc, num, i) => {\n        if (Fp.is0(num))\n            return acc;\n        inverted[i] = acc;\n        return Fp.mul(acc, num);\n    }, Fp.ONE);\n    // Invert last element\n    const invertedAcc = Fp.inv(multipliedAcc);\n    // Walk from last to first, multiply them by inverted each other MOD p\n    nums.reduceRight((acc, num, i) => {\n        if (Fp.is0(num))\n            return acc;\n        inverted[i] = Fp.mul(acc, inverted[i]);\n        return Fp.mul(acc, num);\n    }, invertedAcc);\n    return inverted;\n}\n// TODO: remove\nexport function FpDiv(Fp, lhs, rhs) {\n    return Fp.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, Fp.ORDER) : Fp.inv(rhs));\n}\n/**\n * Legendre symbol.\n * Legendre constant is used to calculate Legendre symbol (a | p)\n * which denotes the value of a^((p-1)/2) (mod p).\n *\n * * (a | p) ≡ 1    if a is a square (mod p), quadratic residue\n * * (a | p) ≡ -1   if a is not a square (mod p), quadratic non residue\n * * (a | p) ≡ 0    if a ≡ 0 (mod p)\n */\nexport function FpLegendre(Fp, n) {\n    // We can use 3rd argument as optional cache of this value\n    // but seems unneeded for now. The operation is very fast.\n    const p1mod2 = (Fp.ORDER - _1n) / _2n;\n    const powered = Fp.pow(n, p1mod2);\n    const yes = Fp.eql(powered, Fp.ONE);\n    const zero = Fp.eql(powered, Fp.ZERO);\n    const no = Fp.eql(powered, Fp.neg(Fp.ONE));\n    if (!yes && !zero && !no)\n        throw new Error('invalid Legendre symbol result');\n    return yes ? 1 : zero ? 0 : -1;\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(Fp, n) {\n    const l = FpLegendre(Fp, n);\n    return l === 1;\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n    // Bit size, byte size of CURVE.n\n    if (nBitLength !== undefined)\n        anumber(nBitLength);\n    const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n    const nByteLength = Math.ceil(_nBitLength / 8);\n    return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * Fragile: always run a benchmark on a change.\n * Security note: operations don't check 'isValid' for all elements for performance reasons,\n * it is caller responsibility to check this.\n * This is low-level code, please make sure you know what you're doing.\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n    if (ORDER <= _0n)\n        throw new Error('invalid field: expected ORDER > 0, got ' + ORDER);\n    const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n    if (BYTES > 2048)\n        throw new Error('invalid field: expected ORDER of <= 2048 bytes');\n    let sqrtP; // cached sqrtP\n    const f = Object.freeze({\n        ORDER,\n        isLE,\n        BITS,\n        BYTES,\n        MASK: bitMask(BITS),\n        ZERO: _0n,\n        ONE: _1n,\n        create: (num) => mod(num, ORDER),\n        isValid: (num) => {\n            if (typeof num !== 'bigint')\n                throw new Error('invalid field element: expected bigint, got ' + typeof num);\n            return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n        },\n        is0: (num) => num === _0n,\n        isOdd: (num) => (num & _1n) === _1n,\n        neg: (num) => mod(-num, ORDER),\n        eql: (lhs, rhs) => lhs === rhs,\n        sqr: (num) => mod(num * num, ORDER),\n        add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n        sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n        mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n        pow: (num, power) => FpPow(f, num, power),\n        div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n        // Same as above, but doesn't normalize\n        sqrN: (num) => num * num,\n        addN: (lhs, rhs) => lhs + rhs,\n        subN: (lhs, rhs) => lhs - rhs,\n        mulN: (lhs, rhs) => lhs * rhs,\n        inv: (num) => invert(num, ORDER),\n        sqrt: redef.sqrt ||\n            ((n) => {\n                if (!sqrtP)\n                    sqrtP = FpSqrt(ORDER);\n                return sqrtP(f, n);\n            }),\n        toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n        fromBytes: (bytes) => {\n            if (bytes.length !== BYTES)\n                throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length);\n            return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n        },\n        // TODO: we don't need it here, move out to separate fn\n        invertBatch: (lst) => FpInvertBatch(f, lst),\n        // We can't move this out because Fp6, Fp12 implement it\n        // and it's unclear what to return in there.\n        cmov: (a, b, c) => (c ? b : a),\n    });\n    return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n    if (!Fp.isOdd)\n        throw new Error(\"Field doesn't have isOdd\");\n    const root = Fp.sqrt(elm);\n    return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n    if (!Fp.isOdd)\n        throw new Error(\"Field doesn't have isOdd\");\n    const root = Fp.sqrt(elm);\n    return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use `mapKeyToField` instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n    hash = ensureBytes('privateHash', hash);\n    const hashLen = hash.length;\n    const minLen = nLength(groupOrder).nByteLength + 8;\n    if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n        throw new Error('hashToPrivateScalar: expected ' + minLen + '-1024 bytes of input, got ' + hashLen);\n    const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n    return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n    if (typeof fieldOrder !== 'bigint')\n        throw new Error('field order must be bigint');\n    const bitLength = fieldOrder.toString(2).length;\n    return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n    const length = getFieldBytesLength(fieldOrder);\n    return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n    const len = key.length;\n    const fieldLen = getFieldBytesLength(fieldOrder);\n    const minLen = getMinHashLength(fieldOrder);\n    // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n    if (len < 16 || len < minLen || len > 1024)\n        throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len);\n    const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key);\n    // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n    const reduced = mod(num, fieldOrder - _1n) + _1n;\n    return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { nLength, validateField } from \"./modular.js\";\nimport { bitLen, bitMask, validateObject } from \"./utils.js\";\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nfunction constTimeNegate(condition, item) {\n    const neg = item.negate();\n    return condition ? neg : item;\n}\nfunction validateW(W, bits) {\n    if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n        throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\nfunction calcWOpts(W, scalarBits) {\n    validateW(W, scalarBits);\n    const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n    const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n    const maxNumber = 2 ** W; // W=8 256\n    const mask = bitMask(W); // W=8 255 == mask 0b11111111\n    const shiftBy = BigInt(W); // W=8 8\n    return { windows, windowSize, mask, maxNumber, shiftBy };\n}\nfunction calcOffsets(n, window, wOpts) {\n    const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n    let wbits = Number(n & mask); // extract W bits.\n    let nextN = n >> shiftBy; // shift number by W bits.\n    // What actually happens here:\n    // const highestBit = Number(mask ^ (mask >> 1n));\n    // let wbits2 = wbits - 1; // skip zero\n    // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n    // split if bits > max: +224 => 256-32\n    if (wbits > windowSize) {\n        // we skip zero, which means instead of `>= size-1`, we do `> size`\n        wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n        nextN += _1n; // +256 (carry)\n    }\n    const offsetStart = window * windowSize;\n    const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero\n    const isZero = wbits === 0; // is current window slice a 0?\n    const isNeg = wbits < 0; // is current window slice negative?\n    const isNegF = window % 2 !== 0; // fake random statement for noise\n    const offsetF = offsetStart; // fake offset for noise\n    return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\nfunction validateMSMPoints(points, c) {\n    if (!Array.isArray(points))\n        throw new Error('array expected');\n    points.forEach((p, i) => {\n        if (!(p instanceof c))\n            throw new Error('invalid point at index ' + i);\n    });\n}\nfunction validateMSMScalars(scalars, field) {\n    if (!Array.isArray(scalars))\n        throw new Error('array of scalars expected');\n    scalars.forEach((s, i) => {\n        if (!field.isValid(s))\n            throw new Error('invalid scalar at index ' + i);\n    });\n}\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\nfunction getW(P) {\n    return pointWindowSizes.get(P) || 1;\n}\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * @todo Research returning 2d JS array of windows, instead of a single window.\n * This would allow windows to be in different memory locations\n */\nexport function wNAF(c, bits) {\n    return {\n        constTimeNegate,\n        hasPrecomputes(elm) {\n            return getW(elm) !== 1;\n        },\n        // non-const time multiplication ladder\n        unsafeLadder(elm, n, p = c.ZERO) {\n            let d = elm;\n            while (n > _0n) {\n                if (n & _1n)\n                    p = p.add(d);\n                d = d.double();\n                n >>= _1n;\n            }\n            return p;\n        },\n        /**\n         * Creates a wNAF precomputation window. Used for caching.\n         * Default window size is set by `utils.precompute()` and is equal to 8.\n         * Number of precomputed points depends on the curve size:\n         * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n         * - 𝑊 is the window size\n         * - 𝑛 is the bitlength of the curve order.\n         * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n         * @param elm Point instance\n         * @param W window size\n         * @returns precomputed point tables flattened to a single array\n         */\n        precomputeWindow(elm, W) {\n            const { windows, windowSize } = calcWOpts(W, bits);\n            const points = [];\n            let p = elm;\n            let base = p;\n            for (let window = 0; window < windows; window++) {\n                base = p;\n                points.push(base);\n                // i=1, bc we skip 0\n                for (let i = 1; i < windowSize; i++) {\n                    base = base.add(p);\n                    points.push(base);\n                }\n                p = base.double();\n            }\n            return points;\n        },\n        /**\n         * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n         * @param W window size\n         * @param precomputes precomputed tables\n         * @param n scalar (we don't check here, but should be less than curve order)\n         * @returns real and fake (for const-time) points\n         */\n        wNAF(W, precomputes, n) {\n            // Smaller version:\n            // https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n            // TODO: check the scalar is less than group order?\n            // wNAF behavior is undefined otherwise. But have to carefully remove\n            // other checks before wNAF. ORDER == bits here.\n            // Accumulators\n            let p = c.ZERO;\n            let f = c.BASE;\n            // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n            // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n            // there is negate now: it is possible that negated element from low value\n            // would be the same as high element, which will create carry into next window.\n            // It's not obvious how this can fail, but still worth investigating later.\n            const wo = calcWOpts(W, bits);\n            for (let window = 0; window < wo.windows; window++) {\n                // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n                const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n                n = nextN;\n                if (isZero) {\n                    // bits are 0: add garbage to fake point\n                    // Important part for const-time getPublicKey: add random \"noise\" point to f.\n                    f = f.add(constTimeNegate(isNegF, precomputes[offsetF]));\n                }\n                else {\n                    // bits are 1: add to result point\n                    p = p.add(constTimeNegate(isNeg, precomputes[offset]));\n                }\n            }\n            // Return both real and fake points: JIT won't eliminate f.\n            // At this point there is a way to F be infinity-point even if p is not,\n            // which makes it less const-time: around 1 bigint multiply.\n            return { p, f };\n        },\n        /**\n         * Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.\n         * @param W window size\n         * @param precomputes precomputed tables\n         * @param n scalar (we don't check here, but should be less than curve order)\n         * @param acc accumulator point to add result of multiplication\n         * @returns point\n         */\n        wNAFUnsafe(W, precomputes, n, acc = c.ZERO) {\n            const wo = calcWOpts(W, bits);\n            for (let window = 0; window < wo.windows; window++) {\n                if (n === _0n)\n                    break; // Early-exit, skip 0 value\n                const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n                n = nextN;\n                if (isZero) {\n                    // Window bits are 0: skip processing.\n                    // Move to next window.\n                    continue;\n                }\n                else {\n                    const item = precomputes[offset];\n                    acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n                }\n            }\n            return acc;\n        },\n        getPrecomputes(W, P, transform) {\n            // Calculate precomputes on a first run, reuse them after\n            let comp = pointPrecomputes.get(P);\n            if (!comp) {\n                comp = this.precomputeWindow(P, W);\n                if (W !== 1)\n                    pointPrecomputes.set(P, transform(comp));\n            }\n            return comp;\n        },\n        wNAFCached(P, n, transform) {\n            const W = getW(P);\n            return this.wNAF(W, this.getPrecomputes(W, P, transform), n);\n        },\n        wNAFCachedUnsafe(P, n, transform, prev) {\n            const W = getW(P);\n            if (W === 1)\n                return this.unsafeLadder(P, n, prev); // For W=1 ladder is ~x2 faster\n            return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev);\n        },\n        // We calculate precomputes for elliptic curve point multiplication\n        // using windowed method. This specifies window size and\n        // stores precomputed values. Usually only base point would be precomputed.\n        setWindowSize(P, W) {\n            validateW(W, bits);\n            pointWindowSizes.set(P, W);\n            pointPrecomputes.delete(P);\n        },\n    };\n}\n/**\n * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * 30x faster vs naive addition on L=4096, 10x faster than precomputes.\n * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.\n * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @param scalars array of L scalars (aka private keys / bigints)\n */\nexport function pippenger(c, fieldN, points, scalars) {\n    // If we split scalars by some window (let's say 8 bits), every chunk will only\n    // take 256 buckets even if there are 4096 scalars, also re-uses double.\n    // TODO:\n    // - https://eprint.iacr.org/2024/750.pdf\n    // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n    // 0 is accepted in scalars\n    validateMSMPoints(points, c);\n    validateMSMScalars(scalars, fieldN);\n    const plength = points.length;\n    const slength = scalars.length;\n    if (plength !== slength)\n        throw new Error('arrays of points and scalars must have equal length');\n    // if (plength === 0) throw new Error('array must be of length >= 2');\n    const zero = c.ZERO;\n    const wbits = bitLen(BigInt(plength));\n    let windowSize = 1; // bits\n    if (wbits > 12)\n        windowSize = wbits - 3;\n    else if (wbits > 4)\n        windowSize = wbits - 2;\n    else if (wbits > 0)\n        windowSize = 2;\n    const MASK = bitMask(windowSize);\n    const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array\n    const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;\n    let sum = zero;\n    for (let i = lastBits; i >= 0; i -= windowSize) {\n        buckets.fill(zero);\n        for (let j = 0; j < slength; j++) {\n            const scalar = scalars[j];\n            const wbits = Number((scalar >> BigInt(i)) & MASK);\n            buckets[wbits] = buckets[wbits].add(points[j]);\n        }\n        let resI = zero; // not using this will do small speed-up, but will lose ct\n        // Skip first bucket, because it is zero\n        for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {\n            sumI = sumI.add(buckets[j]);\n            resI = resI.add(sumI);\n        }\n        sum = sum.add(resI);\n        if (i !== 0)\n            for (let j = 0; j < windowSize; j++)\n                sum = sum.double();\n    }\n    return sum;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c Curve Point constructor\n * @param fieldN field over CURVE.N - important that it's not over CURVE.P\n * @param points array of L curve points\n * @returns function which multiplies points with scaars\n */\nexport function precomputeMSMUnsafe(c, fieldN, points, windowSize) {\n    /**\n     * Performance Analysis of Window-based Precomputation\n     *\n     * Base Case (256-bit scalar, 8-bit window):\n     * - Standard precomputation requires:\n     *   - 31 additions per scalar × 256 scalars = 7,936 ops\n     *   - Plus 255 summary additions = 8,191 total ops\n     *   Note: Summary additions can be optimized via accumulator\n     *\n     * Chunked Precomputation Analysis:\n     * - Using 32 chunks requires:\n     *   - 255 additions per chunk\n     *   - 256 doublings\n     *   - Total: (255 × 32) + 256 = 8,416 ops\n     *\n     * Memory Usage Comparison:\n     * Window Size | Standard Points | Chunked Points\n     * ------------|-----------------|---------------\n     *     4-bit   |     520         |      15\n     *     8-bit   |    4,224        |     255\n     *    10-bit   |   13,824        |   1,023\n     *    16-bit   |  557,056        |  65,535\n     *\n     * Key Advantages:\n     * 1. Enables larger window sizes due to reduced memory overhead\n     * 2. More efficient for smaller scalar counts:\n     *    - 16 chunks: (16 × 255) + 256 = 4,336 ops\n     *    - ~2x faster than standard 8,191 ops\n     *\n     * Limitations:\n     * - Not suitable for plain precomputes (requires 256 constant doublings)\n     * - Performance degrades with larger scalar counts:\n     *   - Optimal for ~256 scalars\n     *   - Less efficient for 4096+ scalars (Pippenger preferred)\n     */\n    validateW(windowSize, fieldN.BITS);\n    validateMSMPoints(points, c);\n    const zero = c.ZERO;\n    const tableSize = 2 ** windowSize - 1; // table size (without zero)\n    const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n    const MASK = bitMask(windowSize);\n    const tables = points.map((p) => {\n        const res = [];\n        for (let i = 0, acc = p; i < tableSize; i++) {\n            res.push(acc);\n            acc = acc.add(p);\n        }\n        return res;\n    });\n    return (scalars) => {\n        validateMSMScalars(scalars, fieldN);\n        if (scalars.length > points.length)\n            throw new Error('array of scalars must be smaller than array of points');\n        let res = zero;\n        for (let i = 0; i < chunks; i++) {\n            // No need to double if accumulator is still zero.\n            if (res !== zero)\n                for (let j = 0; j < windowSize; j++)\n                    res = res.double();\n            const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n            for (let j = 0; j < scalars.length; j++) {\n                const n = scalars[j];\n                const curr = Number((n >> shiftBy) & MASK);\n                if (!curr)\n                    continue; // skip zero scalars chunks\n                res = res.add(tables[j][curr - 1]);\n            }\n        }\n        return res;\n    };\n}\nexport function validateBasic(curve) {\n    validateField(curve.Fp);\n    validateObject(curve, {\n        n: 'bigint',\n        h: 'bigint',\n        Gx: 'field',\n        Gy: 'field',\n    }, {\n        nBitLength: 'isSafeInteger',\n        nByteLength: 'isSafeInteger',\n    });\n    // Set defaults\n    return Object.freeze({\n        ...nLength(curve.n, curve.nBitLength),\n        ...curve,\n        ...{ p: curve.Fp.ORDER },\n    });\n}\n//# sourceMappingURL=curve.js.map","/**\n * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.\n *\n * ### Parameters\n *\n * To initialize a weierstrass curve, one needs to pass following params:\n *\n * * a: formula param\n * * b: formula param\n * * Fp: finite field of prime characteristic P; may be complex (Fp2). Arithmetics is done in field\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * Gx: Base point (x, y) aka generator point. Gx = x coordinate\n * * Gy: ...y coordinate\n * * h: cofactor, usually 1. h*n = curve group order (n is only subgroup order)\n * * lowS: whether to enable (default) or disable \"low-s\" non-malleable signatures\n *\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n *   `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n *   `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n *   it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance\n * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create\n * unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n *     1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n *     which is hard to debug.\n *     2. Params can be generic and we can't enforce them to be constant value:\n *     if somebody creates curve from non-constant params,\n *     it would be allowed to interact with other curves with non-constant params\n *\n * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// prettier-ignore\nimport { pippenger, validateBasic, wNAF } from \"./curve.js\";\n// prettier-ignore\nimport { Field, FpInvertBatch, getMinHashLength, invert, mapHashToField, mod, validateField } from \"./modular.js\";\n// prettier-ignore\nimport { aInRange, abool, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, ensureBytes, hexToBytes, inRange, isBytes, memoized, numberToBytesBE, numberToHexUnpadded, validateObject } from \"./utils.js\";\nfunction validateSigVerOpts(opts) {\n    if (opts.lowS !== undefined)\n        abool('lowS', opts.lowS);\n    if (opts.prehash !== undefined)\n        abool('prehash', opts.prehash);\n}\nfunction validatePointOpts(curve) {\n    const opts = validateBasic(curve);\n    validateObject(opts, {\n        a: 'field',\n        b: 'field',\n    }, {\n        allowInfinityPoint: 'boolean',\n        allowedPrivateKeyLengths: 'array',\n        clearCofactor: 'function',\n        fromBytes: 'function',\n        isTorsionFree: 'function',\n        toBytes: 'function',\n        wrapPrivateKey: 'boolean',\n    });\n    const { endo, Fp, a } = opts;\n    if (endo) {\n        if (!Fp.eql(a, Fp.ZERO)) {\n            throw new Error('invalid endo: CURVE.a must be 0');\n        }\n        if (typeof endo !== 'object' ||\n            typeof endo.beta !== 'bigint' ||\n            typeof endo.splitScalar !== 'function') {\n            throw new Error('invalid endo: expected \"beta\": bigint and \"splitScalar\": function');\n        }\n    }\n    return Object.freeze({ ...opts });\n}\nexport class DERErr extends Error {\n    constructor(m = '') {\n        super(m);\n    }\n}\n/**\n * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:\n *\n *     [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]\n *\n * Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html\n */\nexport const DER = {\n    // asn.1 DER encoding utils\n    Err: DERErr,\n    // Basic building block is TLV (Tag-Length-Value)\n    _tlv: {\n        encode: (tag, data) => {\n            const { Err: E } = DER;\n            if (tag < 0 || tag > 256)\n                throw new E('tlv.encode: wrong tag');\n            if (data.length & 1)\n                throw new E('tlv.encode: unpadded data');\n            const dataLen = data.length / 2;\n            const len = numberToHexUnpadded(dataLen);\n            if ((len.length / 2) & 128)\n                throw new E('tlv.encode: long form length too big');\n            // length of length with long form flag\n            const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 128) : '';\n            const t = numberToHexUnpadded(tag);\n            return t + lenLen + len + data;\n        },\n        // v - value, l - left bytes (unparsed)\n        decode(tag, data) {\n            const { Err: E } = DER;\n            let pos = 0;\n            if (tag < 0 || tag > 256)\n                throw new E('tlv.encode: wrong tag');\n            if (data.length < 2 || data[pos++] !== tag)\n                throw new E('tlv.decode: wrong tlv');\n            const first = data[pos++];\n            const isLong = !!(first & 128); // First bit of first length byte is flag for short/long form\n            let length = 0;\n            if (!isLong)\n                length = first;\n            else {\n                // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n                const lenLen = first & 127;\n                if (!lenLen)\n                    throw new E('tlv.decode(long): indefinite length not supported');\n                if (lenLen > 4)\n                    throw new E('tlv.decode(long): byte length is too big'); // this will overflow u32 in js\n                const lengthBytes = data.subarray(pos, pos + lenLen);\n                if (lengthBytes.length !== lenLen)\n                    throw new E('tlv.decode: length bytes not complete');\n                if (lengthBytes[0] === 0)\n                    throw new E('tlv.decode(long): zero leftmost byte');\n                for (const b of lengthBytes)\n                    length = (length << 8) | b;\n                pos += lenLen;\n                if (length < 128)\n                    throw new E('tlv.decode(long): not minimal encoding');\n            }\n            const v = data.subarray(pos, pos + length);\n            if (v.length !== length)\n                throw new E('tlv.decode: wrong value length');\n            return { v, l: data.subarray(pos + length) };\n        },\n    },\n    // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n    // since we always use positive integers here. It must always be empty:\n    // - add zero byte if exists\n    // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n    _int: {\n        encode(num) {\n            const { Err: E } = DER;\n            if (num < _0n)\n                throw new E('integer: negative integers are not allowed');\n            let hex = numberToHexUnpadded(num);\n            // Pad with zero byte if negative flag is present\n            if (Number.parseInt(hex[0], 16) & 0b1000)\n                hex = '00' + hex;\n            if (hex.length & 1)\n                throw new E('unexpected DER parsing assertion: unpadded hex');\n            return hex;\n        },\n        decode(data) {\n            const { Err: E } = DER;\n            if (data[0] & 128)\n                throw new E('invalid signature integer: negative');\n            if (data[0] === 0x00 && !(data[1] & 128))\n                throw new E('invalid signature integer: unnecessary leading zero');\n            return bytesToNumberBE(data);\n        },\n    },\n    toSig(hex) {\n        // parse DER signature\n        const { Err: E, _int: int, _tlv: tlv } = DER;\n        const data = ensureBytes('signature', hex);\n        const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n        if (seqLeftBytes.length)\n            throw new E('invalid signature: left bytes after parsing');\n        const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes);\n        const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes);\n        if (sLeftBytes.length)\n            throw new E('invalid signature: left bytes after parsing');\n        return { r: int.decode(rBytes), s: int.decode(sBytes) };\n    },\n    hexFromSig(sig) {\n        const { _tlv: tlv, _int: int } = DER;\n        const rs = tlv.encode(0x02, int.encode(sig.r));\n        const ss = tlv.encode(0x02, int.encode(sig.s));\n        const seq = rs + ss;\n        return tlv.encode(0x30, seq);\n    },\n};\nfunction numToSizedHex(num, size) {\n    return bytesToHex(numberToBytesBE(num, size));\n}\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n    const CURVE = validatePointOpts(opts);\n    const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n    const Fn = Field(CURVE.n, CURVE.nBitLength);\n    const toBytes = CURVE.toBytes ||\n        ((_c, point, _isCompressed) => {\n            const a = point.toAffine();\n            return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n        });\n    const fromBytes = CURVE.fromBytes ||\n        ((bytes) => {\n            // const head = bytes[0];\n            const tail = bytes.subarray(1);\n            // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n            const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n            const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n            return { x, y };\n        });\n    /**\n     * y² = x³ + ax + b: Short weierstrass curve formula. Takes x, returns y².\n     * @returns y²\n     */\n    function weierstrassEquation(x) {\n        const { a, b } = CURVE;\n        const x2 = Fp.sqr(x); // x * x\n        const x3 = Fp.mul(x2, x); // x² * x\n        return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x³ + a * x + b\n    }\n    function isValidXY(x, y) {\n        const left = Fp.sqr(y); // y²\n        const right = weierstrassEquation(x); // x³ + ax + b\n        return Fp.eql(left, right);\n    }\n    // Validate whether the passed curve params are valid.\n    // Test 1: equation y² = x³ + ax + b should work for generator point.\n    if (!isValidXY(CURVE.Gx, CURVE.Gy))\n        throw new Error('bad curve params: generator point');\n    // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0.\n    // Guarantees curve is genus-1, smooth (non-singular).\n    const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);\n    const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));\n    if (Fp.is0(Fp.add(_4a3, _27b2)))\n        throw new Error('bad curve params: a or b');\n    // Valid group elements reside in range 1..n-1\n    function isWithinCurveOrder(num) {\n        return inRange(num, _1n, CURVE.n);\n    }\n    // Validates if priv key is valid and converts it to bigint.\n    // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n    function normPrivateKeyToScalar(key) {\n        const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE;\n        if (lengths && typeof key !== 'bigint') {\n            if (isBytes(key))\n                key = bytesToHex(key);\n            // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n            if (typeof key !== 'string' || !lengths.includes(key.length))\n                throw new Error('invalid private key');\n            key = key.padStart(nByteLength * 2, '0');\n        }\n        let num;\n        try {\n            num =\n                typeof key === 'bigint'\n                    ? key\n                    : bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n        }\n        catch (error) {\n            throw new Error('invalid private key, expected hex or ' + nByteLength + ' bytes, got ' + typeof key);\n        }\n        if (wrapPrivateKey)\n            num = mod(num, N); // disabled by default, enabled for BLS\n        aInRange('private key', num, _1n, N); // num in range [1..N-1]\n        return num;\n    }\n    function aprjpoint(other) {\n        if (!(other instanceof Point))\n            throw new Error('ProjectivePoint expected');\n    }\n    // Memoized toAffine / validity check. They are heavy. Points are immutable.\n    // Converts Projective point to affine (x, y) coordinates.\n    // Can accept precomputed Z^-1 - for example, from invertBatch.\n    // (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n    const toAffineMemo = memoized((p, iz) => {\n        const { px: x, py: y, pz: z } = p;\n        // Fast-path for normalized points\n        if (Fp.eql(z, Fp.ONE))\n            return { x, y };\n        const is0 = p.is0();\n        // If invZ was 0, we return zero point. However we still want to execute\n        // all operations, so we replace invZ with a random number, 1.\n        if (iz == null)\n            iz = is0 ? Fp.ONE : Fp.inv(z);\n        const ax = Fp.mul(x, iz);\n        const ay = Fp.mul(y, iz);\n        const zz = Fp.mul(z, iz);\n        if (is0)\n            return { x: Fp.ZERO, y: Fp.ZERO };\n        if (!Fp.eql(zz, Fp.ONE))\n            throw new Error('invZ was invalid');\n        return { x: ax, y: ay };\n    });\n    // NOTE: on exception this will crash 'cached' and no value will be set.\n    // Otherwise true will be return\n    const assertValidMemo = memoized((p) => {\n        if (p.is0()) {\n            // (0, 1, 0) aka ZERO is invalid in most contexts.\n            // In BLS, ZERO can be serialized, so we allow it.\n            // (0, 0, 0) is invalid representation of ZERO.\n            if (CURVE.allowInfinityPoint && !Fp.is0(p.py))\n                return;\n            throw new Error('bad point: ZERO');\n        }\n        // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n        const { x, y } = p.toAffine();\n        // Check if x, y are valid field elements\n        if (!Fp.isValid(x) || !Fp.isValid(y))\n            throw new Error('bad point: x or y not FE');\n        if (!isValidXY(x, y))\n            throw new Error('bad point: equation left != right');\n        if (!p.isTorsionFree())\n            throw new Error('bad point: not in prime-order subgroup');\n        return true;\n    });\n    /**\n     * Projective Point works in 3d / projective (homogeneous) coordinates: (X, Y, Z) ∋ (x=X/Z, y=Y/Z)\n     * Default Point works in 2d / affine coordinates: (x, y)\n     * We're doing calculations in projective, because its operations don't require costly inversion.\n     */\n    class Point {\n        constructor(px, py, pz) {\n            if (px == null || !Fp.isValid(px))\n                throw new Error('x required');\n            if (py == null || !Fp.isValid(py) || Fp.is0(py))\n                throw new Error('y required');\n            if (pz == null || !Fp.isValid(pz))\n                throw new Error('z required');\n            this.px = px;\n            this.py = py;\n            this.pz = pz;\n            Object.freeze(this);\n        }\n        // Does not validate if the point is on-curve.\n        // Use fromHex instead, or call assertValidity() later.\n        static fromAffine(p) {\n            const { x, y } = p || {};\n            if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n                throw new Error('invalid affine point');\n            if (p instanceof Point)\n                throw new Error('projective point not allowed');\n            const is0 = (i) => Fp.eql(i, Fp.ZERO);\n            // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n            if (is0(x) && is0(y))\n                return Point.ZERO;\n            return new Point(x, y, Fp.ONE);\n        }\n        get x() {\n            return this.toAffine().x;\n        }\n        get y() {\n            return this.toAffine().y;\n        }\n        /**\n         * Takes a bunch of Projective Points but executes only one\n         * inversion on all of them. Inversion is very slow operation,\n         * so this improves performance massively.\n         * Optimization: converts a list of projective points to a list of identical points with Z=1.\n         */\n        static normalizeZ(points) {\n            const toInv = FpInvertBatch(Fp, points.map((p) => p.pz));\n            return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n        }\n        /**\n         * Converts hash string or Uint8Array to Point.\n         * @param hex short/long ECDSA hex\n         */\n        static fromHex(hex) {\n            const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n            P.assertValidity();\n            return P;\n        }\n        // Multiplies generator point by privateKey.\n        static fromPrivateKey(privateKey) {\n            return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n        }\n        // Multiscalar Multiplication\n        static msm(points, scalars) {\n            return pippenger(Point, Fn, points, scalars);\n        }\n        // \"Private method\", don't use it directly\n        _setWindowSize(windowSize) {\n            wnaf.setWindowSize(this, windowSize);\n        }\n        // A point on curve is valid if it conforms to equation.\n        assertValidity() {\n            assertValidMemo(this);\n        }\n        hasEvenY() {\n            const { y } = this.toAffine();\n            if (Fp.isOdd)\n                return !Fp.isOdd(y);\n            throw new Error(\"Field doesn't support isOdd\");\n        }\n        /**\n         * Compare one point to another.\n         */\n        equals(other) {\n            aprjpoint(other);\n            const { px: X1, py: Y1, pz: Z1 } = this;\n            const { px: X2, py: Y2, pz: Z2 } = other;\n            const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n            const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n            return U1 && U2;\n        }\n        /**\n         * Flips point to one corresponding to (x, -y) in Affine coordinates.\n         */\n        negate() {\n            return new Point(this.px, Fp.neg(this.py), this.pz);\n        }\n        // Renes-Costello-Batina exception-free doubling formula.\n        // There is 30% faster Jacobian formula, but it is not complete.\n        // https://eprint.iacr.org/2015/1060, algorithm 3\n        // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n        double() {\n            const { a, b } = CURVE;\n            const b3 = Fp.mul(b, _3n);\n            const { px: X1, py: Y1, pz: Z1 } = this;\n            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n            let t0 = Fp.mul(X1, X1); // step 1\n            let t1 = Fp.mul(Y1, Y1);\n            let t2 = Fp.mul(Z1, Z1);\n            let t3 = Fp.mul(X1, Y1);\n            t3 = Fp.add(t3, t3); // step 5\n            Z3 = Fp.mul(X1, Z1);\n            Z3 = Fp.add(Z3, Z3);\n            X3 = Fp.mul(a, Z3);\n            Y3 = Fp.mul(b3, t2);\n            Y3 = Fp.add(X3, Y3); // step 10\n            X3 = Fp.sub(t1, Y3);\n            Y3 = Fp.add(t1, Y3);\n            Y3 = Fp.mul(X3, Y3);\n            X3 = Fp.mul(t3, X3);\n            Z3 = Fp.mul(b3, Z3); // step 15\n            t2 = Fp.mul(a, t2);\n            t3 = Fp.sub(t0, t2);\n            t3 = Fp.mul(a, t3);\n            t3 = Fp.add(t3, Z3);\n            Z3 = Fp.add(t0, t0); // step 20\n            t0 = Fp.add(Z3, t0);\n            t0 = Fp.add(t0, t2);\n            t0 = Fp.mul(t0, t3);\n            Y3 = Fp.add(Y3, t0);\n            t2 = Fp.mul(Y1, Z1); // step 25\n            t2 = Fp.add(t2, t2);\n            t0 = Fp.mul(t2, t3);\n            X3 = Fp.sub(X3, t0);\n            Z3 = Fp.mul(t2, t1);\n            Z3 = Fp.add(Z3, Z3); // step 30\n            Z3 = Fp.add(Z3, Z3);\n            return new Point(X3, Y3, Z3);\n        }\n        // Renes-Costello-Batina exception-free addition formula.\n        // There is 30% faster Jacobian formula, but it is not complete.\n        // https://eprint.iacr.org/2015/1060, algorithm 1\n        // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n        add(other) {\n            aprjpoint(other);\n            const { px: X1, py: Y1, pz: Z1 } = this;\n            const { px: X2, py: Y2, pz: Z2 } = other;\n            let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n            const a = CURVE.a;\n            const b3 = Fp.mul(CURVE.b, _3n);\n            let t0 = Fp.mul(X1, X2); // step 1\n            let t1 = Fp.mul(Y1, Y2);\n            let t2 = Fp.mul(Z1, Z2);\n            let t3 = Fp.add(X1, Y1);\n            let t4 = Fp.add(X2, Y2); // step 5\n            t3 = Fp.mul(t3, t4);\n            t4 = Fp.add(t0, t1);\n            t3 = Fp.sub(t3, t4);\n            t4 = Fp.add(X1, Z1);\n            let t5 = Fp.add(X2, Z2); // step 10\n            t4 = Fp.mul(t4, t5);\n            t5 = Fp.add(t0, t2);\n            t4 = Fp.sub(t4, t5);\n            t5 = Fp.add(Y1, Z1);\n            X3 = Fp.add(Y2, Z2); // step 15\n            t5 = Fp.mul(t5, X3);\n            X3 = Fp.add(t1, t2);\n            t5 = Fp.sub(t5, X3);\n            Z3 = Fp.mul(a, t4);\n            X3 = Fp.mul(b3, t2); // step 20\n            Z3 = Fp.add(X3, Z3);\n            X3 = Fp.sub(t1, Z3);\n            Z3 = Fp.add(t1, Z3);\n            Y3 = Fp.mul(X3, Z3);\n            t1 = Fp.add(t0, t0); // step 25\n            t1 = Fp.add(t1, t0);\n            t2 = Fp.mul(a, t2);\n            t4 = Fp.mul(b3, t4);\n            t1 = Fp.add(t1, t2);\n            t2 = Fp.sub(t0, t2); // step 30\n            t2 = Fp.mul(a, t2);\n            t4 = Fp.add(t4, t2);\n            t0 = Fp.mul(t1, t4);\n            Y3 = Fp.add(Y3, t0);\n            t0 = Fp.mul(t5, t4); // step 35\n            X3 = Fp.mul(t3, X3);\n            X3 = Fp.sub(X3, t0);\n            t0 = Fp.mul(t3, t1);\n            Z3 = Fp.mul(t5, Z3);\n            Z3 = Fp.add(Z3, t0); // step 40\n            return new Point(X3, Y3, Z3);\n        }\n        subtract(other) {\n            return this.add(other.negate());\n        }\n        is0() {\n            return this.equals(Point.ZERO);\n        }\n        wNAF(n) {\n            return wnaf.wNAFCached(this, n, Point.normalizeZ);\n        }\n        /**\n         * Non-constant-time multiplication. Uses double-and-add algorithm.\n         * It's faster, but should only be used when you don't care about\n         * an exposed private key e.g. sig verification, which works over *public* keys.\n         */\n        multiplyUnsafe(sc) {\n            const { endo, n: N } = CURVE;\n            aInRange('scalar', sc, _0n, N);\n            const I = Point.ZERO;\n            if (sc === _0n)\n                return I;\n            if (this.is0() || sc === _1n)\n                return this;\n            // Case a: no endomorphism. Case b: has precomputes.\n            if (!endo || wnaf.hasPrecomputes(this))\n                return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ);\n            // Case c: endomorphism\n            /** See docs for {@link EndomorphismOpts} */\n            let { k1neg, k1, k2neg, k2 } = endo.splitScalar(sc);\n            let k1p = I;\n            let k2p = I;\n            let d = this;\n            while (k1 > _0n || k2 > _0n) {\n                if (k1 & _1n)\n                    k1p = k1p.add(d);\n                if (k2 & _1n)\n                    k2p = k2p.add(d);\n                d = d.double();\n                k1 >>= _1n;\n                k2 >>= _1n;\n            }\n            if (k1neg)\n                k1p = k1p.negate();\n            if (k2neg)\n                k2p = k2p.negate();\n            k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n            return k1p.add(k2p);\n        }\n        /**\n         * Constant time multiplication.\n         * Uses wNAF method. Windowed method may be 10% faster,\n         * but takes 2x longer to generate and consumes 2x memory.\n         * Uses precomputes when available.\n         * Uses endomorphism for Koblitz curves.\n         * @param scalar by which the point would be multiplied\n         * @returns New point\n         */\n        multiply(scalar) {\n            const { endo, n: N } = CURVE;\n            aInRange('scalar', scalar, _1n, N);\n            let point, fake; // Fake point is used to const-time mult\n            /** See docs for {@link EndomorphismOpts} */\n            if (endo) {\n                const { k1neg, k1, k2neg, k2 } = endo.splitScalar(scalar);\n                let { p: k1p, f: f1p } = this.wNAF(k1);\n                let { p: k2p, f: f2p } = this.wNAF(k2);\n                k1p = wnaf.constTimeNegate(k1neg, k1p);\n                k2p = wnaf.constTimeNegate(k2neg, k2p);\n                k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n                point = k1p.add(k2p);\n                fake = f1p.add(f2p);\n            }\n            else {\n                const { p, f } = this.wNAF(scalar);\n                point = p;\n                fake = f;\n            }\n            // Normalize `z` for both points, but return only real one\n            return Point.normalizeZ([point, fake])[0];\n        }\n        /**\n         * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n         * Not using Strauss-Shamir trick: precomputation tables are faster.\n         * The trick could be useful if both P and Q are not G (not in our case).\n         * @returns non-zero affine point\n         */\n        multiplyAndAddUnsafe(Q, a, b) {\n            const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n            const mul = (P, a // Select faster multiply() method\n            ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n            const sum = mul(this, a).add(mul(Q, b));\n            return sum.is0() ? undefined : sum;\n        }\n        // Converts Projective point to affine (x, y) coordinates.\n        // Can accept precomputed Z^-1 - for example, from invertBatch.\n        // (x, y, z) ∋ (x=x/z, y=y/z)\n        toAffine(iz) {\n            return toAffineMemo(this, iz);\n        }\n        isTorsionFree() {\n            const { h: cofactor, isTorsionFree } = CURVE;\n            if (cofactor === _1n)\n                return true; // No subgroups, always torsion-free\n            if (isTorsionFree)\n                return isTorsionFree(Point, this);\n            throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n        }\n        clearCofactor() {\n            const { h: cofactor, clearCofactor } = CURVE;\n            if (cofactor === _1n)\n                return this; // Fast-path\n            if (clearCofactor)\n                return clearCofactor(Point, this);\n            return this.multiplyUnsafe(CURVE.h);\n        }\n        toRawBytes(isCompressed = true) {\n            abool('isCompressed', isCompressed);\n            this.assertValidity();\n            return toBytes(Point, this, isCompressed);\n        }\n        toHex(isCompressed = true) {\n            abool('isCompressed', isCompressed);\n            return bytesToHex(this.toRawBytes(isCompressed));\n        }\n    }\n    // base / generator point\n    Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n    // zero / infinity / identity point\n    Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n    const { endo, nBitLength } = CURVE;\n    const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength);\n    return {\n        CURVE,\n        ProjectivePoint: Point,\n        normPrivateKeyToScalar,\n        weierstrassEquation,\n        isWithinCurveOrder,\n    };\n}\nfunction validateOpts(curve) {\n    const opts = validateBasic(curve);\n    validateObject(opts, {\n        hash: 'hash',\n        hmac: 'function',\n        randomBytes: 'function',\n    }, {\n        bits2int: 'function',\n        bits2int_modN: 'function',\n        lowS: 'boolean',\n    });\n    return Object.freeze({ lowS: true, ...opts });\n}\n/**\n * Creates short weierstrass curve and ECDSA signature methods for it.\n * @example\n * import { Field } from '@noble/curves/abstract/modular';\n * // Before that, define BigInt-s: a, b, p, n, Gx, Gy\n * const curve = weierstrass({ a, b, Fp: Field(p), n, Gx, Gy, h: 1n })\n */\nexport function weierstrass(curveDef) {\n    const CURVE = validateOpts(curveDef);\n    const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE;\n    const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n    const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n    function modN(a) {\n        return mod(a, CURVE_ORDER);\n    }\n    function invN(a) {\n        return invert(a, CURVE_ORDER);\n    }\n    const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n        ...CURVE,\n        toBytes(_c, point, isCompressed) {\n            const a = point.toAffine();\n            const x = Fp.toBytes(a.x);\n            const cat = concatBytes;\n            abool('isCompressed', isCompressed);\n            if (isCompressed) {\n                return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n            }\n            else {\n                return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n            }\n        },\n        fromBytes(bytes) {\n            const len = bytes.length;\n            const head = bytes[0];\n            const tail = bytes.subarray(1);\n            // this.assertValidity() is done inside of fromHex\n            if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n                const x = bytesToNumberBE(tail);\n                if (!inRange(x, _1n, Fp.ORDER))\n                    throw new Error('Point is not on curve');\n                const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n                let y;\n                try {\n                    y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n                }\n                catch (sqrtError) {\n                    const suffix = sqrtError instanceof Error ? ': ' + sqrtError.message : '';\n                    throw new Error('Point is not on curve' + suffix);\n                }\n                const isYOdd = (y & _1n) === _1n;\n                // ECDSA\n                const isHeadOdd = (head & 1) === 1;\n                if (isHeadOdd !== isYOdd)\n                    y = Fp.neg(y);\n                return { x, y };\n            }\n            else if (len === uncompressedLen && head === 0x04) {\n                const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n                const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n                return { x, y };\n            }\n            else {\n                const cl = compressedLen;\n                const ul = uncompressedLen;\n                throw new Error('invalid Point, expected length of ' + cl + ', or uncompressed ' + ul + ', got ' + len);\n            }\n        },\n    });\n    function isBiggerThanHalfOrder(number) {\n        const HALF = CURVE_ORDER >> _1n;\n        return number > HALF;\n    }\n    function normalizeS(s) {\n        return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n    }\n    // slice bytes num\n    const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to));\n    /**\n     * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n     */\n    class Signature {\n        constructor(r, s, recovery) {\n            aInRange('r', r, _1n, CURVE_ORDER); // r in [1..N]\n            aInRange('s', s, _1n, CURVE_ORDER); // s in [1..N]\n            this.r = r;\n            this.s = s;\n            if (recovery != null)\n                this.recovery = recovery;\n            Object.freeze(this);\n        }\n        // pair (bytes of r, bytes of s)\n        static fromCompact(hex) {\n            const l = nByteLength;\n            hex = ensureBytes('compactSignature', hex, l * 2);\n            return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n        }\n        // DER encoded ECDSA signature\n        // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n        static fromDER(hex) {\n            const { r, s } = DER.toSig(ensureBytes('DER', hex));\n            return new Signature(r, s);\n        }\n        /**\n         * @todo remove\n         * @deprecated\n         */\n        assertValidity() { }\n        addRecoveryBit(recovery) {\n            return new Signature(this.r, this.s, recovery);\n        }\n        recoverPublicKey(msgHash) {\n            const { r, s, recovery: rec } = this;\n            const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n            if (rec == null || ![0, 1, 2, 3].includes(rec))\n                throw new Error('recovery id invalid');\n            const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n            if (radj >= Fp.ORDER)\n                throw new Error('recovery id 2 or 3 invalid');\n            const prefix = (rec & 1) === 0 ? '02' : '03';\n            const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES));\n            const ir = invN(radj); // r^-1\n            const u1 = modN(-h * ir); // -hr^-1\n            const u2 = modN(s * ir); // sr^-1\n            const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n            if (!Q)\n                throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n            Q.assertValidity();\n            return Q;\n        }\n        // Signatures should be low-s, to prevent malleability.\n        hasHighS() {\n            return isBiggerThanHalfOrder(this.s);\n        }\n        normalizeS() {\n            return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n        }\n        // DER-encoded\n        toDERRawBytes() {\n            return hexToBytes(this.toDERHex());\n        }\n        toDERHex() {\n            return DER.hexFromSig(this);\n        }\n        // padded bytes of r, then padded bytes of s\n        toCompactRawBytes() {\n            return hexToBytes(this.toCompactHex());\n        }\n        toCompactHex() {\n            const l = nByteLength;\n            return numToSizedHex(this.r, l) + numToSizedHex(this.s, l);\n        }\n    }\n    const utils = {\n        isValidPrivateKey(privateKey) {\n            try {\n                normPrivateKeyToScalar(privateKey);\n                return true;\n            }\n            catch (error) {\n                return false;\n            }\n        },\n        normPrivateKeyToScalar: normPrivateKeyToScalar,\n        /**\n         * Produces cryptographically secure private key from random of size\n         * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n         */\n        randomPrivateKey: () => {\n            const length = getMinHashLength(CURVE.n);\n            return mapHashToField(CURVE.randomBytes(length), CURVE.n);\n        },\n        /**\n         * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n         * Allows to massively speed-up `point.multiply(scalar)`.\n         * @returns cached point\n         * @example\n         * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n         * fast.multiply(privKey); // much faster ECDH now\n         */\n        precompute(windowSize = 8, point = Point.BASE) {\n            point._setWindowSize(windowSize);\n            point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n            return point;\n        },\n    };\n    /**\n     * Computes public key for a private key. Checks for validity of the private key.\n     * @param privateKey private key\n     * @param isCompressed whether to return compact (default), or full key\n     * @returns Public key, full when isCompressed=false; short when isCompressed=true\n     */\n    function getPublicKey(privateKey, isCompressed = true) {\n        return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n    }\n    /**\n     * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n     */\n    function isProbPub(item) {\n        if (typeof item === 'bigint')\n            return false;\n        if (item instanceof Point)\n            return true;\n        const arr = ensureBytes('key', item);\n        const len = arr.length;\n        const fpl = Fp.BYTES;\n        const compLen = fpl + 1; // e.g. 33 for 32\n        const uncompLen = 2 * fpl + 1; // e.g. 65 for 32\n        if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) {\n            return undefined;\n        }\n        else {\n            return len === compLen || len === uncompLen;\n        }\n    }\n    /**\n     * ECDH (Elliptic Curve Diffie Hellman).\n     * Computes shared public key from private key and public key.\n     * Checks: 1) private key validity 2) shared key is on-curve.\n     * Does NOT hash the result.\n     * @param privateA private key\n     * @param publicB different public key\n     * @param isCompressed whether to return compact (default), or full key\n     * @returns shared public key\n     */\n    function getSharedSecret(privateA, publicB, isCompressed = true) {\n        if (isProbPub(privateA) === true)\n            throw new Error('first arg must be private key');\n        if (isProbPub(publicB) === false)\n            throw new Error('second arg must be public key');\n        const b = Point.fromHex(publicB); // check for being on-curve\n        return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n    }\n    // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n    // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n    // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n    // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n    const bits2int = CURVE.bits2int ||\n        function (bytes) {\n            // Our custom check \"just in case\", for protection against DoS\n            if (bytes.length > 8192)\n                throw new Error('input is too large');\n            // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n            // for some cases, since bytes.length * 8 is not actual bitLength.\n            const num = bytesToNumberBE(bytes); // check for == u8 done here\n            const delta = bytes.length * 8 - nBitLength; // truncate to nBitLength leftmost bits\n            return delta > 0 ? num >> BigInt(delta) : num;\n        };\n    const bits2int_modN = CURVE.bits2int_modN ||\n        function (bytes) {\n            return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n        };\n    // NOTE: pads output with zero as per spec\n    const ORDER_MASK = bitMask(nBitLength);\n    /**\n     * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n     */\n    function int2octets(num) {\n        aInRange('num < 2^' + nBitLength, num, _0n, ORDER_MASK);\n        // works with order, can have different size than numToField!\n        return numberToBytesBE(num, nByteLength);\n    }\n    // Steps A, D of RFC6979 3.2\n    // Creates RFC6979 seed; converts msg/privKey to numbers.\n    // Used only in sign, not in verify.\n    // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order,\n    // this will be invalid at least for P521. Also it can be bigger for P224 + SHA256\n    function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n        if (['recovered', 'canonical'].some((k) => k in opts))\n            throw new Error('sign() legacy options not supported');\n        const { hash, randomBytes } = CURVE;\n        let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n        if (lowS == null)\n            lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n        msgHash = ensureBytes('msgHash', msgHash);\n        validateSigVerOpts(opts);\n        if (prehash)\n            msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n        // We can't later call bits2octets, since nested bits2int is broken for curves\n        // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n        // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n        const h1int = bits2int_modN(msgHash);\n        const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n        const seedArgs = [int2octets(d), int2octets(h1int)];\n        // extraEntropy. RFC6979 3.6: additional k' (optional).\n        if (ent != null && ent !== false) {\n            // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n            const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n            seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n        }\n        const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2\n        const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n        // Converts signature params into point w r/s, checks result for validity.\n        function k2sig(kBytes) {\n            // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n            const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n            if (!isWithinCurveOrder(k))\n                return; // Important: all mod() calls here must be done over N\n            const ik = invN(k); // k^-1 mod n\n            const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n            const r = modN(q.x); // r = q.x mod n\n            if (r === _0n)\n                return;\n            // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n            // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n            // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n            const s = modN(ik * modN(m + r * d)); // Not using blinding here\n            if (s === _0n)\n                return;\n            let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n            let normS = s;\n            if (lowS && isBiggerThanHalfOrder(s)) {\n                normS = normalizeS(s); // if lowS was passed, ensure s is always\n                recovery ^= 1; // // in the bottom half of N\n            }\n            return new Signature(r, normS, recovery); // use normS, not s\n        }\n        return { seed, k2sig };\n    }\n    const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n    const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n    /**\n     * Signs message hash with a private key.\n     * ```\n     * sign(m, d, k) where\n     *   (x, y) = G × k\n     *   r = x mod n\n     *   s = (m + dr)/k mod n\n     * ```\n     * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n     * @param privKey private key\n     * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n     * @returns signature with recovery param\n     */\n    function sign(msgHash, privKey, opts = defaultSigOpts) {\n        const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n        const C = CURVE;\n        const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n        return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n    }\n    // Enable precomputes. Slows down first publicKey computation by 20ms.\n    Point.BASE._setWindowSize(8);\n    // utils.precompute(8, ProjectivePoint.BASE)\n    /**\n     * Verifies a signature against message hash and public key.\n     * Rejects lowS signatures by default: to override,\n     * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n     *\n     * ```\n     * verify(r, s, h, P) where\n     *   U1 = hs^-1 mod n\n     *   U2 = rs^-1 mod n\n     *   R = U1⋅G - U2⋅P\n     *   mod(R.x, n) == r\n     * ```\n     */\n    function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n        const sg = signature;\n        msgHash = ensureBytes('msgHash', msgHash);\n        publicKey = ensureBytes('publicKey', publicKey);\n        const { lowS, prehash, format } = opts;\n        // Verify opts, deduce signature format\n        validateSigVerOpts(opts);\n        if ('strict' in opts)\n            throw new Error('options.strict was renamed to lowS');\n        if (format !== undefined && format !== 'compact' && format !== 'der')\n            throw new Error('format must be compact or der');\n        const isHex = typeof sg === 'string' || isBytes(sg);\n        const isObj = !isHex &&\n            !format &&\n            typeof sg === 'object' &&\n            sg !== null &&\n            typeof sg.r === 'bigint' &&\n            typeof sg.s === 'bigint';\n        if (!isHex && !isObj)\n            throw new Error('invalid signature, expected Uint8Array, hex string or Signature instance');\n        let _sig = undefined;\n        let P;\n        try {\n            if (isObj)\n                _sig = new Signature(sg.r, sg.s);\n            if (isHex) {\n                // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n                // Since DER can also be 2*nByteLength bytes, we check for it first.\n                try {\n                    if (format !== 'compact')\n                        _sig = Signature.fromDER(sg);\n                }\n                catch (derError) {\n                    if (!(derError instanceof DER.Err))\n                        throw derError;\n                }\n                if (!_sig && format !== 'der')\n                    _sig = Signature.fromCompact(sg);\n            }\n            P = Point.fromHex(publicKey);\n        }\n        catch (error) {\n            return false;\n        }\n        if (!_sig)\n            return false;\n        if (lowS && _sig.hasHighS())\n            return false;\n        if (prehash)\n            msgHash = CURVE.hash(msgHash);\n        const { r, s } = _sig;\n        const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n        const is = invN(s); // s^-1\n        const u1 = modN(h * is); // u1 = hs^-1 mod n\n        const u2 = modN(r * is); // u2 = rs^-1 mod n\n        const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n        if (!R)\n            return false;\n        const v = modN(R.x);\n        return v === r;\n    }\n    return {\n        CURVE,\n        getPublicKey,\n        getSharedSecret,\n        sign,\n        verify,\n        ProjectivePoint: Point,\n        Signature,\n        utils,\n    };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n    // Generic implementation\n    const q = Fp.ORDER;\n    let l = _0n;\n    for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n        l += _1n;\n    const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n    // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n    // 2n ** c1 == 2n << (c1-1)\n    const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n    const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n    const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1)  # Integer arithmetic\n    const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2            # Integer arithmetic\n    const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1                # Integer arithmetic\n    const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1)                  # Integer arithmetic\n    const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n    const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n    let sqrtRatio = (u, v) => {\n        let tv1 = c6; // 1. tv1 = c6\n        let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n        let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n        tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n        let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n        tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n        tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n        tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n        tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n        let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n        tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n        let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n        tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n        tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n        tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n        tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n        // 17. for i in (c1, c1 - 1, ..., 2):\n        for (let i = c1; i > _1n; i--) {\n            let tv5 = i - _2n; // 18.    tv5 = i - 2\n            tv5 = _2n << (tv5 - _1n); // 19.    tv5 = 2^tv5\n            let tvv5 = Fp.pow(tv4, tv5); // 20.    tv5 = tv4^tv5\n            const e1 = Fp.eql(tvv5, Fp.ONE); // 21.    e1 = tv5 == 1\n            tv2 = Fp.mul(tv3, tv1); // 22.    tv2 = tv3 * tv1\n            tv1 = Fp.mul(tv1, tv1); // 23.    tv1 = tv1 * tv1\n            tvv5 = Fp.mul(tv4, tv1); // 24.    tv5 = tv4 * tv1\n            tv3 = Fp.cmov(tv2, tv3, e1); // 25.    tv3 = CMOV(tv2, tv3, e1)\n            tv4 = Fp.cmov(tvv5, tv4, e1); // 26.    tv4 = CMOV(tv5, tv4, e1)\n        }\n        return { isValid: isQR, value: tv3 };\n    };\n    if (Fp.ORDER % _4n === _3n) {\n        // sqrt_ratio_3mod4(u, v)\n        const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4     # Integer arithmetic\n        const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n        sqrtRatio = (u, v) => {\n            let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n            const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n            tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n            let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n            y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n            const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n            const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n            const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n            let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n            return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n        };\n    }\n    // No curves uses that\n    // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n    return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n    validateField(Fp);\n    if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n        throw new Error('mapToCurveSimpleSWU: invalid opts');\n    const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n    if (!Fp.isOdd)\n        throw new Error('Fp.isOdd is not implemented!');\n    // Input: u, an element of F.\n    // Output: (x, y), a point on E.\n    return (u) => {\n        // prettier-ignore\n        let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n        tv1 = Fp.sqr(u); // 1.  tv1 = u^2\n        tv1 = Fp.mul(tv1, opts.Z); // 2.  tv1 = Z * tv1\n        tv2 = Fp.sqr(tv1); // 3.  tv2 = tv1^2\n        tv2 = Fp.add(tv2, tv1); // 4.  tv2 = tv2 + tv1\n        tv3 = Fp.add(tv2, Fp.ONE); // 5.  tv3 = tv2 + 1\n        tv3 = Fp.mul(tv3, opts.B); // 6.  tv3 = B * tv3\n        tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7.  tv4 = CMOV(Z, -tv2, tv2 != 0)\n        tv4 = Fp.mul(tv4, opts.A); // 8.  tv4 = A * tv4\n        tv2 = Fp.sqr(tv3); // 9.  tv2 = tv3^2\n        tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n        tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n        tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n        tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n        tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n        tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n        tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n        x = Fp.mul(tv1, tv3); // 17.   x = tv1 * tv3\n        const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n        y = Fp.mul(tv1, u); // 19.   y = tv1 * u  -> Z * u^3 * y1\n        y = Fp.mul(y, value); // 20.   y = y * y1\n        x = Fp.cmov(x, tv3, isValid); // 21.   x = CMOV(x, tv3, is_gx1_square)\n        y = Fp.cmov(y, value, isValid); // 22.   y = CMOV(y, y1, is_gx1_square)\n        const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23.  e1 = sgn0(u) == sgn0(y)\n        y = Fp.cmov(Fp.neg(y), y, e1); // 24.   y = CMOV(-y, y, e1)\n        const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0];\n        x = Fp.mul(x, tv4_inv); // 25.   x = x / tv4\n        return { x, y };\n    };\n}\n//# sourceMappingURL=weierstrass.js.map","/**\n * Utilities for short weierstrass curves, combined with noble-hashes.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from \"./abstract/weierstrass.js\";\n/** connects noble-curves to noble-hashes */\nexport function getHash(hash) {\n    return {\n        hash,\n        hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n        randomBytes,\n    };\n}\nexport function createCurve(curveDef, defHash) {\n    const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n    return { ...create(defHash), create };\n}\n//# sourceMappingURL=_shortw_utils.js.map","/**\n * Internal module for NIST P256, P384, P521 curves.\n * Do not use for now.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256, sha384, sha512 } from '@noble/hashes/sha2';\nimport { createCurve } from \"./_shortw_utils.js\";\nimport { createHasher } from \"./abstract/hash-to-curve.js\";\nimport { Field } from \"./abstract/modular.js\";\nimport { mapToCurveSimpleSWU } from \"./abstract/weierstrass.js\";\nconst Fp256 = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));\nconst p256_a = Fp256.create(BigInt('-3'));\nconst p256_b = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\n/**\n * secp256r1 curve, ECDSA and ECDH methods.\n * Field: `2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n`\n */\n// prettier-ignore\nexport const p256 = createCurve({\n    a: p256_a,\n    b: p256_b,\n    Fp: Fp256,\n    n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n    Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n    Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n    h: BigInt(1),\n    lowS: false\n}, sha256);\n/** Alias to p256. */\nexport const secp256r1 = p256;\nconst p256_mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp256, {\n    A: p256_a,\n    B: p256_b,\n    Z: Fp256.create(BigInt('-10')),\n}))();\n/** Hashing / encoding to p256 points / field. RFC 9380 methods. */\nexport const p256_hasher = /* @__PURE__ */ (() => createHasher(secp256r1.ProjectivePoint, (scalars) => p256_mapSWU(scalars[0]), {\n    DST: 'P256_XMD:SHA-256_SSWU_RO_',\n    encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n    p: Fp256.ORDER,\n    m: 1,\n    k: 128,\n    expand: 'xmd',\n    hash: sha256,\n}))();\n// Field over which we'll do calculations.\nconst Fp384 = Field(BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'));\nconst p384_a = Fp384.create(BigInt('-3'));\n// prettier-ignore\nconst p384_b = BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef');\n/**\n * secp384r1 curve, ECDSA and ECDH methods.\n * Field: `2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n`.\n * */\n// prettier-ignore\nexport const p384 = createCurve({\n    a: p384_a,\n    b: p384_b,\n    Fp: Fp384,\n    n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'),\n    Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'),\n    Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'),\n    h: BigInt(1),\n    lowS: false\n}, sha384);\n/** Alias to p384. */\nexport const secp384r1 = p384;\nconst p384_mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp384, {\n    A: p384_a,\n    B: p384_b,\n    Z: Fp384.create(BigInt('-12')),\n}))();\n/** Hashing / encoding to p384 points / field. RFC 9380 methods. */\nexport const p384_hasher = /* @__PURE__ */ (() => createHasher(secp384r1.ProjectivePoint, (scalars) => p384_mapSWU(scalars[0]), {\n    DST: 'P384_XMD:SHA-384_SSWU_RO_',\n    encodeDST: 'P384_XMD:SHA-384_SSWU_NU_',\n    p: Fp384.ORDER,\n    m: 1,\n    k: 192,\n    expand: 'xmd',\n    hash: sha384,\n}))();\n// Field over which we'll do calculations.\nconst Fp521 = Field(BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'));\nconst p521_a = Fp521.create(BigInt('-3'));\nconst p521_b = BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00');\n/**\n * NIST secp521r1 aka p521 curve, ECDSA and ECDH methods.\n * Field: `2n**521n - 1n`.\n */\n// prettier-ignore\nexport const p521 = createCurve({\n    a: p521_a,\n    b: p521_b,\n    Fp: Fp521,\n    n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'),\n    Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'),\n    Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'),\n    h: BigInt(1),\n    lowS: false,\n    allowedPrivateKeyLengths: [130, 131, 132] // P521 keys are variable-length. Normalize to 132b\n}, sha512);\n/** Alias to p521. */\nexport const secp521r1 = p521;\nconst p521_mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp521, {\n    A: p521_a,\n    B: p521_b,\n    Z: Fp521.create(BigInt('-4')),\n}))();\n/** Hashing / encoding to p521 points / field. RFC 9380 methods. */\nexport const p521_hasher = /* @__PURE__ */ (() => createHasher(secp521r1.ProjectivePoint, (scalars) => p521_mapSWU(scalars[0]), {\n    DST: 'P521_XMD:SHA-512_SSWU_RO_',\n    encodeDST: 'P521_XMD:SHA-512_SSWU_NU_',\n    p: Fp521.ORDER,\n    m: 1,\n    k: 256,\n    expand: 'xmd',\n    hash: sha512,\n}))();\n//# sourceMappingURL=nist.js.map","import * as Schema from \"effect/Schema\";\n\nexport const DpopPublicJwk = Schema.Struct({\n  kty: Schema.Literal(\"EC\"),\n  crv: Schema.Literal(\"P-256\"),\n  x: Schema.String.check(Schema.isNonEmpty()),\n  y: Schema.String.check(Schema.isNonEmpty()),\n});\nexport type DpopPublicJwk = typeof DpopPublicJwk.Type;\n\nexport function normalizeDpopHtu(url: string): string | null {\n  try {\n    const parsed = new URL(url);\n    parsed.hash = \"\";\n    parsed.search = \"\";\n    return parsed.toString();\n  } catch {\n    return null;\n  }\n}\n","function isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function stableStringify(value: unknown): string {\n  if (Array.isArray(value)) {\n    return `[${value.map(stableStringify).join(\",\")}]`;\n  }\n  if (isRecord(value)) {\n    return `{${Object.entries(value)\n      .filter(([, entryValue]) => entryValue !== undefined)\n      .sort(([left], [right]) => left.localeCompare(right))\n      .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableStringify(entryValue)}`)\n      .join(\",\")}}`;\n  }\n  return JSON.stringify(value) ?? \"null\";\n}\n","import { p256 } from \"@noble/curves/nist\";\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\nimport { DpopPublicJwk as DpopPublicJwkSchema, normalizeDpopHtu } from \"./dpopCommon.ts\";\nimport type { DpopPublicJwk as DpopPublicJwkType } from \"./dpopCommon.ts\";\nimport { stableStringify } from \"./relaySigning.ts\";\n\nconst DPOP_TYP = \"dpop+jwt\";\nconst DPOP_ALG = \"ES256\";\nconst DEFAULT_MAX_AGE_SECONDS = 300;\n\nexport const DpopPublicJwk = DpopPublicJwkSchema;\nexport type DpopPublicJwk = DpopPublicJwkType;\nexport { normalizeDpopHtu };\n\nconst DpopJwtHeaderPublicJwk = Schema.Struct({\n  ...DpopPublicJwkSchema.fields,\n  d: Schema.optionalKey(Schema.Never),\n});\n\nconst DpopJwtHeaderJson = Schema.fromJsonString(\n  Schema.Struct({\n    typ: Schema.Literal(DPOP_TYP),\n    alg: Schema.Literal(DPOP_ALG),\n    jwk: DpopJwtHeaderPublicJwk,\n  }),\n);\nconst decodeDpopJwtHeaderJson = Schema.decodeUnknownOption(DpopJwtHeaderJson);\n\nconst DpopJwtPayloadJson = Schema.fromJsonString(\n  Schema.Struct({\n    htm: Schema.String.check(Schema.isNonEmpty()),\n    htu: Schema.String.check(Schema.isNonEmpty()),\n    jti: Schema.String.check(Schema.isNonEmpty()),\n    iat: Schema.Int,\n    ath: Schema.optionalKey(Schema.String),\n  }),\n);\nconst decodeDpopJwtPayloadJson = Schema.decodeUnknownOption(DpopJwtPayloadJson);\n\nexport type DpopVerificationResult =\n  | {\n      readonly ok: true;\n      readonly thumbprint: string;\n      readonly jti: string;\n      readonly iat: number;\n    }\n  | {\n      readonly ok: false;\n      readonly reason: string;\n    };\n\nfunction base64UrlToBytes(value: string): Uint8Array {\n  return Result.getOrThrow(Encoding.decodeBase64Url(value));\n}\n\nfunction decodeBase64UrlDpopJwtHeader(value: string) {\n  return decodeDpopJwtHeaderJson(Result.getOrThrow(Encoding.decodeBase64UrlString(value)));\n}\n\nfunction decodeBase64UrlDpopJwtPayload(value: string) {\n  return decodeDpopJwtPayloadJson(Result.getOrThrow(Encoding.decodeBase64UrlString(value)));\n}\n\nfunction dpopThumbprintInput(jwk: DpopPublicJwkType): string {\n  return stableStringify({\n    crv: jwk.crv,\n    kty: jwk.kty,\n    x: jwk.x,\n    y: jwk.y,\n  });\n}\n\nexport function computeDpopJwkThumbprint(jwk: DpopPublicJwkType): string {\n  return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(dpopThumbprintInput(jwk))));\n}\n\nexport function computeDpopAccessTokenHash(accessToken: string): string {\n  return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(accessToken)));\n}\n\nfunction publicKeyBytesFromJwk(jwk: DpopPublicJwkType): Uint8Array {\n  const x = base64UrlToBytes(jwk.x);\n  const y = base64UrlToBytes(jwk.y);\n  if (x.length !== 32 || y.length !== 32) {\n    throw new Error(\"Invalid P-256 public key coordinate length.\");\n  }\n  const publicKey = new Uint8Array(65);\n  publicKey[0] = 0x04;\n  publicKey.set(x, 1);\n  publicKey.set(y, 33);\n  return publicKey;\n}\n\nexport function verifyDpopProof(input: {\n  readonly proof: string | null | undefined;\n  readonly method: string;\n  readonly url: string;\n  readonly nowEpochSeconds: number;\n  readonly expectedThumbprint?: string;\n  readonly expectedAccessToken?: string;\n  readonly maxAgeSeconds?: number;\n}): DpopVerificationResult {\n  if (!input.proof?.trim()) {\n    return { ok: false, reason: \"Missing DPoP proof.\" };\n  }\n\n  const parts = input.proof.split(\".\");\n  if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {\n    return { ok: false, reason: \"Invalid DPoP compact JWT.\" };\n  }\n\n  try {\n    const header = decodeBase64UrlDpopJwtHeader(parts[0]);\n    const payload = decodeBase64UrlDpopJwtPayload(parts[1]);\n    if (Option.isNone(header)) {\n      return { ok: false, reason: \"Invalid DPoP JWT header.\" };\n    }\n    if (Option.isNone(payload)) {\n      return { ok: false, reason: \"Invalid DPoP JWT payload.\" };\n    }\n\n    const thumbprint = computeDpopJwkThumbprint(header.value.jwk);\n    if (input.expectedThumbprint && thumbprint !== input.expectedThumbprint) {\n      return { ok: false, reason: \"DPoP key thumbprint mismatch.\" };\n    }\n    if (payload.value.htm.toUpperCase() !== input.method.toUpperCase()) {\n      return { ok: false, reason: \"DPoP method mismatch.\" };\n    }\n    const normalizedHtu = normalizeDpopHtu(input.url);\n    if (normalizedHtu === null || payload.value.htu !== normalizedHtu) {\n      return { ok: false, reason: \"DPoP URL mismatch.\" };\n    }\n    if (input.expectedAccessToken) {\n      const expectedAth = computeDpopAccessTokenHash(input.expectedAccessToken);\n      if (payload.value.ath !== expectedAth) {\n        return { ok: false, reason: \"DPoP access token hash mismatch.\" };\n      }\n    }\n\n    const maxAgeSeconds = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;\n    if (\n      payload.value.iat > input.nowEpochSeconds + 5 ||\n      input.nowEpochSeconds - payload.value.iat > maxAgeSeconds\n    ) {\n      return { ok: false, reason: \"DPoP proof is outside the allowed time window.\" };\n    }\n\n    const signature = base64UrlToBytes(parts[2]);\n    const signatureInputHash = sha256(new TextEncoder().encode(`${parts[0]}.${parts[1]}`));\n    const verified = p256.verify(\n      signature,\n      signatureInputHash,\n      publicKeyBytesFromJwk(header.value.jwk),\n      {\n        prehash: false,\n        format: \"compact\",\n      },\n    );\n    return verified\n      ? {\n          ok: true,\n          thumbprint,\n          jti: payload.value.jti,\n          iat: payload.value.iat,\n        }\n      : { ok: false, reason: \"Invalid DPoP signature.\" };\n  } catch {\n    return { ok: false, reason: \"Invalid DPoP proof.\" };\n  }\n}\n","import { verifyDpopProof } from \"@t3tools/shared/dpop\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as Option from \"effect/Option\";\nimport * as HttpServerRequest from \"effect/unstable/http/HttpServerRequest\";\n\nimport {\n  ServerAuthDpopReplayKeyCalculationError,\n  ServerAuthDpopReplayStateRecordError,\n  ServerAuthInvalidCredentialError,\n  type ServerAuthInternalError,\n} from \"./EnvironmentAuth.ts\";\nimport * as ServerSecretStore from \"./ServerSecretStore.ts\";\n\nexport const mapDpopReplayStoreError = (\n  error: ServerSecretStore.SecretStoreError,\n): ServerAuthInvalidCredentialError | ServerAuthInternalError =>\n  ServerSecretStore.isSecretAlreadyExistsError(error)\n    ? new ServerAuthInvalidCredentialError({\n        diagnostic: \"DPoP proof replayed.\",\n        cause: error,\n      })\n    : new ServerAuthDpopReplayStateRecordError({\n        cause: error,\n      });\n\nexport const verifyRequestDpopProof = (input: {\n  readonly request: HttpServerRequest.HttpServerRequest;\n  readonly expectedThumbprint?: string;\n  readonly expectedAccessToken?: string;\n}) =>\n  Effect.gen(function* () {\n    const proof = input.request.headers.dpop;\n    const url = HttpServerRequest.toURL(input.request);\n    if (Option.isNone(url)) {\n      return yield* new ServerAuthInvalidCredentialError({\n        diagnostic: \"Invalid DPoP request URL.\",\n      });\n    }\n    const now = yield* DateTime.now;\n    const result = verifyDpopProof({\n      proof,\n      method: input.request.method,\n      url: url.value.href,\n      nowEpochSeconds: Math.floor(now.epochMilliseconds / 1_000),\n      ...(input.expectedThumbprint ? { expectedThumbprint: input.expectedThumbprint } : {}),\n      ...(input.expectedAccessToken ? { expectedAccessToken: input.expectedAccessToken } : {}),\n    });\n    if (!result.ok) {\n      return yield* new ServerAuthInvalidCredentialError({\n        diagnostic: result.reason,\n      });\n    }\n    const secretStore = yield* ServerSecretStore.ServerSecretStore;\n    const replayKey = yield* Crypto.Crypto.pipe(\n      Effect.flatMap((crypto) =>\n        crypto.digest(\"SHA-256\", new TextEncoder().encode(`${result.thumbprint}:${result.jti}`)),\n      ),\n      Effect.map(Encoding.encodeBase64Url),\n      Effect.mapError(\n        (cause) =>\n          new ServerAuthDpopReplayKeyCalculationError({\n            cause,\n          }),\n      ),\n    );\n    yield* secretStore\n      .create(\n        `dpop-proof-${replayKey}`,\n        new TextEncoder().encode(\n          [\n            `thumbprint=${result.thumbprint}`,\n            `jti=${result.jti}`,\n            `iat=${result.iat}`,\n            `consumedAt=${DateTime.formatIso(now)}`,\n          ].join(\"\\n\"),\n        ),\n      )\n      .pipe(\n        Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>\n          Effect.fail(mapDpopReplayStoreError(error)),\n        ),\n      );\n    return result.thumbprint;\n  });\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS orchestration_events (\n      sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n      event_id TEXT NOT NULL UNIQUE,\n      aggregate_kind TEXT NOT NULL,\n      stream_id TEXT NOT NULL,\n      stream_version INTEGER NOT NULL,\n      event_type TEXT NOT NULL,\n      occurred_at TEXT NOT NULL,\n      command_id TEXT,\n      causation_event_id TEXT,\n      correlation_id TEXT,\n      actor_kind TEXT NOT NULL,\n      payload_json TEXT NOT NULL,\n      metadata_json TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE UNIQUE INDEX IF NOT EXISTS idx_orch_events_stream_version\n    ON orchestration_events(aggregate_kind, stream_id, stream_version)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_events_stream_sequence\n    ON orchestration_events(aggregate_kind, stream_id, sequence)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_events_command_id\n    ON orchestration_events(command_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_events_correlation_id\n    ON orchestration_events(correlation_id)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS orchestration_command_receipts (\n      command_id TEXT PRIMARY KEY,\n      aggregate_kind TEXT NOT NULL,\n      aggregate_id TEXT NOT NULL,\n      accepted_at TEXT NOT NULL,\n      result_sequence INTEGER NOT NULL,\n      status TEXT NOT NULL,\n      error TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_command_receipts_aggregate\n    ON orchestration_command_receipts(aggregate_kind, aggregate_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_orch_command_receipts_sequence\n    ON orchestration_command_receipts(result_sequence)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS checkpoint_diff_blobs (\n      thread_id TEXT NOT NULL,\n      from_turn_count INTEGER NOT NULL,\n      to_turn_count INTEGER NOT NULL,\n      diff TEXT NOT NULL,\n      created_at TEXT NOT NULL,\n      UNIQUE (thread_id, from_turn_count, to_turn_count)\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_checkpoint_diff_blobs_thread_to_turn\n    ON checkpoint_diff_blobs(thread_id, to_turn_count)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS provider_session_runtime (\n      thread_id TEXT PRIMARY KEY,\n      provider_name TEXT NOT NULL,\n      adapter_key TEXT NOT NULL,\n      runtime_mode TEXT NOT NULL DEFAULT 'full-access',\n      status TEXT NOT NULL,\n      last_seen_at TEXT NOT NULL,\n      resume_cursor_json TEXT,\n      runtime_payload_json TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_status\n    ON provider_session_runtime(status)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_provider\n    ON provider_session_runtime(provider_name)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_projects (\n      project_id TEXT PRIMARY KEY,\n      title TEXT NOT NULL,\n      workspace_root TEXT NOT NULL,\n      default_model TEXT,\n      scripts_json TEXT NOT NULL,\n      created_at TEXT NOT NULL,\n      updated_at TEXT NOT NULL,\n      deleted_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_threads (\n      thread_id TEXT PRIMARY KEY,\n      project_id TEXT NOT NULL,\n      title TEXT NOT NULL,\n      model TEXT NOT NULL,\n      branch TEXT,\n      worktree_path TEXT,\n      latest_turn_id TEXT,\n      created_at TEXT NOT NULL,\n      updated_at TEXT NOT NULL,\n      deleted_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_thread_messages (\n      message_id TEXT PRIMARY KEY,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      role TEXT NOT NULL,\n      text TEXT NOT NULL,\n      is_streaming INTEGER NOT NULL,\n      created_at TEXT NOT NULL,\n      updated_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_thread_activities (\n      activity_id TEXT PRIMARY KEY,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      tone TEXT NOT NULL,\n      kind TEXT NOT NULL,\n      summary TEXT NOT NULL,\n      payload_json TEXT NOT NULL,\n      created_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_thread_sessions (\n      thread_id TEXT PRIMARY KEY,\n      status TEXT NOT NULL,\n      provider_name TEXT,\n      provider_session_id TEXT,\n      provider_thread_id TEXT,\n      active_turn_id TEXT,\n      last_error TEXT,\n      updated_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_turns (\n      row_id INTEGER PRIMARY KEY AUTOINCREMENT,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      pending_message_id TEXT,\n      assistant_message_id TEXT,\n      state TEXT NOT NULL,\n      requested_at TEXT NOT NULL,\n      started_at TEXT,\n      completed_at TEXT,\n      checkpoint_turn_count INTEGER,\n      checkpoint_ref TEXT,\n      checkpoint_status TEXT,\n      checkpoint_files_json TEXT NOT NULL,\n      UNIQUE (thread_id, turn_id),\n      UNIQUE (thread_id, checkpoint_turn_count)\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_pending_approvals (\n      request_id TEXT PRIMARY KEY,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      status TEXT NOT NULL,\n      decision TEXT,\n      created_at TEXT NOT NULL,\n      resolved_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_state (\n      projector TEXT PRIMARY KEY,\n      last_applied_sequence INTEGER NOT NULL,\n      updated_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_projects_updated_at\n    ON projection_projects(updated_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_project_id\n    ON projection_threads(project_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created\n    ON projection_thread_messages(thread_id, created_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_created\n    ON projection_thread_activities(thread_id, created_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_provider_session\n    ON projection_thread_sessions(provider_session_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_turns_thread_requested\n    ON projection_turns(thread_id, requested_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_turns_thread_checkpoint_completed\n    ON projection_turns(thread_id, checkpoint_turn_count, completed_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_pending_approvals_thread_status\n    ON projection_pending_approvals(thread_id, status)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nconst DEFAULT_RUNTIME_MODE = \"full-access\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n      ALTER TABLE projection_thread_sessions\n      ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'\n    `;\n\n  yield* sql`\n    UPDATE projection_thread_sessions\n    SET runtime_mode = ${DEFAULT_RUNTIME_MODE}\n    WHERE runtime_mode IS NULL\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_thread_messages\n    ADD COLUMN attachments_json TEXT\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_thread_activities\n    ADD COLUMN sequence INTEGER\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence\n    ON projection_thread_activities(thread_id, sequence)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.asVoid(SqlClient.SqlClient);\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'\n  `;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET runtime_mode = 'full-access'\n    WHERE runtime_mode IS NULL\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_set(payload_json, '$.runtimeMode', 'full-access')\n    WHERE event_type = 'thread.created'\n      AND json_type(payload_json, '$.runtimeMode') IS NULL\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN interaction_mode TEXT NOT NULL DEFAULT 'default'\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS projection_thread_proposed_plans (\n      plan_id TEXT PRIMARY KEY,\n      thread_id TEXT NOT NULL,\n      turn_id TEXT,\n      plan_markdown TEXT NOT NULL,\n      created_at TEXT NOT NULL,\n      updated_at TEXT NOT NULL\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_proposed_plans_thread_created\n    ON projection_thread_proposed_plans(thread_id, created_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_thread_proposed_plans\n    ADD COLUMN implemented_at TEXT\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_thread_proposed_plans\n    ADD COLUMN implementation_thread_id TEXT\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_turns\n    ADD COLUMN source_proposed_plan_thread_id TEXT\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_turns\n    ADD COLUMN source_proposed_plan_id TEXT\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_projects\n    ADD COLUMN default_model_selection_json TEXT\n  `;\n\n  yield* sql`\n    UPDATE projection_projects\n    SET default_model_selection_json = CASE\n      WHEN default_model IS NULL THEN NULL\n      ELSE json_object(\n        'provider',\n        CASE\n          WHEN lower(default_model) LIKE '%claude%' THEN 'claudeAgent'\n          ELSE 'codex'\n        END,\n        'model',\n        default_model\n      )\n    END\n    WHERE default_model_selection_json IS NULL\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN model_selection_json TEXT\n  `;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET model_selection_json = json_object(\n      'provider',\n      COALESCE(\n        (\n          SELECT provider_name\n          FROM projection_thread_sessions\n          WHERE projection_thread_sessions.thread_id = projection_threads.thread_id\n        ),\n        CASE\n          WHEN lower(model) LIKE '%claude%' THEN 'claudeAgent'\n          ELSE 'codex'\n        END,\n        'codex'\n      ),\n      'model',\n      model\n    )\n    WHERE model_selection_json IS NULL\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_projects\n    DROP COLUMN default_model\n  `;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    DROP COLUMN model\n  `;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = CASE\n      WHEN json_type(payload_json, '$.defaultModel') = 'null' THEN json_remove(\n        json_set(payload_json, '$.defaultModelSelection', json('null')),\n        '$.defaultProvider',\n        '$.defaultModel',\n        '$.defaultModelOptions'\n      )\n      ELSE json_remove(\n        json_set(\n          payload_json,\n          '$.defaultModelSelection',\n          json_patch(\n            json_object(\n              'provider',\n              CASE\n                WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL\n                THEN json_extract(payload_json, '$.defaultProvider')\n                WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'\n                THEN 'claudeAgent'\n                ELSE 'codex'\n              END,\n              'model',\n              json_extract(payload_json, '$.defaultModel')\n            ),\n              CASE\n                WHEN json_type(payload_json, '$.defaultModelOptions') IS NULL THEN '{}'\n                WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL\n                  OR json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL\n                THEN CASE\n                  WHEN (\n                  CASE\n                    WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL\n                    THEN json_extract(payload_json, '$.defaultProvider')\n                    WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'\n                    THEN 'claudeAgent'\n                    ELSE 'codex'\n                    END\n                  ) = 'claudeAgent'\n                  THEN CASE\n                    WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL\n                    THEN json_object(\n                      'options',\n                      json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))\n                    )\n                    WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL\n                    THEN json_object(\n                      'options',\n                      json(json_extract(payload_json, '$.defaultModelOptions.codex'))\n                    )\n                    ELSE '{}'\n                  END\n                  ELSE CASE\n                    WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL\n                    THEN json_object(\n                      'options',\n                      json(json_extract(payload_json, '$.defaultModelOptions.codex'))\n                    )\n                    WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL\n                    THEN json_object(\n                      'options',\n                      json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))\n                    )\n                    ELSE '{}'\n                  END\n                END\n              ELSE json_object(\n                'options',\n                json(json_extract(payload_json, '$.defaultModelOptions'))\n              )\n            END\n          )\n        ),\n        '$.defaultProvider',\n        '$.defaultModel',\n        '$.defaultModelOptions'\n      )\n    END\n    WHERE event_type IN ('project.created', 'project.meta-updated')\n      AND json_type(payload_json, '$.defaultModelSelection') IS NULL\n      AND json_type(payload_json, '$.defaultModel') IS NOT NULL\n  `;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_remove(\n      json_set(\n        payload_json,\n        '$.modelSelection',\n        json_patch(\n          json_object(\n            'provider',\n            CASE\n              WHEN json_extract(payload_json, '$.provider') IS NOT NULL\n              THEN json_extract(payload_json, '$.provider')\n              WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'\n              THEN 'claudeAgent'\n              ELSE 'codex'\n            END,\n            'model',\n            json_extract(payload_json, '$.model')\n          ),\n          CASE\n            WHEN json_type(payload_json, '$.modelOptions') IS NULL THEN '{}'\n            WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL\n              OR json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL\n            THEN CASE\n              WHEN (\n                CASE\n                  WHEN json_extract(payload_json, '$.provider') IS NOT NULL\n                  THEN json_extract(payload_json, '$.provider')\n                  WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'\n                  THEN 'claudeAgent'\n                  ELSE 'codex'\n                  END\n              ) = 'claudeAgent'\n              THEN CASE\n                WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL\n                THEN json_object(\n                  'options',\n                  json(json_extract(payload_json, '$.modelOptions.claudeAgent'))\n                )\n                WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL\n                THEN json_object(\n                  'options',\n                  json(json_extract(payload_json, '$.modelOptions.codex'))\n                )\n                ELSE '{}'\n              END\n              ELSE CASE\n                WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL\n                THEN json_object(\n                  'options',\n                  json(json_extract(payload_json, '$.modelOptions.codex'))\n                )\n                WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL\n                THEN json_object(\n                  'options',\n                  json(json_extract(payload_json, '$.modelOptions.claudeAgent'))\n                )\n                ELSE '{}'\n              END\n            END\n            ELSE json_object('options', json(json_extract(payload_json, '$.modelOptions')))\n          END\n        )\n      ),\n      '$.provider',\n      '$.model',\n      '$.modelOptions'\n    )\n    WHERE event_type IN ('thread.created', 'thread.meta-updated', 'thread.turn-start-requested')\n      AND json_type(payload_json, '$.modelSelection') IS NULL\n      AND json_type(payload_json, '$.model') IS NOT NULL\n  `;\n\n  // Backfill thread.created events that predate the model field entirely\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_set(\n      payload_json,\n      '$.modelSelection',\n      json(json_object('provider', 'codex', 'model', 'gpt-5.4'))\n    )\n    WHERE event_type = 'thread.created'\n      AND json_type(payload_json, '$.modelSelection') IS NULL\n      AND json_type(payload_json, '$.model') IS NULL\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (columns.some((column) => column.name === \"archived_at\")) {\n    return;\n  }\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN archived_at TEXT\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_project_archived_at\n    ON projection_threads(project_id, archived_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_projects_workspace_root_deleted_at\n    ON projection_projects(workspace_root, deleted_at)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_project_deleted_created\n    ON projection_threads(project_id, deleted_at, created_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS auth_pairing_links (\n      id TEXT PRIMARY KEY,\n      credential TEXT NOT NULL UNIQUE,\n      method TEXT NOT NULL,\n      role TEXT NOT NULL,\n      subject TEXT NOT NULL,\n      created_at TEXT NOT NULL,\n      expires_at TEXT NOT NULL,\n      consumed_at TEXT,\n      revoked_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_auth_pairing_links_active\n    ON auth_pairing_links(revoked_at, consumed_at, expires_at)\n  `;\n\n  yield* sql`\n    CREATE TABLE IF NOT EXISTS auth_sessions (\n      session_id TEXT PRIMARY KEY,\n      subject TEXT NOT NULL,\n      role TEXT NOT NULL,\n      method TEXT NOT NULL,\n      issued_at TEXT NOT NULL,\n      expires_at TEXT NOT NULL,\n      revoked_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_auth_sessions_active\n    ON auth_sessions(revoked_at, expires_at, issued_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const pairingLinkColumns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(auth_pairing_links)\n  `;\n  if (!pairingLinkColumns.some((column) => column.name === \"label\")) {\n    yield* sql`\n      ALTER TABLE auth_pairing_links\n      ADD COLUMN label TEXT\n    `;\n  }\n\n  const sessionColumns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(auth_sessions)\n  `;\n\n  if (!sessionColumns.some((column) => column.name === \"client_label\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_label TEXT\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_ip_address\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_ip_address TEXT\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_user_agent\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_user_agent TEXT\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_device_type\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_device_type TEXT NOT NULL DEFAULT 'unknown'\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_os\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_os TEXT\n    `;\n  }\n\n  if (!sessionColumns.some((column) => column.name === \"client_browser\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN client_browser TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const sessionColumns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(auth_sessions)\n  `;\n\n  if (!sessionColumns.some((column) => column.name === \"last_connected_at\")) {\n    yield* sql`\n      ALTER TABLE auth_sessions\n      ADD COLUMN last_connected_at TEXT\n    `;\n  }\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN latest_user_message_at TEXT\n  `.pipe(Effect.catch(() => Effect.void));\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN pending_approval_count INTEGER NOT NULL DEFAULT 0\n  `.pipe(Effect.catch(() => Effect.void));\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN pending_user_input_count INTEGER NOT NULL DEFAULT 0\n  `.pipe(Effect.catch(() => Effect.void));\n\n  yield* sql`\n    ALTER TABLE projection_threads\n    ADD COLUMN has_actionable_proposed_plan INTEGER NOT NULL DEFAULT 0\n  `.pipe(Effect.catch(() => Effect.void));\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    INSERT OR IGNORE INTO projection_pending_approvals (\n      request_id,\n      thread_id,\n      turn_id,\n      status,\n      decision,\n      created_at,\n      resolved_at\n    )\n    SELECT\n      requested.request_id,\n      requested.thread_id,\n      requested.turn_id,\n      'pending',\n      NULL,\n      requested.created_at,\n      NULL\n    FROM (\n      SELECT\n        json_extract(payload_json, '$.requestId') AS request_id,\n        thread_id,\n        turn_id,\n        created_at,\n        ROW_NUMBER() OVER (\n          PARTITION BY json_extract(payload_json, '$.requestId')\n          ORDER BY created_at ASC, activity_id ASC\n        ) AS row_number\n      FROM projection_thread_activities\n      WHERE kind = 'approval.requested'\n        AND json_extract(payload_json, '$.requestId') IS NOT NULL\n    ) AS requested\n    WHERE requested.row_number = 1\n  `;\n\n  yield* sql`\n    WITH latest_resolutions AS (\n      SELECT\n        resolved.request_id,\n        resolved.resolved_at,\n        resolved.decision\n      FROM (\n        SELECT\n          json_extract(payload_json, '$.requestId') AS request_id,\n          created_at AS resolved_at,\n          CASE\n            WHEN json_extract(payload_json, '$.decision') IN (\n              'accept',\n              'acceptForSession',\n              'decline',\n              'cancel'\n            )\n            THEN json_extract(payload_json, '$.decision')\n            ELSE NULL\n          END AS decision,\n          ROW_NUMBER() OVER (\n            PARTITION BY json_extract(payload_json, '$.requestId')\n            ORDER BY created_at DESC, activity_id DESC\n          ) AS row_number\n        FROM projection_thread_activities\n        WHERE kind = 'approval.resolved'\n          AND json_extract(payload_json, '$.requestId') IS NOT NULL\n      ) AS resolved\n      WHERE resolved.row_number = 1\n    )\n    UPDATE projection_pending_approvals\n    SET\n      status = 'resolved',\n      decision = (\n        SELECT latest_resolutions.decision\n        FROM latest_resolutions\n        WHERE latest_resolutions.request_id = projection_pending_approvals.request_id\n      ),\n      resolved_at = (\n        SELECT latest_resolutions.resolved_at\n        FROM latest_resolutions\n        WHERE latest_resolutions.request_id = projection_pending_approvals.request_id\n      )\n    WHERE EXISTS (\n      SELECT 1\n      FROM latest_resolutions\n      WHERE latest_resolutions.request_id = projection_pending_approvals.request_id\n    )\n  `;\n\n  yield* sql`\n    WITH latest_response_events AS (\n      SELECT\n        response.request_id,\n        response.resolved_at,\n        response.decision\n      FROM (\n        SELECT\n          json_extract(payload_json, '$.requestId') AS request_id,\n          occurred_at AS resolved_at,\n          CASE\n            WHEN json_extract(payload_json, '$.decision') IN (\n              'accept',\n              'acceptForSession',\n              'decline',\n              'cancel'\n            )\n            THEN json_extract(payload_json, '$.decision')\n            ELSE NULL\n          END AS decision,\n          ROW_NUMBER() OVER (\n            PARTITION BY json_extract(payload_json, '$.requestId')\n            ORDER BY occurred_at DESC, sequence DESC\n          ) AS row_number\n        FROM orchestration_events\n        WHERE event_type = 'thread.approval-response-requested'\n          AND json_extract(payload_json, '$.requestId') IS NOT NULL\n      ) AS response\n      WHERE response.row_number = 1\n    )\n    UPDATE projection_pending_approvals\n    SET\n      status = 'resolved',\n      decision = (\n        SELECT latest_response_events.decision\n        FROM latest_response_events\n        WHERE latest_response_events.request_id = projection_pending_approvals.request_id\n      ),\n      resolved_at = (\n        SELECT latest_response_events.resolved_at\n        FROM latest_response_events\n        WHERE latest_response_events.request_id = projection_pending_approvals.request_id\n      )\n    WHERE EXISTS (\n      SELECT 1\n      FROM latest_response_events\n      WHERE latest_response_events.request_id = projection_pending_approvals.request_id\n    )\n  `;\n\n  yield* sql`\n    WITH latest_stale_failures AS (\n      SELECT\n        failure.request_id,\n        failure.resolved_at\n      FROM (\n        SELECT\n          json_extract(payload_json, '$.requestId') AS request_id,\n          created_at AS resolved_at,\n          ROW_NUMBER() OVER (\n            PARTITION BY json_extract(payload_json, '$.requestId')\n            ORDER BY created_at DESC, activity_id DESC\n          ) AS row_number\n        FROM projection_thread_activities\n        WHERE kind = 'provider.approval.respond.failed'\n          AND json_extract(payload_json, '$.requestId') IS NOT NULL\n          AND (\n            lower(COALESCE(json_extract(payload_json, '$.detail'), ''))\n              LIKE '%stale pending approval request%'\n            OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))\n              LIKE '%unknown pending approval request%'\n            OR lower(COALESCE(json_extract(payload_json, '$.detail'), ''))\n              LIKE '%unknown pending permission request%'\n          )\n      ) AS failure\n      WHERE failure.row_number = 1\n    )\n    UPDATE projection_pending_approvals\n    SET\n      status = 'resolved',\n      decision = NULL,\n      resolved_at = (\n        SELECT latest_stale_failures.resolved_at\n        FROM latest_stale_failures\n        WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id\n      )\n    WHERE status = 'pending'\n      AND EXISTS (\n        SELECT 1\n        FROM latest_stale_failures\n        WHERE latest_stale_failures.request_id = projection_pending_approvals.request_id\n      )\n  `;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET\n      latest_user_message_at = (\n        SELECT MAX(message.created_at)\n        FROM projection_thread_messages AS message\n        WHERE message.thread_id = projection_threads.thread_id\n          AND message.role = 'user'\n      ),\n      pending_approval_count = COALESCE((\n        SELECT COUNT(*)\n        FROM projection_pending_approvals\n        WHERE projection_pending_approvals.thread_id = projection_threads.thread_id\n          AND projection_pending_approvals.status = 'pending'\n      ), 0),\n      pending_user_input_count = COALESCE((\n        WITH latest_user_input_states AS (\n          SELECT\n            latest.request_id,\n            latest.kind,\n            latest.detail\n          FROM (\n            SELECT\n              json_extract(activity.payload_json, '$.requestId') AS request_id,\n              activity.kind,\n              lower(COALESCE(json_extract(activity.payload_json, '$.detail'), '')) AS detail,\n              ROW_NUMBER() OVER (\n                PARTITION BY json_extract(activity.payload_json, '$.requestId')\n                ORDER BY activity.created_at DESC, activity.activity_id DESC\n              ) AS row_number\n            FROM projection_thread_activities AS activity\n            WHERE activity.thread_id = projection_threads.thread_id\n              AND json_extract(activity.payload_json, '$.requestId') IS NOT NULL\n              AND activity.kind IN (\n                'user-input.requested',\n                'user-input.resolved',\n                'provider.user-input.respond.failed'\n              )\n          ) AS latest\n          WHERE latest.row_number = 1\n        )\n        SELECT COUNT(*)\n        FROM latest_user_input_states\n        WHERE latest_user_input_states.kind = 'user-input.requested'\n          OR (\n            latest_user_input_states.kind = 'provider.user-input.respond.failed'\n            AND latest_user_input_states.detail NOT LIKE '%stale pending user-input request%'\n            AND latest_user_input_states.detail NOT LIKE '%unknown pending user-input request%'\n          )\n      ), 0),\n      has_actionable_proposed_plan = COALESCE((\n        SELECT CASE\n          WHEN projection_threads.latest_turn_id IS NOT NULL\n            AND EXISTS (\n              SELECT 1\n              FROM projection_thread_proposed_plans AS latest_turn_plan_exists\n              WHERE latest_turn_plan_exists.thread_id = projection_threads.thread_id\n                AND latest_turn_plan_exists.turn_id = projection_threads.latest_turn_id\n            )\n            THEN CASE\n              WHEN (\n                SELECT latest_turn_plan.implemented_at\n                FROM projection_thread_proposed_plans AS latest_turn_plan\n                WHERE latest_turn_plan.thread_id = projection_threads.thread_id\n                  AND latest_turn_plan.turn_id = projection_threads.latest_turn_id\n                ORDER BY latest_turn_plan.updated_at DESC, latest_turn_plan.plan_id DESC\n                LIMIT 1\n              ) IS NULL\n                THEN 1\n                ELSE 0\n              END\n          WHEN EXISTS (\n            SELECT 1\n            FROM projection_thread_proposed_plans AS any_plan\n            WHERE any_plan.thread_id = projection_threads.thread_id\n          )\n            THEN CASE\n              WHEN (\n                SELECT latest_plan.implemented_at\n                FROM projection_thread_proposed_plans AS latest_plan\n                WHERE latest_plan.thread_id = projection_threads.thread_id\n                ORDER BY latest_plan.updated_at DESC, latest_plan.plan_id DESC\n                LIMIT 1\n              ) IS NULL\n                THEN 1\n                ELSE 0\n              END\n          ELSE 0\n        END\n      ), 0)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    DELETE FROM projection_pending_approvals\n    WHERE NOT EXISTS (\n      SELECT 1\n      FROM projection_thread_activities AS activity\n      WHERE activity.kind = 'approval.requested'\n        AND json_extract(activity.payload_json, '$.requestId')\n          = projection_pending_approvals.request_id\n    )\n  `;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET pending_approval_count = COALESCE((\n      SELECT COUNT(*)\n      FROM projection_pending_approvals\n      WHERE projection_pending_approvals.thread_id = projection_threads.thread_id\n        AND projection_pending_approvals.status = 'pending'\n    ), 0)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\n/**\n * Canonicalize `modelSelection.options` / `defaultModelSelection.options` from\n * the legacy object shape (`{ effort: \"max\", fastMode: true, ... }`) to the\n * current array-of-selections shape (`[{ id: \"effort\", value: \"max\" }, ...]`).\n *\n * Migration 016 introduced `modelSelection` with `options` stored as a\n * per-provider object. Later the schema was reshaped so that options are a\n * generic `Array<{ id, value }>` of user-selected option entries. Stored rows\n * from before the reshape still have the object shape and fail to decode.\n *\n * For each value in the legacy object:\n *   - string values are kept if non-empty after trim\n *   - boolean values are always kept (true | false)\n *   - any other value type (number, null, nested object/array) is dropped,\n *     matching the permissive client-side normalizer in composerDraftStore.\n *\n * Touched storage:\n *   - `projection_threads.model_selection_json.options`\n *   - `projection_projects.default_model_selection_json.options`\n *   - `orchestration_events.payload_json.$.modelSelection.options`\n *     (thread.created | thread.meta-updated | thread.turn-start-requested)\n *   - `orchestration_events.payload_json.$.defaultModelSelection.options`\n *     (project.created | project.meta-updated)\n */\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    UPDATE projection_threads\n    SET model_selection_json = json_set(\n      model_selection_json,\n      '$.options',\n      (\n        SELECT json_group_array(\n          json_object(\n            'id', key,\n            'value',\n            CASE type\n              WHEN 'true' THEN json('true')\n              WHEN 'false' THEN json('false')\n              ELSE atom\n            END\n          )\n        )\n        FROM json_each(json_extract(model_selection_json, '$.options'))\n        WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')\n           OR type IN ('true', 'false')\n      )\n    )\n    WHERE model_selection_json IS NOT NULL\n      AND json_type(model_selection_json, '$.options') = 'object'\n  `;\n\n  yield* sql`\n    UPDATE projection_projects\n    SET default_model_selection_json = json_set(\n      default_model_selection_json,\n      '$.options',\n      (\n        SELECT json_group_array(\n          json_object(\n            'id', key,\n            'value',\n            CASE type\n              WHEN 'true' THEN json('true')\n              WHEN 'false' THEN json('false')\n              ELSE atom\n            END\n          )\n        )\n        FROM json_each(json_extract(default_model_selection_json, '$.options'))\n        WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')\n           OR type IN ('true', 'false')\n      )\n    )\n    WHERE default_model_selection_json IS NOT NULL\n      AND json_type(default_model_selection_json, '$.options') = 'object'\n  `;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_set(\n      payload_json,\n      '$.modelSelection.options',\n      (\n        SELECT json_group_array(\n          json_object(\n            'id', key,\n            'value',\n            CASE type\n              WHEN 'true' THEN json('true')\n              WHEN 'false' THEN json('false')\n              ELSE atom\n            END\n          )\n        )\n        FROM json_each(json_extract(payload_json, '$.modelSelection.options'))\n        WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')\n           OR type IN ('true', 'false')\n      )\n    )\n    WHERE event_type IN (\n      'thread.created',\n      'thread.meta-updated',\n      'thread.turn-start-requested'\n    )\n      AND json_type(payload_json, '$.modelSelection.options') = 'object'\n  `;\n\n  yield* sql`\n    UPDATE orchestration_events\n    SET payload_json = json_set(\n      payload_json,\n      '$.defaultModelSelection.options',\n      (\n        SELECT json_group_array(\n          json_object(\n            'id', key,\n            'value',\n            CASE type\n              WHEN 'true' THEN json('true')\n              WHEN 'false' THEN json('false')\n              ELSE atom\n            END\n          )\n        )\n        FROM json_each(json_extract(payload_json, '$.defaultModelSelection.options'))\n        WHERE (type = 'text' AND trim(coalesce(atom, '')) != '')\n           OR type IN ('true', 'false')\n      )\n    )\n    WHERE event_type IN ('project.created', 'project.meta-updated')\n      AND json_type(payload_json, '$.defaultModelSelection.options') = 'object'\n  `;\n});\n","/**\n * Adds the nullable `provider_instance_id` routing column to\n * `provider_session_runtime`.\n *\n * Slice D of the provider-array refactor splits \"driver kind\" from\n * \"configured instance\". Existing rows have only the driver name in\n * `provider_name`; new rows additionally carry the user-defined instance\n * routing key. The column remains nullable so legacy rows can still decode;\n * the persistence boundary is responsible for materializing a concrete\n * instance id before any hot routing path sees the binding.\n *\n * The column is nullable on purpose — backfilling it during the migration\n * would require knowing which configured instance \"owned\" each historical\n * session, and that mapping is ambiguous when the user later configures\n * multiple instances of the same driver. Keeping that compatibility at the\n * persistence boundary keeps the fallback out of active routing code.\n */\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(provider_session_runtime)\n  `;\n  if (!columns.some((column) => column.name === \"provider_instance_id\")) {\n    yield* sql`\n      ALTER TABLE provider_session_runtime\n      ADD COLUMN provider_instance_id TEXT\n    `;\n  }\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_instance\n    ON provider_session_runtime(provider_instance_id)\n  `;\n});\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as Effect from \"effect/Effect\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_thread_sessions)\n  `;\n  if (!columns.some((column) => column.name === \"provider_instance_id\")) {\n    yield* sql`\n      ALTER TABLE projection_thread_sessions\n      ADD COLUMN provider_instance_id TEXT\n    `;\n  }\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_sessions_instance\n    ON projection_thread_sessions(provider_instance_id)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence_created_id\n    ON projection_thread_activities(thread_id, sequence, created_at, activity_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_thread_messages_thread_created_id\n    ON projection_thread_messages(thread_id, created_at, message_id)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_active\n    ON projection_threads(deleted_at, archived_at, project_id, created_at, thread_id)\n  `;\n\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_archived\n    ON projection_threads(deleted_at, archived_at, project_id, thread_id)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\n/**\n * This is an intentional alpha cutover: role-bearing credentials and sessions\n * cannot safely be assigned new capabilities implicitly.\n */\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  yield* sql`DROP TABLE IF EXISTS auth_pairing_links`;\n  yield* sql`DROP TABLE IF EXISTS auth_sessions`;\n\n  yield* sql`\n    CREATE TABLE auth_pairing_links (\n      id TEXT PRIMARY KEY,\n      credential TEXT NOT NULL UNIQUE,\n      method TEXT NOT NULL,\n      scopes TEXT NOT NULL,\n      subject TEXT NOT NULL,\n      label TEXT,\n      created_at TEXT NOT NULL,\n      expires_at TEXT NOT NULL,\n      consumed_at TEXT,\n      revoked_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX idx_auth_pairing_links_active\n    ON auth_pairing_links(revoked_at, consumed_at, expires_at)\n  `;\n\n  yield* sql`\n    CREATE TABLE auth_sessions (\n      session_id TEXT PRIMARY KEY,\n      subject TEXT NOT NULL,\n      scopes TEXT NOT NULL,\n      method TEXT NOT NULL,\n      client_label TEXT,\n      client_ip_address TEXT,\n      client_user_agent TEXT,\n      client_device_type TEXT NOT NULL DEFAULT 'unknown',\n      client_os TEXT,\n      client_browser TEXT,\n      issued_at TEXT NOT NULL,\n      expires_at TEXT NOT NULL,\n      last_connected_at TEXT,\n      revoked_at TEXT\n    )\n  `;\n\n  yield* sql`\n    CREATE INDEX idx_auth_sessions_active\n    ON auth_sessions(revoked_at, expires_at, issued_at)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const pairingLinkColumns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(auth_pairing_links)\n  `;\n  if (!pairingLinkColumns.some((column) => column.name === \"proof_key_thumbprint\")) {\n    yield* sql`\n      ALTER TABLE auth_pairing_links\n      ADD COLUMN proof_key_thumbprint TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (!columns.some((column) => column.name === \"settled_override\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN settled_override TEXT\n    `;\n  }\n\n  if (!columns.some((column) => column.name === \"settled_at\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN settled_at TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (!columns.some((column) => column.name === \"snoozed_until\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN snoozed_until TEXT\n    `;\n  }\n\n  if (!columns.some((column) => column.name === \"snoozed_at\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN snoozed_at TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (!columns.some((column) => column.name === \"title_regeneration_request_id\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN title_regeneration_request_id TEXT\n    `;\n  }\n\n  if (!columns.some((column) => column.name === \"title_regeneration_started_at\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN title_regeneration_started_at TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (!columns.some((column) => column.name === \"pinned_at\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN pinned_at TEXT\n    `;\n  }\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\n/**\n * Composite index for windowed thread detail reads. Pagination orders turns by\n * the stable keyset (requested_at, turn_id); the pre-existing\n * (thread_id, requested_at) index cannot serve the tiebreak order, forcing a\n * temp B-tree over all of a thread's turns before the page LIMIT applies.\n * With this index the candidates scan is genuinely bounded by the page size.\n */\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  yield* sql`\n    CREATE INDEX IF NOT EXISTS idx_projection_turns_thread_keyset\n    ON projection_turns(thread_id, requested_at, turn_id)\n  `;\n});\n","import * as Effect from \"effect/Effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nexport default Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const columns = yield* sql<{ readonly name: string }>`\n    PRAGMA table_info(projection_threads)\n  `;\n\n  if (!columns.some((column) => column.name === \"pin_order_key\")) {\n    yield* sql`\n      ALTER TABLE projection_threads\n      ADD COLUMN pin_order_key TEXT\n    `;\n  }\n});\n","/**\n * MigrationsLive - Migration runner with inline loader\n *\n * Uses Migrator.make with fromRecord to define migrations inline.\n * All migrations are statically imported - no dynamic file system loading.\n *\n * Migrations run automatically when the MigrationLayer is provided,\n * ensuring the database schema is always up-to-date before the application starts.\n */\n\nimport * as Migrator from \"effect/unstable/sql/Migrator\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\n// Import all migrations statically\nimport Migration0001 from \"./Migrations/001_OrchestrationEvents.ts\";\nimport Migration0002 from \"./Migrations/002_OrchestrationCommandReceipts.ts\";\nimport Migration0003 from \"./Migrations/003_CheckpointDiffBlobs.ts\";\nimport Migration0004 from \"./Migrations/004_ProviderSessionRuntime.ts\";\nimport Migration0005 from \"./Migrations/005_Projections.ts\";\nimport Migration0006 from \"./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts\";\nimport Migration0007 from \"./Migrations/007_ProjectionThreadMessageAttachments.ts\";\nimport Migration0008 from \"./Migrations/008_ProjectionThreadActivitySequence.ts\";\nimport Migration0009 from \"./Migrations/009_ProviderSessionRuntimeMode.ts\";\nimport Migration0010 from \"./Migrations/010_ProjectionThreadsRuntimeMode.ts\";\nimport Migration0011 from \"./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts\";\nimport Migration0012 from \"./Migrations/012_ProjectionThreadsInteractionMode.ts\";\nimport Migration0013 from \"./Migrations/013_ProjectionThreadProposedPlans.ts\";\nimport Migration0014 from \"./Migrations/014_ProjectionThreadProposedPlanImplementation.ts\";\nimport Migration0015 from \"./Migrations/015_ProjectionTurnsSourceProposedPlan.ts\";\nimport Migration0016 from \"./Migrations/016_CanonicalizeModelSelections.ts\";\nimport Migration0017 from \"./Migrations/017_ProjectionThreadsArchivedAt.ts\";\nimport Migration0018 from \"./Migrations/018_ProjectionThreadsArchivedAtIndex.ts\";\nimport Migration0019 from \"./Migrations/019_ProjectionSnapshotLookupIndexes.ts\";\nimport Migration0020 from \"./Migrations/020_AuthAccessManagement.ts\";\nimport Migration0021 from \"./Migrations/021_AuthSessionClientMetadata.ts\";\nimport Migration0022 from \"./Migrations/022_AuthSessionLastConnectedAt.ts\";\nimport Migration0023 from \"./Migrations/023_ProjectionThreadShellSummary.ts\";\nimport Migration0024 from \"./Migrations/024_BackfillProjectionThreadShellSummary.ts\";\nimport Migration0025 from \"./Migrations/025_CleanupInvalidProjectionPendingApprovals.ts\";\nimport Migration0026 from \"./Migrations/026_CanonicalizeModelSelectionOptions.ts\";\nimport Migration0027 from \"./Migrations/027_ProviderSessionRuntimeInstanceId.ts\";\nimport Migration0028 from \"./Migrations/028_ProjectionThreadSessionInstanceId.ts\";\nimport Migration0029 from \"./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts\";\nimport Migration0030 from \"./Migrations/030_ProjectionThreadShellArchiveIndexes.ts\";\nimport Migration0031 from \"./Migrations/031_AuthAuthorizationScopes.ts\";\nimport Migration0032 from \"./Migrations/032_AuthPairingProofKeyThumbprint.ts\";\nimport Migration0033 from \"./Migrations/033_ProjectionThreadsSettled.ts\";\nimport Migration0034 from \"./Migrations/034_ProjectionThreadsSnoozed.ts\";\nimport Migration0035 from \"./Migrations/035_ProjectionThreadTitleRegeneration.ts\";\nimport Migration0036 from \"./Migrations/036_ProjectionThreadsPinned.ts\";\nimport Migration0037 from \"./Migrations/037_ProjectionTurnsKeysetIndex.ts\";\nimport Migration0038 from \"./Migrations/038_ProjectionThreadsPinOrderKey.ts\";\n\n/**\n * Migration loader with all migrations defined inline.\n *\n * Key format: \"{id}_{name}\" where:\n * - id: numeric migration ID (determines execution order)\n * - name: descriptive name for the migration\n *\n * Uses Migrator.fromRecord which parses the key format and\n * returns migrations sorted by ID.\n */\nexport const migrationEntries = [\n  [1, \"OrchestrationEvents\", Migration0001],\n  [2, \"OrchestrationCommandReceipts\", Migration0002],\n  [3, \"CheckpointDiffBlobs\", Migration0003],\n  [4, \"ProviderSessionRuntime\", Migration0004],\n  [5, \"Projections\", Migration0005],\n  [6, \"ProjectionThreadSessionRuntimeModeColumns\", Migration0006],\n  [7, \"ProjectionThreadMessageAttachments\", Migration0007],\n  [8, \"ProjectionThreadActivitySequence\", Migration0008],\n  [9, \"ProviderSessionRuntimeMode\", Migration0009],\n  [10, \"ProjectionThreadsRuntimeMode\", Migration0010],\n  [11, \"OrchestrationThreadCreatedRuntimeMode\", Migration0011],\n  [12, \"ProjectionThreadsInteractionMode\", Migration0012],\n  [13, \"ProjectionThreadProposedPlans\", Migration0013],\n  [14, \"ProjectionThreadProposedPlanImplementation\", Migration0014],\n  [15, \"ProjectionTurnsSourceProposedPlan\", Migration0015],\n  [16, \"CanonicalizeModelSelections\", Migration0016],\n  [17, \"ProjectionThreadsArchivedAt\", Migration0017],\n  [18, \"ProjectionThreadsArchivedAtIndex\", Migration0018],\n  [19, \"ProjectionSnapshotLookupIndexes\", Migration0019],\n  [20, \"AuthAccessManagement\", Migration0020],\n  [21, \"AuthSessionClientMetadata\", Migration0021],\n  [22, \"AuthSessionLastConnectedAt\", Migration0022],\n  [23, \"ProjectionThreadShellSummary\", Migration0023],\n  [24, \"BackfillProjectionThreadShellSummary\", Migration0024],\n  [25, \"CleanupInvalidProjectionPendingApprovals\", Migration0025],\n  [26, \"CanonicalizeModelSelectionOptions\", Migration0026],\n  [27, \"ProviderSessionRuntimeInstanceId\", Migration0027],\n  [28, \"ProjectionThreadSessionInstanceId\", Migration0028],\n  [29, \"ProjectionThreadDetailOrderingIndexes\", Migration0029],\n  [30, \"ProjectionThreadShellArchiveIndexes\", Migration0030],\n  [31, \"AuthAuthorizationScopes\", Migration0031],\n  [32, \"AuthPairingProofKeyThumbprint\", Migration0032],\n  [33, \"ProjectionThreadsSettled\", Migration0033],\n  [34, \"ProjectionThreadsSnoozed\", Migration0034],\n  [35, \"ProjectionThreadTitleRegeneration\", Migration0035],\n  [36, \"ProjectionThreadsPinned\", Migration0036],\n  [37, \"ProjectionTurnsKeysetIndex\", Migration0037],\n  [38, \"ProjectionThreadsPinOrderKey\", Migration0038],\n] as const;\n\nexport const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);\n\nexport const makeMigrationLoader = (throughId?: number) =>\n  Migrator.fromRecord(\n    Object.fromEntries(\n      migrationEntries\n        .filter(([id]) => throughId === undefined || id <= throughId)\n        .map(([id, name, migration]) => [`${id}_${name}`, migration]),\n    ),\n  );\n\n/**\n * Migrator run function - no schema dumping needed\n * Uses the base Migrator.make without platform dependencies\n */\nconst run = Migrator.make({});\n\nexport interface RunMigrationsOptions {\n  readonly toMigrationInclusive?: number | undefined;\n}\n\n/**\n * Run all pending migrations.\n *\n * Creates the migrations tracking table (effect_sql_migrations) if it doesn't exist,\n * then runs any migrations with ID greater than the latest recorded migration.\n *\n * Returns array of [id, name] tuples for migrations that were run.\n *\n * @returns Effect containing array of executed migrations\n */\nexport const runMigrations = Effect.fn(\"runMigrations\")(function* ({\n  toMigrationInclusive,\n}: RunMigrationsOptions = {}) {\n  const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });\n  const migrations = executedMigrations.map(([id, name]) => `${id}_${name}`);\n  yield* migrations.length === 0\n    ? Effect.logDebug(\"Database schema is current\")\n    : Effect.log(\"Migrations ran successfully\").pipe(Effect.annotateLogs({ migrations }));\n  return executedMigrations;\n});\n\n/**\n * Layer that runs migrations when the layer is built.\n *\n * Use this to ensure migrations run before your application starts.\n * Migrations are run automatically - no separate script is needed.\n *\n * @example\n * ```typescript\n * import { MigrationsLive } from \"@acme/db/Migrations\"\n * import * as SqliteClient from \"@acme/db/SqliteClient\"\n *\n * // Migrations run automatically when SqliteClient is provided\n * const AppLayer = MigrationsLive.pipe(\n *   Layer.provideMerge(SqliteClient.layer({ filename: \"database.sqlite\" }))\n * )\n * ```\n */\nexport const MigrationsLive = Layer.effectDiscard(runMigrations());\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport type { SqlError } from \"effect/unstable/sql/SqlError\";\n\nimport { runMigrations } from \"../Migrations.ts\";\nimport { ServerConfig } from \"../../config.ts\";\n\ntype RuntimeSqliteLayerConfig = {\n  readonly filename: string;\n  readonly spanAttributes?: Record<string, unknown>;\n};\n\ntype Loader = {\n  layer: (config: RuntimeSqliteLayerConfig) => Layer.Layer<SqlClient.SqlClient, SqlError>;\n};\nconst defaultSqliteClientLoaders = {\n  bun: () => import(\"@effect/sql-sqlite-bun/SqliteClient\"),\n  node: () => import(\"../NodeSqliteClient.ts\"),\n} satisfies Record<string, () => Promise<Loader>>;\n\nconst makeRuntimeSqliteLayer = Effect.fn(\"makeRuntimeSqliteLayer\")(function* (\n  config: RuntimeSqliteLayerConfig,\n) {\n  const runtime = process.versions.bun !== undefined ? \"bun\" : \"node\";\n  const loader = defaultSqliteClientLoaders[runtime];\n  const clientModule = yield* Effect.promise<Loader>(loader);\n  return clientModule.layer(config);\n}, Layer.unwrap);\n\nconst setup = Layer.effectDiscard(\n  Effect.gen(function* () {\n    const sql = yield* SqlClient.SqlClient;\n    yield* sql`PRAGMA foreign_keys = ON;`;\n    yield* sql`PRAGMA journal_mode = WAL;`;\n    yield* runMigrations();\n  }),\n);\n\nexport const makeSqlitePersistenceLive = Effect.fn(\"makeSqlitePersistenceLive\")(function* (\n  dbPath: string,\n) {\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });\n\n  return Layer.provideMerge(\n    setup,\n    makeRuntimeSqliteLayer({\n      filename: dbPath,\n      spanAttributes: {\n        \"db.name\": path.basename(dbPath),\n        \"service.name\": \"t3-server\",\n      },\n    }),\n  );\n}, Layer.unwrap);\n\nexport const SqlitePersistenceMemory = Layer.provideMerge(\n  setup,\n  makeRuntimeSqliteLayer({ filename: \":memory:\" }),\n);\n\nexport const layerConfig = Layer.unwrap(\n  Effect.gen(function* () {\n    const { dbPath } = yield* ServerConfig;\n    return makeSqlitePersistenceLive(dbPath);\n  }),\n);\n","import {\n  AuthAccessTokenType,\n  AuthAccessWriteScope,\n  AuthAdministrativeScopes,\n  AuthStandardClientScopes,\n  type AuthAccessTokenResult,\n  type AuthBrowserSessionResult,\n  type AuthClientMetadata,\n  type AuthClientSession,\n  type AuthCreatePairingCredentialInput,\n  type AuthEnvironmentScope,\n  type AuthPairingLink,\n  type AuthPairingCredentialResult,\n  type AuthSessionId,\n  type AuthSessionState,\n  type ServerAuthDescriptor,\n  type ServerAuthSessionMethod,\n  type AuthWebSocketTicketResult,\n} from \"@t3tools/contracts\";\nimport { encodeOAuthScope } from \"@t3tools/shared/oauthScope\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as HttpServerRequest from \"effect/unstable/http/HttpServerRequest\";\n\nimport * as EnvironmentAuthPolicy from \"./EnvironmentAuthPolicy.ts\";\nimport * as PairingGrantStore from \"./PairingGrantStore.ts\";\nimport * as ServerSecretStore from \"./ServerSecretStore.ts\";\nimport * as SessionStore from \"./SessionStore.ts\";\nimport { verifyRequestDpopProof } from \"./dpop.ts\";\nimport { layerConfig as SqlitePersistenceLayer } from \"../persistence/Layers/Sqlite.ts\";\n\nexport const DEFAULT_SESSION_SUBJECT = \"cli-issued-session\";\nexport const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = \"administrative-bootstrap\";\n\nexport interface IssuedPairingLink {\n  readonly id: string;\n  readonly credential: string;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly subject: string;\n  readonly label?: string;\n  readonly createdAt: DateTime.Utc;\n  readonly expiresAt: DateTime.Utc;\n}\n\nexport interface IssuedBearerSession {\n  readonly sessionId: AuthSessionId;\n  readonly token: string;\n  readonly method: \"bearer-access-token\";\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly subject: string;\n  readonly client: AuthClientMetadata;\n  readonly expiresAt: DateTime.Utc;\n}\n\nexport interface AuthenticatedSession {\n  readonly sessionId: AuthSessionId;\n  readonly subject: string;\n  readonly method: ServerAuthSessionMethod;\n  readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n  readonly proofKeyThumbprint?: string;\n  readonly expiresAt?: DateTime.DateTime;\n}\n\nconst serverAuthInternalErrorContext = {\n  cause: Schema.Defect(),\n};\n\nexport class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthBootstrapCredentialValidationError>()(\n  \"ServerAuthBootstrapCredentialValidationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to validate bootstrap credential.\";\n  }\n}\n\nexport class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(\n  \"ServerAuthSessionCredentialValidationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to validate session credential.\";\n  }\n}\n\nexport class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(\n  \"ServerAuthAuthenticatedSessionIssueError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue authenticated session.\";\n  }\n}\n\nexport class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(\n  \"ServerAuthAuthenticatedAccessTokenIssueError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue authenticated access token.\";\n  }\n}\n\nexport class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(\n  \"ServerAuthPairingLinkCreationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to create pairing link.\";\n  }\n}\n\nexport class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<ServerAuthPairingLinksListError>()(\n  \"ServerAuthPairingLinksListError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to list pairing links.\";\n  }\n}\n\nexport class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(\n  \"ServerAuthPairingLinkRevocationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke pairing link.\";\n  }\n}\n\nexport class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(\n  \"ServerAuthSessionTokenIssueError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue session token.\";\n  }\n}\n\nexport class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerAuthSessionsListError>()(\n  \"ServerAuthSessionsListError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to list sessions.\";\n  }\n}\n\nexport class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(\n  \"ServerAuthSessionRevocationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke session.\";\n  }\n}\n\nexport class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(\n  \"ServerAuthOtherSessionsRevocationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to revoke other sessions.\";\n  }\n}\n\nexport class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(\n  \"ServerAuthWebSocketTokenIssueError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to issue websocket token.\";\n  }\n}\n\nexport class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(\n  \"ServerAuthDpopReplayStateRecordError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to record DPoP proof replay state.\";\n  }\n}\n\nexport class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(\n  \"ServerAuthDpopReplayKeyCalculationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to calculate DPoP replay key.\";\n  }\n}\n\nexport class ServerAuthLinkedCloudAccountVerificationError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountVerificationError>()(\n  \"ServerAuthLinkedCloudAccountVerificationError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Could not verify the linked cloud account.\";\n  }\n}\n\nexport class ServerAuthLinkedCloudAccountReadError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountReadError>()(\n  \"ServerAuthLinkedCloudAccountReadError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Could not read the linked cloud account.\";\n  }\n}\n\nexport class ServerAuthLinkedCloudAccountMissingError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountMissingError>()(\n  \"ServerAuthLinkedCloudAccountMissingError\",\n  {},\n) {\n  override get message(): string {\n    return \"Cloud linked user is not installed for this environment.\";\n  }\n}\n\nexport class ServerAuthCloudLinkJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudLinkJwtSigningError>()(\n  \"ServerAuthCloudLinkJwtSigningError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to sign cloud link JWT.\";\n  }\n}\n\nexport class ServerAuthCloudMintPublicKeyMissingError extends Schema.TaggedErrorClass<ServerAuthCloudMintPublicKeyMissingError>()(\n  \"ServerAuthCloudMintPublicKeyMissingError\",\n  {},\n) {\n  override get message(): string {\n    return \"Cloud mint public key is not installed for this environment.\";\n  }\n}\n\nexport class ServerAuthCloudRelayIssuerMissingError extends Schema.TaggedErrorClass<ServerAuthCloudRelayIssuerMissingError>()(\n  \"ServerAuthCloudRelayIssuerMissingError\",\n  {},\n) {\n  override get message(): string {\n    return \"Cloud relay issuer is not installed for this environment.\";\n  }\n}\n\nexport class ServerAuthCloudHealthJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudHealthJwtSigningError>()(\n  \"ServerAuthCloudHealthJwtSigningError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to sign cloud health JWT.\";\n  }\n}\n\nexport class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudMintJwtSigningError>()(\n  \"ServerAuthCloudMintJwtSigningError\",\n  {\n    ...serverAuthInternalErrorContext,\n  },\n) {\n  override get message(): string {\n    return \"Failed to sign cloud mint JWT.\";\n  }\n}\n\nexport const ServerAuthInternalError = Schema.Union([\n  ServerAuthBootstrapCredentialValidationError,\n  ServerAuthSessionCredentialValidationError,\n  ServerAuthAuthenticatedSessionIssueError,\n  ServerAuthAuthenticatedAccessTokenIssueError,\n  ServerAuthPairingLinkCreationError,\n  ServerAuthPairingLinksListError,\n  ServerAuthPairingLinkRevocationError,\n  ServerAuthSessionTokenIssueError,\n  ServerAuthSessionsListError,\n  ServerAuthSessionRevocationError,\n  ServerAuthOtherSessionsRevocationError,\n  ServerAuthWebSocketTokenIssueError,\n  ServerAuthDpopReplayStateRecordError,\n  ServerAuthDpopReplayKeyCalculationError,\n  ServerAuthLinkedCloudAccountVerificationError,\n  ServerAuthLinkedCloudAccountReadError,\n  ServerAuthLinkedCloudAccountMissingError,\n  ServerAuthCloudLinkJwtSigningError,\n  ServerAuthCloudMintPublicKeyMissingError,\n  ServerAuthCloudRelayIssuerMissingError,\n  ServerAuthCloudHealthJwtSigningError,\n  ServerAuthCloudMintJwtSigningError,\n]);\nexport type ServerAuthInternalError = typeof ServerAuthInternalError.Type;\nexport const isServerAuthInternalError = Schema.is(ServerAuthInternalError);\n\nexport class ServerAuthMissingCredentialError extends Schema.TaggedErrorClass<ServerAuthMissingCredentialError>()(\n  \"ServerAuthMissingCredentialError\",\n  {},\n) {\n  override get message(): string {\n    return \"Server authentication credential is missing.\";\n  }\n}\n\nexport class ServerAuthInvalidCredentialError extends Schema.TaggedErrorClass<ServerAuthInvalidCredentialError>()(\n  \"ServerAuthInvalidCredentialError\",\n  {\n    diagnostic: Schema.optional(Schema.String),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return \"Server authentication credential is invalid.\";\n  }\n}\n\nexport const ServerAuthCredentialError = Schema.Union([\n  ServerAuthMissingCredentialError,\n  ServerAuthInvalidCredentialError,\n]);\nexport type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;\nexport const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);\nexport const serverAuthCredentialReason = (\n  error: ServerAuthCredentialError,\n): \"missing_credential\" | \"invalid_credential\" =>\n  error._tag === \"ServerAuthMissingCredentialError\" ? \"missing_credential\" : \"invalid_credential\";\n\nexport class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerAuthInvalidScopeError>()(\n  \"ServerAuthInvalidScopeError\",\n  {},\n) {\n  override get message(): string {\n    return \"The requested authentication scope is invalid.\";\n  }\n}\n\nexport class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(\n  \"ServerAuthScopeNotGrantedError\",\n  {},\n) {\n  override get message(): string {\n    return \"The requested authentication scope was not granted.\";\n  }\n}\n\nexport const ServerAuthInvalidRequestError = Schema.Union([\n  ServerAuthInvalidScopeError,\n  ServerAuthScopeNotGrantedError,\n]);\nexport type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;\nexport const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);\nexport const serverAuthInvalidRequestReason = (\n  error: ServerAuthInvalidRequestError,\n): \"invalid_scope\" | \"scope_not_granted\" =>\n  error._tag === \"ServerAuthInvalidScopeError\" ? \"invalid_scope\" : \"scope_not_granted\";\n\nexport class ServerAuthForbiddenOperationError extends Schema.TaggedErrorClass<ServerAuthForbiddenOperationError>()(\n  \"ServerAuthForbiddenOperationError\",\n  {},\n) {\n  override get message(): string {\n    return \"The current authentication session cannot revoke itself.\";\n  }\n}\n\nexport class EnvironmentAuth extends Context.Service<\n  EnvironmentAuth,\n  {\n    readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;\n    readonly getSessionState: (\n      request: HttpServerRequest.HttpServerRequest,\n    ) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;\n    readonly createBrowserSession: (\n      credential: string,\n      requestMetadata: AuthClientMetadata,\n    ) => Effect.Effect<\n      {\n        readonly response: AuthBrowserSessionResult;\n        readonly sessionToken: string;\n      },\n      ServerAuthInvalidCredentialError | ServerAuthInternalError\n    >;\n    readonly exchangeBootstrapCredentialForAccessToken: (\n      credential: string,\n      requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,\n      requestMetadata: AuthClientMetadata,\n      input?: {\n        readonly proofKeyThumbprint?: string;\n      },\n    ) => Effect.Effect<\n      AuthAccessTokenResult,\n      ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError\n    >;\n    readonly createPairingLink: (input?: {\n      readonly ttl?: Duration.Duration;\n      readonly label?: string;\n      readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;\n      readonly subject?: string;\n      readonly proofKeyThumbprint?: string;\n      readonly purpose?: \"startup\";\n    }) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;\n    readonly issuePairingCredential: (\n      input?: AuthCreatePairingCredentialInput,\n    ) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;\n    readonly issueStartupPairingCredential: () => Effect.Effect<\n      AuthPairingCredentialResult,\n      ServerAuthInternalError\n    >;\n    readonly listPairingLinks: (input?: {\n      readonly excludeSubjects?: ReadonlyArray<string>;\n    }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;\n    readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;\n    readonly issueSession: (input?: {\n      readonly ttl?: Duration.Duration;\n      readonly subject?: string;\n      readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;\n      readonly label?: string;\n    }) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;\n    readonly listSessions: () => Effect.Effect<\n      ReadonlyArray<AuthClientSession>,\n      ServerAuthInternalError\n    >;\n    readonly revokeSession: (\n      sessionId: AuthSessionId,\n    ) => Effect.Effect<boolean, ServerAuthInternalError>;\n    readonly revokeOtherSessionsExcept: (\n      sessionId: AuthSessionId,\n    ) => Effect.Effect<number, ServerAuthInternalError>;\n    readonly listClientSessions: (\n      currentSessionId: AuthSessionId,\n    ) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;\n    readonly revokeClientSession: (\n      currentSessionId: AuthSessionId,\n      targetSessionId: AuthSessionId,\n    ) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;\n    readonly revokeOtherClientSessions: (\n      currentSessionId: AuthSessionId,\n    ) => Effect.Effect<number, ServerAuthInternalError>;\n    readonly authenticateHttpRequest: (\n      request: HttpServerRequest.HttpServerRequest,\n    ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;\n    readonly authenticateWebSocketUpgrade: (\n      request: HttpServerRequest.HttpServerRequest,\n    ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;\n    readonly issueWebSocketTicket: (\n      session: Pick<AuthenticatedSession, \"sessionId\">,\n    ) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;\n    readonly issueStartupPairingUrl: (\n      baseUrl: string,\n    ) => Effect.Effect<string, ServerAuthInternalError>;\n  }\n>()(\"t3/auth/EnvironmentAuth\") {}\n\ntype BootstrapExchangeResult = {\n  readonly response: AuthBrowserSessionResult;\n  readonly sessionToken: string;\n};\n\nconst AUTHORIZATION_PREFIX = \"Bearer \";\nconst DPOP_AUTHORIZATION_PREFIX = \"DPoP \";\nconst WEBSOCKET_TICKET_QUERY_PARAM = \"wsTicket\";\n\nconst bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {\n  const leftCanManage = left.scopes.includes(AuthAccessWriteScope);\n  const rightCanManage = right.scopes.includes(AuthAccessWriteScope);\n  if (leftCanManage !== rightCanManage) {\n    return leftCanManage ? -1 : 1;\n  }\n  if (left.connected !== right.connected) {\n    return left.connected ? -1 : 1;\n  }\n  return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;\n};\n\nexport function toBootstrapExchangeError(\n  cause: PairingGrantStore.BootstrapCredentialError,\n): ServerAuthInvalidCredentialError | ServerAuthInternalError {\n  if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {\n    return new ServerAuthBootstrapCredentialValidationError({ cause });\n  }\n\n  return new ServerAuthInvalidCredentialError({\n    cause,\n  });\n}\n\nconst mapSessionVerificationErrors = <A, R>(\n  effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,\n): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>\n  effect.pipe(\n    Effect.mapError((cause) =>\n      SessionStore.isSessionCredentialInvalidError(cause)\n        ? new ServerAuthInvalidCredentialError({ cause })\n        : new ServerAuthSessionCredentialValidationError({ cause }),\n    ),\n  );\n\nfunction parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {\n  const header = request.headers[\"authorization\"];\n  if (typeof header !== \"string\" || !header.startsWith(AUTHORIZATION_PREFIX)) {\n    return null;\n  }\n  const token = header.slice(AUTHORIZATION_PREFIX.length).trim();\n  return token.length > 0 ? token : null;\n}\n\nfunction parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null {\n  const header = request.headers[\"authorization\"];\n  if (typeof header !== \"string\" || !header.startsWith(DPOP_AUTHORIZATION_PREFIX)) {\n    return null;\n  }\n  const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim();\n  return token.length > 0 ? token : null;\n}\n\nexport const make = Effect.gen(function* () {\n  const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;\n  const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;\n  const sessions = yield* SessionStore.SessionStore;\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const crypto = yield* Crypto.Crypto;\n  const descriptor = yield* policy.getDescriptor();\n\n  const authenticateToken = (\n    token: string,\n  ): Effect.Effect<\n    AuthenticatedSession,\n    ServerAuthInvalidCredentialError | ServerAuthInternalError\n  > =>\n    sessions.verify(token).pipe(\n      Effect.tapError((cause) =>\n        SessionStore.isSessionCredentialInvalidError(cause)\n          ? Effect.logWarning(\"Rejected authenticated session credential.\").pipe(\n              Effect.annotateLogs({\n                reason: cause.message,\n              }),\n            )\n          : Effect.void,\n      ),\n      Effect.map((session) => ({\n        sessionId: session.sessionId,\n        subject: session.subject,\n        method: session.method,\n        scopes: session.scopes,\n        ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),\n        ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),\n      })),\n      mapSessionVerificationErrors,\n    );\n\n  const authenticateRequest = (\n    request: HttpServerRequest.HttpServerRequest,\n  ): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {\n    const cookieToken = request.cookies[sessions.cookieName];\n    const bearerToken = parseBearerToken(request);\n    const dpopToken = parseDpopToken(request);\n    const credential = cookieToken ?? bearerToken ?? dpopToken;\n    if (!credential) {\n      return Effect.fail(new ServerAuthMissingCredentialError({}));\n    }\n    return authenticateToken(credential).pipe(\n      Effect.flatMap((session) => {\n        if (session.proofKeyThumbprint) {\n          if (!dpopToken || dpopToken !== credential) {\n            return Effect.fail(\n              new ServerAuthInvalidCredentialError({\n                diagnostic: \"DPoP-bound access token requires DPoP authorization.\",\n              }),\n            );\n          }\n          return verifyRequestDpopProof({\n            request,\n            expectedThumbprint: session.proofKeyThumbprint,\n            expectedAccessToken: dpopToken,\n          }).pipe(\n            Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),\n            Effect.provideService(Crypto.Crypto, crypto),\n            Effect.as(session),\n          );\n        }\n        if (dpopToken) {\n          return Effect.fail(\n            new ServerAuthInvalidCredentialError({\n              diagnostic: \"DPoP authorization requires a proof-bound access token.\",\n            }),\n          );\n        }\n        return Effect.succeed(session);\n      }),\n    );\n  };\n\n  const getSessionState: EnvironmentAuth[\"Service\"][\"getSessionState\"] = (request) =>\n    authenticateRequest(request).pipe(\n      Effect.map(\n        (session) =>\n          ({\n            authenticated: true,\n            auth: descriptor,\n            scopes: session.scopes,\n            sessionMethod: session.method,\n            ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),\n          }) satisfies AuthSessionState,\n      ),\n      Effect.catchIf(isServerAuthCredentialError, () =>\n        Effect.succeed({\n          authenticated: false,\n          auth: descriptor,\n        } satisfies AuthSessionState),\n      ),\n      Effect.withSpan(\"EnvironmentAuth.getSessionState\"),\n    );\n\n  const createBrowserSession: EnvironmentAuth[\"Service\"][\"createBrowserSession\"] = (\n    credential,\n    requestMetadata,\n  ) =>\n    bootstrapCredentials.consume(credential).pipe(\n      Effect.mapError(toBootstrapExchangeError),\n      Effect.flatMap((grant) =>\n        sessions\n          .issue({\n            method: \"browser-session-cookie\",\n            subject: grant.subject,\n            scopes: grant.scopes,\n            client: {\n              ...requestMetadata,\n              ...(grant.label ? { label: grant.label } : {}),\n            },\n          })\n          .pipe(\n            Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),\n          ),\n      ),\n      Effect.map(\n        (session) =>\n          ({\n            response: {\n              authenticated: true,\n              scopes: session.scopes,\n              sessionMethod: session.method,\n              expiresAt: DateTime.toUtc(session.expiresAt),\n            } satisfies AuthBrowserSessionResult,\n            sessionToken: session.token,\n          }) satisfies BootstrapExchangeResult,\n      ),\n      Effect.withSpan(\"EnvironmentAuth.createBrowserSession\"),\n    );\n\n  const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth[\"Service\"][\"exchangeBootstrapCredentialForAccessToken\"] =\n    (credential, requestedScopes, requestMetadata, input) =>\n      bootstrapCredentials.consume(credential, input).pipe(\n        Effect.mapError(toBootstrapExchangeError),\n        Effect.flatMap((grant) =>\n          Effect.gen(function* () {\n            const grantedScopes = requestedScopes ?? grant.scopes;\n            if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {\n              return yield* new ServerAuthScopeNotGrantedError({});\n            }\n            return yield* sessions\n              .issue({\n                method: input?.proofKeyThumbprint ? \"dpop-access-token\" : \"bearer-access-token\",\n                subject: grant.subject,\n                scopes: grantedScopes,\n                ...(input?.proofKeyThumbprint\n                  ? {\n                      proofKeyThumbprint: input.proofKeyThumbprint,\n                      ttl: Duration.hours(1),\n                    }\n                  : {}),\n                client: {\n                  ...requestMetadata,\n                  ...(grant.label ? { label: grant.label } : {}),\n                },\n              })\n              .pipe(\n                Effect.mapError(\n                  (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),\n                ),\n              );\n          }),\n        ),\n        Effect.flatMap((session) =>\n          DateTime.now.pipe(\n            Effect.map(\n              (now) =>\n                ({\n                  access_token: session.token,\n                  issued_token_type: AuthAccessTokenType,\n                  token_type: input?.proofKeyThumbprint ? \"DPoP\" : \"Bearer\",\n                  expires_in: Math.max(\n                    0,\n                    Math.floor(\n                      (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,\n                    ),\n                  ),\n                  scope: encodeOAuthScope(session.scopes),\n                }) satisfies AuthAccessTokenResult,\n            ),\n          ),\n        ),\n        Effect.withSpan(\"EnvironmentAuth.exchangeBootstrapCredentialForAccessToken\"),\n      );\n\n  const issuePairingCredentialForSubject = (input: {\n    readonly scopes: ReadonlyArray<AuthEnvironmentScope>;\n    readonly subject: string;\n    readonly label?: string;\n    readonly purpose?: \"startup\";\n  }) =>\n    createPairingLink({\n      scopes: input.scopes,\n      subject: input.subject,\n      ...(input.label ? { label: input.label } : {}),\n      ...(input.purpose ? { purpose: input.purpose } : {}),\n    }).pipe(\n      Effect.map(\n        (issued) =>\n          ({\n            id: issued.id,\n            credential: issued.credential,\n            ...(issued.label ? { label: issued.label } : {}),\n            expiresAt: issued.expiresAt,\n          }) satisfies AuthPairingCredentialResult,\n      ),\n    );\n\n  const createPairingLink: EnvironmentAuth[\"Service\"][\"createPairingLink\"] = Effect.fn(\n    \"EnvironmentAuth.createPairingLink\",\n  )(\n    function* (input) {\n      const createdAt = yield* DateTime.now;\n      const issued = yield* bootstrapCredentials.issueOneTimeToken({\n        scopes: input?.scopes ?? AuthStandardClientScopes,\n        subject: input?.subject ?? \"one-time-token\",\n        ...(input?.ttl ? { ttl: input.ttl } : {}),\n        ...(input?.label ? { label: input.label } : {}),\n        ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),\n        ...(input?.purpose ? { purpose: input.purpose } : {}),\n      });\n      return {\n        id: issued.id,\n        credential: issued.credential,\n        scopes: input?.scopes ?? AuthStandardClientScopes,\n        subject: input?.subject ?? \"one-time-token\",\n        ...(issued.label ? { label: issued.label } : {}),\n        createdAt: DateTime.toUtc(createdAt),\n        expiresAt: DateTime.toUtc(issued.expiresAt),\n      } satisfies IssuedPairingLink;\n    },\n    Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),\n  );\n\n  const listPairingLinks: EnvironmentAuth[\"Service\"][\"listPairingLinks\"] = (input) =>\n    bootstrapCredentials.listActive().pipe(\n      Effect.map((pairingLinks) => {\n        const excludedSubjects = input?.excludeSubjects ?? [\n          INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,\n        ];\n        return pairingLinks\n          .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))\n          .toSorted(\n            (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,\n          );\n      }),\n      Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.listPairingLinks\"),\n    );\n\n  const revokePairingLink: EnvironmentAuth[\"Service\"][\"revokePairingLink\"] = (id) =>\n    bootstrapCredentials.revoke(id).pipe(\n      Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.revokePairingLink\"),\n    );\n\n  const issueSession: EnvironmentAuth[\"Service\"][\"issueSession\"] = (input) =>\n    sessions\n      .issue({\n        subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,\n        method: \"bearer-access-token\",\n        scopes: input?.scopes ?? AuthAdministrativeScopes,\n        client: {\n          ...(input?.label ? { label: input.label } : {}),\n          deviceType: \"bot\",\n        },\n        ...(input?.ttl ? { ttl: input.ttl } : {}),\n      })\n      .pipe(\n        Effect.map(\n          (issued) =>\n            ({\n              sessionId: issued.sessionId,\n              token: issued.token,\n              method: \"bearer-access-token\",\n              scopes: issued.scopes,\n              subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,\n              client: issued.client,\n              expiresAt: DateTime.toUtc(issued.expiresAt),\n            }) satisfies IssuedBearerSession,\n        ),\n        Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),\n        Effect.withSpan(\"EnvironmentAuth.issueSession\"),\n      );\n\n  const listSessions: EnvironmentAuth[\"Service\"][\"listSessions\"] = () =>\n    sessions.listActive().pipe(\n      Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),\n      Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.listSessions\"),\n    );\n\n  const revokeSession: EnvironmentAuth[\"Service\"][\"revokeSession\"] = (sessionId) =>\n    sessions.revoke(sessionId).pipe(\n      Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.revokeSession\"),\n    );\n\n  const revokeOtherSessionsExcept: EnvironmentAuth[\"Service\"][\"revokeOtherSessionsExcept\"] = (\n    sessionId,\n  ) =>\n    sessions.revokeAllExcept(sessionId).pipe(\n      Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),\n      Effect.withSpan(\"EnvironmentAuth.revokeOtherSessionsExcept\"),\n    );\n\n  const issuePairingCredential: EnvironmentAuth[\"Service\"][\"issuePairingCredential\"] = (input) =>\n    issuePairingCredentialForSubject({\n      scopes: input?.scopes ?? AuthStandardClientScopes,\n      subject: \"one-time-token\",\n      ...(input?.label ? { label: input.label } : {}),\n    }).pipe(Effect.withSpan(\"EnvironmentAuth.issuePairingCredential\"));\n\n  const issueStartupPairingCredential: EnvironmentAuth[\"Service\"][\"issueStartupPairingCredential\"] =\n    () =>\n      issuePairingCredentialForSubject({\n        scopes: AuthAdministrativeScopes,\n        subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,\n        purpose: \"startup\",\n      }).pipe(Effect.withSpan(\"EnvironmentAuth.issueStartupPairingCredential\"));\n\n  const listClientSessions: EnvironmentAuth[\"Service\"][\"listClientSessions\"] = (currentSessionId) =>\n    listSessions().pipe(\n      Effect.map((clientSessions) =>\n        clientSessions.map(\n          (clientSession): AuthClientSession => ({\n            ...clientSession,\n            current: clientSession.sessionId === currentSessionId,\n          }),\n        ),\n      ),\n      Effect.withSpan(\"EnvironmentAuth.listClientSessions\"),\n    );\n\n  const revokeClientSession: EnvironmentAuth[\"Service\"][\"revokeClientSession\"] = Effect.fn(\n    \"EnvironmentAuth.revokeClientSession\",\n  )(function* (currentSessionId, targetSessionId) {\n    if (currentSessionId === targetSessionId) {\n      return yield* new ServerAuthForbiddenOperationError({});\n    }\n    return yield* revokeSession(targetSessionId);\n  });\n\n  const revokeOtherClientSessions: EnvironmentAuth[\"Service\"][\"revokeOtherClientSessions\"] = (\n    currentSessionId,\n  ) =>\n    revokeOtherSessionsExcept(currentSessionId).pipe(\n      Effect.withSpan(\"EnvironmentAuth.revokeOtherClientSessions\"),\n    );\n\n  const issueStartupPairingUrl: EnvironmentAuth[\"Service\"][\"issueStartupPairingUrl\"] = (baseUrl) =>\n    issueStartupPairingCredential().pipe(\n      Effect.map((issued) => {\n        const url = new URL(baseUrl);\n        url.pathname = \"/pair\";\n        url.searchParams.delete(\"token\");\n        url.hash = new URLSearchParams([[\"token\", issued.credential]]).toString();\n        return url.toString();\n      }),\n      Effect.withSpan(\"EnvironmentAuth.issueStartupPairingUrl\"),\n    );\n\n  const issueWebSocketTicket: EnvironmentAuth[\"Service\"][\"issueWebSocketTicket\"] = (session) =>\n    sessions.issueWebSocketToken(session.sessionId).pipe(\n      Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),\n      Effect.map(\n        (issued) =>\n          ({\n            ticket: issued.token,\n            expiresAt: DateTime.toUtc(issued.expiresAt),\n          }) satisfies AuthWebSocketTicketResult,\n      ),\n      Effect.withSpan(\"EnvironmentAuth.issueWebSocketTicket\"),\n    );\n\n  const authenticateHttpRequest: EnvironmentAuth[\"Service\"][\"authenticateHttpRequest\"] = (\n    request,\n  ) =>\n    authenticateRequest(request).pipe(Effect.withSpan(\"EnvironmentAuth.authenticateHttpRequest\"));\n\n  const authenticateWebSocketUpgrade: EnvironmentAuth[\"Service\"][\"authenticateWebSocketUpgrade\"] =\n    Effect.fn(\"EnvironmentAuth.authenticateWebSocketUpgrade\")(function* (request) {\n      const requestUrl = HttpServerRequest.toURL(request);\n      if (Option.isSome(requestUrl)) {\n        const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);\n        if (websocketTicket && websocketTicket.trim().length > 0) {\n          return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(\n            Effect.map((session) => ({\n              sessionId: session.sessionId,\n              subject: session.subject,\n              method: session.method,\n              scopes: session.scopes,\n              ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),\n            })),\n            mapSessionVerificationErrors,\n          );\n        }\n      }\n\n      return yield* authenticateRequest(request);\n    });\n\n  return EnvironmentAuth.of({\n    getDescriptor: () =>\n      Effect.succeed(descriptor).pipe(Effect.withSpan(\"EnvironmentAuth.getDescriptor\")),\n    getSessionState,\n    createBrowserSession,\n    exchangeBootstrapCredentialForAccessToken,\n    createPairingLink,\n    issuePairingCredential,\n    issueStartupPairingCredential,\n    listPairingLinks,\n    revokePairingLink,\n    issueSession,\n    listSessions,\n    revokeSession,\n    revokeOtherSessionsExcept,\n    listClientSessions,\n    revokeClientSession,\n    revokeOtherClientSessions,\n    authenticateHttpRequest,\n    authenticateWebSocketUpgrade,\n    issueWebSocketTicket,\n    issueStartupPairingUrl,\n  });\n});\n\nexport const layer = Layer.effect(EnvironmentAuth, make).pipe(\n  Layer.provideMerge(PairingGrantStore.layer),\n  Layer.provideMerge(SessionStore.layer),\n  Layer.provideMerge(EnvironmentAuthPolicy.layer),\n);\n\nexport const storageLayer = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistenceLayer);\n\nexport const runtimeLayer = layer.pipe(Layer.provideMerge(storageLayer));\n","import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\n\nimport type { IssuedBearerSession, IssuedPairingLink } from \"./auth/EnvironmentAuth.ts\";\n\nconst newline = \"\\n\";\n\nfunction serializeOptionalFields(values: ReadonlyArray<string | null | undefined>) {\n  return values.filter((value): value is string => typeof value === \"string\" && value.length > 0);\n}\n\nfunction formatClientMetadata(metadata: AuthClientMetadata): string {\n  const details = serializeOptionalFields([\n    metadata.label,\n    metadata.deviceType !== \"unknown\" ? metadata.deviceType : undefined,\n    metadata.os,\n    metadata.browser,\n    metadata.ipAddress,\n  ]);\n  return details.length > 0 ? details.join(\" | \") : \"unlabeled client\";\n}\n\nfunction toIsoString(value: DateTime.DateTime | DateTime.Utc): string {\n  return DateTime.formatIso(DateTime.toUtc(value));\n}\n\nexport function formatIssuedPairingCredential(\n  credential: IssuedPairingLink,\n  options?: {\n    readonly json?: boolean;\n    readonly baseUrl?: string;\n  },\n): string {\n  const pairUrl =\n    options?.baseUrl != null && options.baseUrl.length > 0\n      ? (() => {\n          const url = new URL(\"/pair\", options.baseUrl);\n          url.searchParams.delete(\"token\");\n          url.hash = new URLSearchParams([[\"token\", credential.credential]]).toString();\n          return url.toString();\n        })()\n      : undefined;\n\n  if (options?.json) {\n    return `${JSON.stringify(\n      {\n        id: credential.id,\n        credential: credential.credential,\n        ...(credential.label ? { label: credential.label } : {}),\n        scopes: credential.scopes,\n        expiresAt: toIsoString(credential.expiresAt),\n        ...(pairUrl ? { pairUrl } : {}),\n      },\n      null,\n      2,\n    )}${newline}`;\n  }\n\n  return (\n    [\n      `Issued client pairing token ${credential.id}.`,\n      `Token: ${credential.credential}`,\n      ...(pairUrl ? [`Pair URL: ${pairUrl}`] : []),\n      `Expires at: ${credential.expiresAt}`,\n    ].join(newline) + newline\n  );\n}\n\nexport function formatPairingCredentialList(\n  credentials: ReadonlyArray<AuthPairingLink>,\n  options?: {\n    readonly json?: boolean;\n  },\n): string {\n  if (options?.json) {\n    return `${JSON.stringify(\n      credentials.map((credential) => ({\n        id: credential.id,\n        ...(credential.label ? { label: credential.label } : {}),\n        scopes: credential.scopes,\n        createdAt: toIsoString(credential.createdAt),\n        expiresAt: toIsoString(credential.expiresAt),\n      })),\n      null,\n      2,\n    )}${newline}`;\n  }\n\n  if (credentials.length === 0) {\n    return `No active pairing credentials.${newline}`;\n  }\n\n  return (\n    credentials\n      .map((credential) =>\n        [\n          `${credential.id}${credential.label ? ` (${credential.label})` : \"\"}`,\n          `  scopes: ${credential.scopes.join(\" \")}`,\n          `  created: ${toIsoString(credential.createdAt)}`,\n          `  expires: ${toIsoString(credential.expiresAt)}`,\n        ].join(newline),\n      )\n      .join(`${newline}${newline}`) + newline\n  );\n}\n\nexport function formatIssuedSession(\n  session: IssuedBearerSession,\n  options?: {\n    readonly json?: boolean;\n    readonly tokenOnly?: boolean;\n  },\n): string {\n  if (options?.tokenOnly) {\n    return `${session.token}${newline}`;\n  }\n\n  if (options?.json) {\n    return `${JSON.stringify(\n      {\n        sessionId: session.sessionId,\n        token: session.token,\n        method: session.method,\n        scopes: session.scopes,\n        subject: session.subject,\n        client: session.client,\n        expiresAt: toIsoString(session.expiresAt),\n      },\n      null,\n      2,\n    )}${newline}`;\n  }\n\n  return (\n    [\n      `Issued bearer access token ${session.sessionId}.`,\n      `Scopes: ${session.scopes.join(\" \")}`,\n      `Token: ${session.token}`,\n      `Subject: ${session.subject}`,\n      `Client: ${formatClientMetadata(session.client)}`,\n      `Expires at: ${toIsoString(session.expiresAt)}`,\n    ].join(newline) + newline\n  );\n}\n\nexport function formatSessionList(\n  sessions: ReadonlyArray<AuthClientSession>,\n  options?: {\n    readonly json?: boolean;\n  },\n): string {\n  if (options?.json) {\n    return `${JSON.stringify(\n      sessions.map((session) => ({\n        sessionId: session.sessionId,\n        method: session.method,\n        scopes: session.scopes,\n        subject: session.subject,\n        client: session.client,\n        connected: session.connected,\n        issuedAt: toIsoString(session.issuedAt),\n        expiresAt: toIsoString(session.expiresAt),\n        lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null,\n      })),\n      null,\n      2,\n    )}${newline}`;\n  }\n\n  if (sessions.length === 0) {\n    return `No active sessions.${newline}`;\n  }\n\n  return (\n    sessions\n      .map((session) =>\n        [\n          `${session.sessionId}${session.connected ? \" connected\" : \"\"}`,\n          `  scopes: ${session.scopes.join(\" \")}`,\n          `  method: ${session.method}`,\n          `  subject: ${session.subject}`,\n          `  client: ${formatClientMetadata(session.client)}`,\n          `  issued: ${toIsoString(session.issuedAt)}`,\n          `  last connected: ${\n            session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : \"never\"\n          }`,\n          `  expires: ${toIsoString(session.expiresAt)}`,\n        ].join(newline),\n      )\n      .join(`${newline}${newline}`) + newline\n  );\n}\n","import * as P from \"effect/Predicate\";\n\nexport type DeepPartial<T> = T extends readonly (infer U)[]\n  ? readonly DeepPartial<U>[]\n  : T extends object\n    ? { [K in keyof T]?: DeepPartial<T[K]> }\n    : T;\n\nexport function deepMerge<T extends Record<string, unknown>>(current: T, patch: DeepPartial<T>): T {\n  if (!P.isObject(current) || !P.isObject(patch)) {\n    return patch as T;\n  }\n\n  const next = { ...current } as Record<string, unknown>;\n  for (const [key, value] of Object.entries(patch)) {\n    if (value === undefined) continue;\n\n    const existing = next[key];\n    next[key] = P.isObject(existing) && P.isObject(value) ? deepMerge(existing, value) : value;\n  }\n\n  return next as T;\n}\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaGetter from \"effect/SchemaGetter\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\n\nconst MAX_SCHEMA_DIAGNOSTIC_ISSUES = 8;\nconst MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS = 16;\nconst MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH = 64;\nconst MAX_SCHEMA_DIAGNOSTIC_LENGTH = 2_048;\n\ninterface SchemaDiagnosticIssue {\n  readonly message: string;\n  readonly path: ReadonlyArray<PropertyKey>;\n}\n\n// Schema's default formatter includes actual values. These diagnostics cross\n// process and UI boundaries, so retain only issue kinds and bounded paths.\n\nfunction truncateDiagnostic(value: string, maxLength: number): string {\n  return value.length <= maxLength ? value : `${value.slice(0, maxLength - 3)}...`;\n}\n\nfunction formatDiagnosticPathSegment(key: PropertyKey): string {\n  if (typeof key === \"number\") {\n    return `[${key}]`;\n  }\n  const value = truncateDiagnostic(\n    typeof key === \"symbol\" ? String(key) : key,\n    MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENT_LENGTH,\n  );\n  return `[${JSON.stringify(value)}]`;\n}\n\nfunction formatDiagnosticIssue(issue: SchemaDiagnosticIssue): string {\n  if (issue.path.length === 0) {\n    return issue.message;\n  }\n  const path = issue.path\n    .slice(0, MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS)\n    .map(formatDiagnosticPathSegment)\n    .join(\"\");\n  const suffix = issue.path.length > MAX_SCHEMA_DIAGNOSTIC_PATH_SEGMENTS ? \"[...]\" : \"\";\n  return `${issue.message}\\n  at ${path}${suffix}`;\n}\n\nfunction schemaDiagnosticMessage(issue: SchemaIssue.Issue): string {\n  switch (issue._tag) {\n    case \"InvalidType\":\n      return \"Invalid type\";\n    case \"InvalidValue\":\n    case \"Filter\":\n    case \"AnyOf\":\n    case \"Encoding\":\n    case \"Pointer\":\n    case \"Composite\":\n      return \"Invalid value\";\n    case \"MissingKey\":\n      return \"Missing key\";\n    case \"UnexpectedKey\":\n      return \"Unexpected key\";\n    case \"Forbidden\":\n      return \"Forbidden operation\";\n    case \"OneOf\":\n      return \"Expected exactly one schema member to match\";\n  }\n}\n\nfunction collectSchemaDiagnosticIssues(\n  issue: SchemaIssue.Issue,\n  path: ReadonlyArray<PropertyKey>,\n  diagnostics: Array<SchemaDiagnosticIssue>,\n): number {\n  switch (issue._tag) {\n    case \"Encoding\":\n      return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);\n    case \"Filter\":\n      if (issue.issue._tag !== \"InvalidValue\") {\n        return collectSchemaDiagnosticIssues(issue.issue, path, diagnostics);\n      }\n      break;\n    case \"Pointer\":\n      return collectSchemaDiagnosticIssues(issue.issue, [...path, ...issue.path], diagnostics);\n    case \"Composite\":\n      return issue.issues.reduce(\n        (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),\n        0,\n      );\n    case \"AnyOf\":\n      if (issue.issues.length > 0) {\n        return issue.issues.reduce(\n          (count, issue) => count + collectSchemaDiagnosticIssues(issue, path, diagnostics),\n          0,\n        );\n      }\n      break;\n  }\n\n  if (diagnostics.length < MAX_SCHEMA_DIAGNOSTIC_ISSUES) {\n    diagnostics.push({ message: schemaDiagnosticMessage(issue), path });\n  }\n  return 1;\n}\n\nexport const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(\n  schema: S,\n) => {\n  const decode = Schema.decodeExit(Schema.fromJsonString(schema));\n  return (input: string) => {\n    const result = decode(input);\n    if (Exit.isFailure(result)) {\n      return Result.fail(result.cause);\n    }\n    return Result.succeed(result.value);\n  };\n};\n\nexport const decodeUnknownJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(\n  schema: S,\n) => {\n  const decode = Schema.decodeUnknownExit(Schema.fromJsonString(schema));\n  return (input: unknown) => {\n    const result = decode(input);\n    if (Exit.isFailure(result)) {\n      return Result.fail(result.cause);\n    }\n    return Result.succeed(result.value);\n  };\n};\n\nexport const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {\n  const issues: Array<SchemaDiagnosticIssue> = [];\n  let issueCount = 0;\n  let failureCount = 0;\n  let defectCount = 0;\n  let interruptionCount = 0;\n\n  for (const reason of cause.reasons) {\n    switch (reason._tag) {\n      case \"Fail\":\n        failureCount += 1;\n        if (Schema.isSchemaError(reason.error)) {\n          issueCount += collectSchemaDiagnosticIssues(reason.error.issue, [], issues);\n        }\n        break;\n      case \"Die\":\n        defectCount += 1;\n        break;\n      case \"Interrupt\":\n        interruptionCount += 1;\n        break;\n    }\n  }\n\n  if (issues.length === 0) {\n    return `Schema validation failed (failureCount=${failureCount}, defectCount=${defectCount}, interruptionCount=${interruptionCount}).`;\n  }\n\n  const omittedIssueCount = issueCount - issues.length;\n  const formatted = issues.map(formatDiagnosticIssue).join(\"\\n\");\n  if (omittedIssueCount === 0) {\n    return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH);\n  }\n  const suffix = `\\n... and ${omittedIssueCount} more issue(s)`;\n  return truncateDiagnostic(formatted, MAX_SCHEMA_DIAGNOSTIC_LENGTH - suffix.length) + suffix;\n};\n\n/**\n * A `Getter` that parses a lenient JSON string (tolerating trailing commas\n * and JS-style comments) into an unknown value.\n *\n * Mirrors `SchemaGetter.parseJson()` but strips JSONC syntax before parsing.\n */\nconst decodeJsonString = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst parseLenientJsonGetter = SchemaGetter.onSome((input: string) => {\n  // Strip single-line comments - alternation preserves quoted strings.\n  let stripped = input.replace(\n    /(\"(?:[^\"\\\\]|\\\\.)*\")|\\/\\/[^\\n]*/g,\n    (match, stringLiteral: string | undefined) => (stringLiteral ? match : \"\"),\n  );\n\n  // Strip multi-line comments.\n  stripped = stripped.replace(\n    /(\"(?:[^\"\\\\]|\\\\.)*\")|\\/\\*[\\s\\S]*?\\*\\//g,\n    (match, stringLiteral: string | undefined) => (stringLiteral ? match : \"\"),\n  );\n\n  // Strip trailing commas before `}` or `]`. The alternation preserves quoted\n  // strings so a comma inside a string value (e.g. `{\"note\":\"a,]\"}`) is not\n  // mistaken for a trailing comma and removed.\n  stripped = stripped.replace(\n    /(\"(?:[^\"\\\\]|\\\\.)*\")|,(\\s*[}\\]])/g,\n    (match, stringLiteral: string | undefined, bracket: string | undefined) =>\n      stringLiteral ? match : (bracket ?? \"\"),\n  );\n\n  return decodeJsonString(stripped).pipe(\n    Effect.map(Option.some),\n    Effect.mapError((error) => error.issue),\n  );\n});\n\n/**\n * Schema transformation: lenient JSONC string ↔ unknown.\n *\n * Same API as `SchemaTransformation.fromJsonString`, but the decode side\n * strips trailing commas and JS-style comments before parsing.\n * Encoding produces strict JSON via `JSON.stringify`.\n */\nexport const fromLenientJsonString = new SchemaTransformation.Transformation(\n  parseLenientJsonGetter,\n  SchemaGetter.stringifyJson(),\n);\n\nexport const prettyJsonString = SchemaGetter.parseJson<string>().compose(\n  SchemaGetter.stringifyJson({ space: 2 }),\n);\n\n/**\n * Build a schema that decodes a lenient JSON string into `A`.\n *\n * Drop-in replacement for `Schema.fromJsonString(schema)` that tolerates\n * trailing commas and comments in the input.\n */\nexport const fromLenientJson = <S extends Schema.Top>(schema: S) =>\n  Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));\n\nexport function extractJsonObject(raw: string): string {\n  const trimmed = raw.trim();\n  if (trimmed.length === 0) {\n    return trimmed;\n  }\n\n  const start = trimmed.indexOf(\"{\");\n  if (start < 0) {\n    return trimmed;\n  }\n\n  let depth = 0;\n  let inString = false;\n  let escaping = false;\n  for (let index = start; index < trimmed.length; index += 1) {\n    const char = trimmed[index];\n    if (inString) {\n      if (escaping) {\n        escaping = false;\n      } else if (char === \"\\\\\") {\n        escaping = true;\n      } else if (char === '\"') {\n        inString = false;\n      }\n      continue;\n    }\n\n    if (char === '\"') {\n      inString = true;\n      continue;\n    }\n\n    if (char === \"{\") {\n      depth += 1;\n      continue;\n    }\n\n    if (char === \"}\") {\n      depth -= 1;\n      if (depth === 0) {\n        return trimmed.slice(start, index + 1);\n      }\n    }\n  }\n\n  return trimmed.slice(start);\n}\n\n/**\n * Build a JSON string schema that encodes with stable 2-space formatting.\n *\n * Decode behavior matches `Schema.fromJsonString(schema)`. Encode behavior\n * keeps the transformation schema-based while preserving human-readable JSON.\n */\nexport const fromJsonStringPretty = <S extends Schema.Top>(schema: S) =>\n  Schema.fromJsonString(schema).pipe(\n    Schema.encode({\n      decode: prettyJsonString,\n      encode: prettyJsonString,\n    }),\n  );\n","import {\n  DEFAULT_MODEL,\n  DEFAULT_MODEL_BY_PROVIDER,\n  MODEL_SLUG_ALIASES_BY_PROVIDER,\n  type ModelCapabilities,\n  type ModelSelection,\n  ProviderDriverKind,\n  ProviderInstanceId,\n  type ProviderOptionDescriptor,\n  type ProviderOptionSelection,\n} from \"@t3tools/contracts\";\n\nconst DEFAULT_PROVIDER_DRIVER_KIND = ProviderDriverKind.make(\"codex\");\n\nexport interface SelectableModelOption {\n  slug: string;\n  name: string;\n}\n\nexport function createModelCapabilities(input: {\n  optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;\n}): ModelCapabilities {\n  return {\n    optionDescriptors: input.optionDescriptors.map(cloneDescriptor),\n  };\n}\n\nfunction getRawSelectionValueById(\n  selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n  id: string,\n): string | boolean | undefined {\n  const selection = selections?.find((candidate) => candidate.id === id);\n  return selection?.value;\n}\n\nexport function getProviderOptionSelectionValue(\n  selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n  id: string,\n): string | boolean | undefined {\n  return getRawSelectionValueById(selections, id);\n}\n\nexport function getProviderOptionStringSelectionValue(\n  selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n  id: string,\n): string | undefined {\n  const value = getProviderOptionSelectionValue(selections, id);\n  return typeof value === \"string\" ? value : undefined;\n}\n\nexport function getProviderOptionBooleanSelectionValue(\n  selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n  id: string,\n): boolean | undefined {\n  const value = getProviderOptionSelectionValue(selections, id);\n  return typeof value === \"boolean\" ? value : undefined;\n}\n\nexport function getModelSelectionOptionValue(\n  modelSelection: ModelSelection | null | undefined,\n  id: string,\n): string | boolean | undefined {\n  return getProviderOptionSelectionValue(modelSelection?.options, id);\n}\n\nexport function getModelSelectionStringOptionValue(\n  modelSelection: ModelSelection | null | undefined,\n  id: string,\n): string | undefined {\n  return getProviderOptionStringSelectionValue(modelSelection?.options, id);\n}\n\nexport function getModelSelectionBooleanOptionValue(\n  modelSelection: ModelSelection | null | undefined,\n  id: string,\n): boolean | undefined {\n  return getProviderOptionBooleanSelectionValue(modelSelection?.options, id);\n}\n\nfunction resolveDescriptorChoiceValue(\n  descriptor: Extract<ProviderOptionDescriptor, { type: \"select\" }>,\n  raw: string | null | undefined,\n): string | undefined {\n  const trimmed = trimOrNull(raw);\n  if (!trimmed) {\n    return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;\n  }\n  if (descriptor.options.length === 0) {\n    return trimmed;\n  }\n  if (\n    descriptor.promptInjectedValues?.includes(trimmed) &&\n    descriptor.options.some((option) => option.id === trimmed)\n  ) {\n    return descriptor.options.find((option) => option.isDefault)?.id;\n  }\n  if (descriptor.options.some((option) => option.id === trimmed)) {\n    return trimmed;\n  }\n  return descriptor.currentValue ?? descriptor.options.find((option) => option.isDefault)?.id;\n}\n\nfunction cloneDescriptor(descriptor: ProviderOptionDescriptor): ProviderOptionDescriptor {\n  return descriptor.type === \"select\"\n    ? {\n        ...descriptor,\n        options: [...descriptor.options],\n        ...(descriptor.promptInjectedValues\n          ? { promptInjectedValues: [...descriptor.promptInjectedValues] }\n          : {}),\n      }\n    : { ...descriptor };\n}\n\nfunction cloneSelection(selection: ProviderOptionSelection): ProviderOptionSelection {\n  return { ...selection };\n}\n\nfunction withDescriptorCurrentValue(\n  descriptor: ProviderOptionDescriptor,\n  rawCurrentValue: string | boolean | undefined,\n): ProviderOptionDescriptor {\n  if (descriptor.type === \"boolean\") {\n    if (typeof rawCurrentValue === \"boolean\") {\n      return {\n        ...descriptor,\n        currentValue: rawCurrentValue,\n      };\n    }\n    return descriptor;\n  }\n  const currentValue =\n    typeof rawCurrentValue === \"string\"\n      ? resolveDescriptorChoiceValue(descriptor, rawCurrentValue)\n      : resolveDescriptorChoiceValue(descriptor, descriptor.currentValue);\n  if (!currentValue) {\n    const { currentValue: _unusedCurrentValue, ...rest } = descriptor;\n    return rest;\n  }\n  return {\n    ...descriptor,\n    currentValue,\n  };\n}\n\nexport function getProviderOptionDescriptors(input: {\n  caps: ModelCapabilities;\n  selections?: ReadonlyArray<ProviderOptionSelection> | null | undefined;\n}): ReadonlyArray<ProviderOptionDescriptor> {\n  const { caps, selections } = input;\n  const baseDescriptors = (caps.optionDescriptors ?? []).map(cloneDescriptor);\n\n  return baseDescriptors.map((descriptor) =>\n    withDescriptorCurrentValue(\n      descriptor,\n      getRawSelectionValueById(selections, descriptor.id) ?? descriptor.currentValue,\n    ),\n  );\n}\n\nexport function getProviderOptionCurrentValue(\n  descriptor: ProviderOptionDescriptor | null | undefined,\n): string | boolean | undefined {\n  if (!descriptor) {\n    return undefined;\n  }\n  if (descriptor.type === \"boolean\") {\n    return descriptor.currentValue;\n  }\n  if (descriptor.currentValue) {\n    return descriptor.currentValue;\n  }\n  return descriptor.options.find((option) => option.isDefault)?.id;\n}\n\nexport function getProviderOptionCurrentLabel(\n  descriptor: ProviderOptionDescriptor | null | undefined,\n): string | undefined {\n  if (!descriptor) {\n    return undefined;\n  }\n  if (descriptor.type === \"boolean\") {\n    return typeof descriptor.currentValue === \"boolean\"\n      ? descriptor.currentValue\n        ? \"On\"\n        : \"Off\"\n      : undefined;\n  }\n  const currentValue = getProviderOptionCurrentValue(descriptor);\n  if (typeof currentValue !== \"string\") {\n    return undefined;\n  }\n  return descriptor.options.find((option) => option.id === currentValue)?.label;\n}\n\nexport function buildProviderOptionSelectionsFromDescriptors(\n  descriptors: ReadonlyArray<ProviderOptionDescriptor> | null | undefined,\n): Array<ProviderOptionSelection> | undefined {\n  if (!descriptors || descriptors.length === 0) {\n    return undefined;\n  }\n\n  const nextSelections: Array<ProviderOptionSelection> = [];\n\n  for (const descriptor of descriptors) {\n    const value = getProviderOptionCurrentValue(descriptor);\n    if (typeof value === \"string\" || typeof value === \"boolean\") {\n      nextSelections.push({ id: descriptor.id, value });\n    }\n  }\n\n  return nextSelections.length > 0 ? nextSelections : undefined;\n}\n\nexport function getModelSelectionOptionDescriptors(\n  modelSelection: ModelSelection | null | undefined,\n  caps?: ModelCapabilities | null | undefined,\n): ReadonlyArray<ProviderOptionDescriptor> {\n  if (!modelSelection) {\n    return [];\n  }\n  if (!caps) {\n    return [];\n  }\n  return getProviderOptionDescriptors({\n    caps,\n    selections: modelSelection.options,\n  });\n}\n\nexport function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {\n  return typeof text === \"string\" && /\\bultrathink\\b/i.test(text);\n}\n\nexport function normalizeModelSlug(\n  model: string | null | undefined,\n  provider: ProviderDriverKind = DEFAULT_PROVIDER_DRIVER_KIND,\n): string | null {\n  const trimmed = normalizeCustomModelSlug(model);\n  if (!trimmed) {\n    return null;\n  }\n\n  const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] ?? {};\n  const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed)\n    ? aliases[trimmed]\n    : undefined;\n  return typeof aliased === \"string\" ? aliased : trimmed;\n}\n\n/** Custom model identifiers are provider-owned, so only trim them; never expand aliases. */\nexport function normalizeCustomModelSlug(model: string | null | undefined): string | null {\n  if (typeof model !== \"string\") {\n    return null;\n  }\n\n  return model.trim() || null;\n}\n\nexport function resolveSelectableModel(\n  provider: ProviderDriverKind,\n  value: string | null | undefined,\n  options: ReadonlyArray<SelectableModelOption>,\n): string | null {\n  if (typeof value !== \"string\") {\n    return null;\n  }\n\n  const trimmed = value.trim();\n  if (!trimmed) {\n    return null;\n  }\n\n  const direct = options.find((option) => option.slug === trimmed);\n  if (direct) {\n    return direct.slug;\n  }\n\n  const byName = options.find((option) => option.name.toLowerCase() === trimmed.toLowerCase());\n  if (byName) {\n    return byName.slug;\n  }\n\n  const normalized = normalizeModelSlug(trimmed, provider);\n  if (!normalized) {\n    return null;\n  }\n\n  const resolved = options.find((option) => option.slug === normalized);\n  return resolved ? resolved.slug : null;\n}\n\nfunction resolveModelSlug(model: string | null | undefined, provider: ProviderDriverKind): string {\n  const normalized = normalizeModelSlug(model, provider);\n  if (!normalized) {\n    return DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;\n  }\n  return normalized;\n}\n\nexport function resolveModelSlugForProvider(\n  provider: ProviderDriverKind,\n  model: string | null | undefined,\n): string {\n  return resolveModelSlug(model, provider);\n}\n\n/** Trim a string, returning null for empty/missing values. */\nexport function trimOrNull<T extends string>(value: T | null | undefined): T | null {\n  if (typeof value !== \"string\") return null;\n  const trimmed = value.trim() as T;\n  return trimmed || null;\n}\n\nfunction cloneSelections(\n  selections: ReadonlyArray<ProviderOptionSelection>,\n): Array<ProviderOptionSelection> {\n  return selections.map(cloneSelection);\n}\n\nexport function createModelSelection(\n  instanceId: ProviderInstanceId,\n  model: string,\n  options?: ReadonlyArray<ProviderOptionSelection> | null,\n): ModelSelection {\n  const selections = options ? cloneSelections(options) : [];\n  const base: ModelSelection = {\n    instanceId,\n    model,\n  };\n  return selections.length > 0 ? { ...base, options: selections } : base;\n}\n\n/**\n * Returns the effort value if it is a prompt-injected value according to\n * any select descriptor in the given capabilities, or null otherwise.\n *\n * Unlike a single `find`, this checks every descriptor so that the\n * correct descriptor's `promptInjectedValues` list is consulted even when\n * multiple select descriptors exist.\n */\nexport function resolvePromptInjectedEffort(\n  caps: ModelCapabilities,\n  rawEffort: string | null | undefined,\n): string | null {\n  const trimmed = trimOrNull(rawEffort);\n  if (!trimmed) return null;\n  const descriptors = getProviderOptionDescriptors({ caps });\n  for (const descriptor of descriptors) {\n    if (descriptor.type === \"select\" && descriptor.promptInjectedValues?.includes(trimmed)) {\n      return trimmed;\n    }\n  }\n  return null;\n}\n\nexport function applyClaudePromptEffortPrefix(\n  text: string,\n  effort: string | null | undefined,\n): string {\n  const trimmed = text.trim();\n  if (!trimmed) {\n    return trimmed;\n  }\n  if (effort !== \"ultrathink\") {\n    return trimmed;\n  }\n  if (trimmed.startsWith(\"Ultrathink:\")) {\n    return trimmed;\n  }\n  return `Ultrathink:\\n${trimmed}`;\n}\n","import {\n  type BackgroundActivityProfile,\n  type BackgroundActivitySettings,\n  DEFAULT_BACKGROUND_ACTIVITY_PROFILE,\n  DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,\n  DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,\n  type ServerSettings,\n} from \"@t3tools/contracts\";\nimport * as Duration from \"effect/Duration\";\n\nexport interface ResolvedBackgroundActivitySettings {\n  readonly profile: BackgroundActivityProfile;\n  readonly automaticGitFetchInterval: Duration.Duration;\n  readonly providerHealthRefreshInterval: Duration.Duration;\n  readonly hostPowerMonitorActiveInterval: Duration.Duration;\n  readonly hostPowerMonitorIdleInterval: Duration.Duration;\n  readonly idleClientTtl: Duration.Duration;\n  readonly pauseWhenHostLocked: boolean;\n  readonly pauseWhenHostLowPower: boolean;\n  readonly pauseWhenClientLowPower: boolean;\n  readonly pauseWhenOnBattery: boolean;\n}\n\nconst PRESET_SETTINGS: Record<BackgroundActivityProfile, ResolvedBackgroundActivitySettings> = {\n  performance: {\n    profile: \"performance\",\n    automaticGitFetchInterval: Duration.seconds(15),\n    providerHealthRefreshInterval: Duration.minutes(1),\n    hostPowerMonitorActiveInterval: Duration.seconds(30),\n    hostPowerMonitorIdleInterval: Duration.minutes(2),\n    idleClientTtl: Duration.seconds(45),\n    pauseWhenHostLocked: true,\n    pauseWhenHostLowPower: false,\n    pauseWhenClientLowPower: false,\n    pauseWhenOnBattery: false,\n  },\n  balanced: {\n    profile: \"balanced\",\n    automaticGitFetchInterval: DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,\n    providerHealthRefreshInterval: DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,\n    hostPowerMonitorActiveInterval: Duration.seconds(30),\n    hostPowerMonitorIdleInterval: Duration.minutes(5),\n    idleClientTtl: Duration.seconds(45),\n    pauseWhenHostLocked: true,\n    pauseWhenHostLowPower: true,\n    pauseWhenClientLowPower: true,\n    pauseWhenOnBattery: false,\n  },\n  \"battery-saver\": {\n    profile: \"battery-saver\",\n    automaticGitFetchInterval: Duration.seconds(0),\n    providerHealthRefreshInterval: Duration.minutes(15),\n    hostPowerMonitorActiveInterval: Duration.minutes(1),\n    hostPowerMonitorIdleInterval: Duration.minutes(10),\n    idleClientTtl: Duration.seconds(45),\n    pauseWhenHostLocked: true,\n    pauseWhenHostLowPower: true,\n    pauseWhenClientLowPower: true,\n    pauseWhenOnBattery: true,\n  },\n};\n\nexport function getBackgroundActivityPresetSettings(\n  profile: BackgroundActivityProfile,\n): ResolvedBackgroundActivitySettings {\n  return PRESET_SETTINGS[profile];\n}\n\nexport function getBackgroundActivityBaseProfile(\n  backgroundActivity: BackgroundActivitySettings,\n): BackgroundActivityProfile {\n  if (backgroundActivity.profile === \"custom\") {\n    return backgroundActivity.baseProfile ?? DEFAULT_BACKGROUND_ACTIVITY_PROFILE;\n  }\n  return backgroundActivity.profile;\n}\n\nexport function resolveBackgroundActivitySettings(\n  backgroundActivity: BackgroundActivitySettings,\n): ResolvedBackgroundActivitySettings {\n  const baseProfile = getBackgroundActivityBaseProfile(backgroundActivity);\n  const preset = PRESET_SETTINGS[baseProfile];\n  const overrides = backgroundActivity.profile === \"custom\" ? backgroundActivity.overrides : {};\n  return {\n    profile: baseProfile,\n    automaticGitFetchInterval:\n      overrides.automaticGitFetchInterval ?? preset.automaticGitFetchInterval,\n    providerHealthRefreshInterval:\n      overrides.providerHealthRefreshInterval ?? preset.providerHealthRefreshInterval,\n    hostPowerMonitorActiveInterval:\n      overrides.hostPowerMonitorActiveInterval ?? preset.hostPowerMonitorActiveInterval,\n    hostPowerMonitorIdleInterval:\n      overrides.hostPowerMonitorIdleInterval ?? preset.hostPowerMonitorIdleInterval,\n    idleClientTtl: overrides.idleClientTtl ?? preset.idleClientTtl,\n    pauseWhenHostLocked: overrides.pauseWhenHostLocked ?? preset.pauseWhenHostLocked,\n    pauseWhenHostLowPower: overrides.pauseWhenHostLowPower ?? preset.pauseWhenHostLowPower,\n    pauseWhenClientLowPower: overrides.pauseWhenClientLowPower ?? preset.pauseWhenClientLowPower,\n    pauseWhenOnBattery: overrides.pauseWhenOnBattery ?? preset.pauseWhenOnBattery,\n  };\n}\n\nfunction durationsEqual(a: Duration.Duration, b: Duration.Duration): boolean {\n  return Duration.toMillis(a) === Duration.toMillis(b);\n}\n\nfunction resolvedSettingsEqual(\n  a: ResolvedBackgroundActivitySettings,\n  b: ResolvedBackgroundActivitySettings,\n): boolean {\n  return (\n    durationsEqual(a.automaticGitFetchInterval, b.automaticGitFetchInterval) &&\n    durationsEqual(a.providerHealthRefreshInterval, b.providerHealthRefreshInterval) &&\n    durationsEqual(a.hostPowerMonitorActiveInterval, b.hostPowerMonitorActiveInterval) &&\n    durationsEqual(a.hostPowerMonitorIdleInterval, b.hostPowerMonitorIdleInterval) &&\n    durationsEqual(a.idleClientTtl, b.idleClientTtl) &&\n    a.pauseWhenHostLocked === b.pauseWhenHostLocked &&\n    a.pauseWhenHostLowPower === b.pauseWhenHostLowPower &&\n    a.pauseWhenClientLowPower === b.pauseWhenClientLowPower &&\n    a.pauseWhenOnBattery === b.pauseWhenOnBattery\n  );\n}\n\nexport function normalizeBackgroundActivitySettings(\n  backgroundActivity: BackgroundActivitySettings,\n): BackgroundActivitySettings {\n  if (backgroundActivity.profile !== \"custom\") {\n    return {\n      schemaVersion: 1,\n      profile: backgroundActivity.profile,\n      overrides: {},\n    };\n  }\n\n  const resolved = resolveBackgroundActivitySettings(backgroundActivity);\n  const profiles: ReadonlyArray<BackgroundActivityProfile> = [\n    getBackgroundActivityBaseProfile(backgroundActivity),\n    \"balanced\",\n    \"performance\",\n    \"battery-saver\",\n  ];\n  for (const profile of profiles) {\n    if (resolvedSettingsEqual(resolved, PRESET_SETTINGS[profile])) {\n      return {\n        schemaVersion: 1,\n        profile,\n        overrides: {},\n      };\n    }\n  }\n\n  const baseProfile = getBackgroundActivityBaseProfile(backgroundActivity);\n  const preset = PRESET_SETTINGS[baseProfile];\n  const overrides: BackgroundActivitySettings[\"overrides\"] = {\n    ...(!durationsEqual(resolved.automaticGitFetchInterval, preset.automaticGitFetchInterval)\n      ? { automaticGitFetchInterval: resolved.automaticGitFetchInterval }\n      : {}),\n    ...(!durationsEqual(\n      resolved.providerHealthRefreshInterval,\n      preset.providerHealthRefreshInterval,\n    )\n      ? { providerHealthRefreshInterval: resolved.providerHealthRefreshInterval }\n      : {}),\n    ...(!durationsEqual(\n      resolved.hostPowerMonitorActiveInterval,\n      preset.hostPowerMonitorActiveInterval,\n    )\n      ? { hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval }\n      : {}),\n    ...(!durationsEqual(resolved.hostPowerMonitorIdleInterval, preset.hostPowerMonitorIdleInterval)\n      ? { hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval }\n      : {}),\n    ...(!durationsEqual(resolved.idleClientTtl, preset.idleClientTtl)\n      ? { idleClientTtl: resolved.idleClientTtl }\n      : {}),\n    ...(resolved.pauseWhenHostLocked !== preset.pauseWhenHostLocked\n      ? { pauseWhenHostLocked: resolved.pauseWhenHostLocked }\n      : {}),\n    ...(resolved.pauseWhenHostLowPower !== preset.pauseWhenHostLowPower\n      ? { pauseWhenHostLowPower: resolved.pauseWhenHostLowPower }\n      : {}),\n    ...(resolved.pauseWhenClientLowPower !== preset.pauseWhenClientLowPower\n      ? { pauseWhenClientLowPower: resolved.pauseWhenClientLowPower }\n      : {}),\n    ...(resolved.pauseWhenOnBattery !== preset.pauseWhenOnBattery\n      ? { pauseWhenOnBattery: resolved.pauseWhenOnBattery }\n      : {}),\n  };\n\n  return {\n    schemaVersion: 1,\n    profile: \"custom\",\n    baseProfile,\n    overrides,\n  };\n}\n\nexport function resolveServerBackgroundActivitySettings(\n  settings: ServerSettings,\n): ResolvedBackgroundActivitySettings {\n  const defaultBackgroundActivity: BackgroundActivitySettings = {\n    schemaVersion: 1,\n    profile: DEFAULT_BACKGROUND_ACTIVITY_PROFILE,\n    overrides: {},\n  };\n  const backgroundActivityIsDefault =\n    settings.backgroundActivity.profile === defaultBackgroundActivity.profile &&\n    settings.backgroundActivity.baseProfile === undefined &&\n    Object.keys(settings.backgroundActivity.overrides).length === 0;\n  const legacyProfile = settings.backgroundActivityProfile;\n  const hasLegacyOverrides =\n    legacyProfile !== DEFAULT_BACKGROUND_ACTIVITY_PROFILE ||\n    Duration.toMillis(settings.automaticGitFetchInterval) !==\n      Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) ||\n    Duration.toMillis(settings.providerHealthRefreshInterval) !==\n      Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL);\n  if (backgroundActivityIsDefault && hasLegacyOverrides) {\n    return resolveBackgroundActivitySettings({\n      schemaVersion: 1,\n      profile:\n        Duration.toMillis(settings.automaticGitFetchInterval) ===\n          Duration.toMillis(\n            getBackgroundActivityPresetSettings(legacyProfile).automaticGitFetchInterval,\n          ) &&\n        Duration.toMillis(settings.providerHealthRefreshInterval) ===\n          Duration.toMillis(\n            getBackgroundActivityPresetSettings(legacyProfile).providerHealthRefreshInterval,\n          )\n          ? legacyProfile\n          : \"custom\",\n      baseProfile: legacyProfile,\n      overrides: {\n        ...(Duration.toMillis(settings.automaticGitFetchInterval) !==\n        Duration.toMillis(\n          getBackgroundActivityPresetSettings(legacyProfile).automaticGitFetchInterval,\n        )\n          ? { automaticGitFetchInterval: settings.automaticGitFetchInterval }\n          : {}),\n        ...(Duration.toMillis(settings.providerHealthRefreshInterval) !==\n        Duration.toMillis(\n          getBackgroundActivityPresetSettings(legacyProfile).providerHealthRefreshInterval,\n        )\n          ? { providerHealthRefreshInterval: settings.providerHealthRefreshInterval }\n          : {}),\n      },\n    });\n  }\n  return resolveBackgroundActivitySettings(settings.backgroundActivity);\n}\n\nexport function normalizeServerBackgroundActivitySettings(\n  settings: ServerSettings,\n): BackgroundActivitySettings {\n  const resolved = resolveServerBackgroundActivitySettings(settings);\n  return normalizeBackgroundActivitySettings({\n    schemaVersion: 1,\n    profile: \"custom\",\n    baseProfile: resolved.profile,\n    overrides: {\n      automaticGitFetchInterval: resolved.automaticGitFetchInterval,\n      providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,\n      hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,\n      hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,\n      idleClientTtl: resolved.idleClientTtl,\n      pauseWhenHostLocked: resolved.pauseWhenHostLocked,\n      pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,\n      pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,\n      pauseWhenOnBattery: resolved.pauseWhenOnBattery,\n    },\n  });\n}\n","import {\n  isProviderDriverKind,\n  isProviderAvailable,\n  type ModelSelection,\n  type ProviderDriverKind,\n  type ServerProvider,\n  ServerSettings,\n  type ServerSettingsPatch,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { deepMerge } from \"./Struct.ts\";\nimport { fromLenientJson } from \"./schemaJson.ts\";\nimport { createModelSelection } from \"./model.ts\";\nimport {\n  getBackgroundActivityBaseProfile,\n  normalizeBackgroundActivitySettings,\n  normalizeServerBackgroundActivitySettings,\n  resolveBackgroundActivitySettings,\n} from \"./backgroundActivitySettings.ts\";\n\nconst ServerSettingsJson = fromLenientJson(ServerSettings);\nconst decodeServerSettingsJson = Schema.decodeUnknownOption(ServerSettingsJson);\n\ntype LegacyProviderSettings = ServerSettings[\"providers\"][keyof ServerSettings[\"providers\"]];\n\nconst getLegacyProviderSettings = (\n  settings: ServerSettings,\n  provider: ProviderDriverKind,\n): LegacyProviderSettings | undefined =>\n  (settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];\n\nexport function isModelSelectionProviderEnabled(\n  settings: ServerSettings,\n  selection: ModelSelection,\n): boolean {\n  const instanceConfig = settings.providerInstances[selection.instanceId];\n  if (instanceConfig !== undefined) {\n    return instanceConfig.enabled ?? true;\n  }\n\n  return (\n    isProviderDriverKind(selection.instanceId) &&\n    getLegacyProviderSettings(settings, selection.instanceId)?.enabled === true\n  );\n}\n\nexport function resolveSourceControlWriterModelSelection(\n  settings: ServerSettings,\n  providers?: ReadonlyArray<ServerProvider>,\n): ModelSelection {\n  const selection = settings.sourceControlWriterModelSelection;\n  if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {\n    return settings.textGenerationModelSelection;\n  }\n  if (providers === undefined) {\n    return selection;\n  }\n\n  const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);\n  return provider?.enabled === true && isProviderAvailable(provider)\n    ? selection\n    : settings.textGenerationModelSelection;\n}\n\nexport interface PersistedServerObservabilitySettings {\n  readonly otlpTracesUrl: string | undefined;\n  readonly otlpMetricsUrl: string | undefined;\n}\n\nexport function normalizePersistedServerSettingString(\n  value: string | null | undefined,\n): string | undefined {\n  const trimmed = value?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function extractPersistedServerObservabilitySettings(input: {\n  readonly observability?: {\n    readonly otlpTracesUrl?: string;\n    readonly otlpMetricsUrl?: string;\n  };\n}): PersistedServerObservabilitySettings {\n  return {\n    otlpTracesUrl: normalizePersistedServerSettingString(input.observability?.otlpTracesUrl),\n    otlpMetricsUrl: normalizePersistedServerSettingString(input.observability?.otlpMetricsUrl),\n  };\n}\n\nexport function parsePersistedServerObservabilitySettings(\n  raw: string,\n): PersistedServerObservabilitySettings {\n  const decoded = decodeServerSettingsJson(raw);\n  if (Option.isSome(decoded)) {\n    return extractPersistedServerObservabilitySettings(decoded.value);\n  }\n  return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };\n}\n\nfunction shouldReplaceTextGenerationModelSelection(\n  patch: ServerSettingsPatch[\"textGenerationModelSelection\"] | undefined,\n): boolean {\n  return Boolean(patch && (patch.instanceId !== undefined || patch.model !== undefined));\n}\n\nfunction mergeModelSelectionOptionsById(input: {\n  current: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;\n  patch: ReadonlyArray<{ readonly id: string; readonly value: string | boolean }> | undefined;\n}): Array<{ id: string; value: string | boolean }> | undefined {\n  if (input.patch === undefined) {\n    return input.current ? [...input.current] : undefined;\n  }\n  if (input.patch.length === 0) {\n    return undefined;\n  }\n\n  const merged = new Map((input.current ?? []).map((selection) => [selection.id, selection.value]));\n  for (const selection of input.patch) {\n    merged.set(selection.id, selection.value);\n  }\n  return [...merged.entries()].map(([id, value]) => ({ id, value }));\n}\n\nexport function applyServerSettingsPatch(\n  current: ServerSettings,\n  patch: ServerSettingsPatch,\n): ServerSettings {\n  const selectionPatch = patch.textGenerationModelSelection;\n  const {\n    automaticGitFetchInterval,\n    providerHealthRefreshInterval,\n    backgroundActivityProfile,\n    backgroundActivity,\n    ...patchForMerge\n  } = patch;\n  const currentBackgroundActivity = normalizeServerBackgroundActivitySettings(current);\n  const backgroundActivityPatch =\n    backgroundActivityProfile !== undefined\n      ? {\n          schemaVersion: 1 as const,\n          profile:\n            automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined\n              ? (\"custom\" as const)\n              : backgroundActivityProfile,\n          ...(automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined\n            ? { baseProfile: backgroundActivityProfile }\n            : {}),\n          overrides: {\n            ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),\n            ...(providerHealthRefreshInterval !== undefined\n              ? { providerHealthRefreshInterval }\n              : {}),\n          },\n        }\n      : automaticGitFetchInterval !== undefined || providerHealthRefreshInterval !== undefined\n        ? {\n            schemaVersion: 1 as const,\n            profile: \"custom\" as const,\n            baseProfile: getBackgroundActivityBaseProfile(currentBackgroundActivity),\n            overrides: {\n              ...(currentBackgroundActivity.profile === \"custom\"\n                ? currentBackgroundActivity.overrides\n                : {}),\n              ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),\n              ...(providerHealthRefreshInterval !== undefined\n                ? { providerHealthRefreshInterval }\n                : {}),\n            },\n          }\n        : undefined;\n  const next = deepMerge(current, patchForMerge);\n  const nextWithReplacementsBase = {\n    ...next,\n    ...(backgroundActivity !== undefined\n      ? {\n          backgroundActivity: {\n            ...deepMerge(currentBackgroundActivity, backgroundActivity),\n            ...(backgroundActivity.overrides !== undefined\n              ? { overrides: backgroundActivity.overrides }\n              : {}),\n          },\n        }\n      : { backgroundActivity: currentBackgroundActivity }),\n    ...(backgroundActivity === undefined && backgroundActivityPatch !== undefined\n      ? { backgroundActivity: backgroundActivityPatch }\n      : {}),\n    ...(patch.providerInstances !== undefined\n      ? { providerInstances: patch.providerInstances }\n      : {}),\n    ...(patch.sourceControlWriterModelSelection !== undefined\n      ? { sourceControlWriterModelSelection: patch.sourceControlWriterModelSelection }\n      : {}),\n    ...(automaticGitFetchInterval !== undefined ? { automaticGitFetchInterval } : {}),\n    ...(providerHealthRefreshInterval !== undefined ? { providerHealthRefreshInterval } : {}),\n  };\n  const normalizedBackgroundActivity = normalizeBackgroundActivitySettings(\n    nextWithReplacementsBase.backgroundActivity,\n  );\n  const resolvedBackgroundActivity = resolveBackgroundActivitySettings(\n    normalizedBackgroundActivity,\n  );\n  const nextWithReplacements = {\n    ...nextWithReplacementsBase,\n    backgroundActivity: normalizedBackgroundActivity,\n    automaticGitFetchInterval: resolvedBackgroundActivity.automaticGitFetchInterval,\n    providerHealthRefreshInterval: resolvedBackgroundActivity.providerHealthRefreshInterval,\n    backgroundActivityProfile: resolvedBackgroundActivity.profile,\n  };\n  if (!selectionPatch) {\n    return nextWithReplacements;\n  }\n\n  const instanceId = selectionPatch.instanceId ?? current.textGenerationModelSelection.instanceId;\n  const model = selectionPatch.model ?? current.textGenerationModelSelection.model;\n  const options = shouldReplaceTextGenerationModelSelection(selectionPatch)\n    ? selectionPatch.options\n    : mergeModelSelectionOptionsById({\n        current: current.textGenerationModelSelection.options,\n        patch: selectionPatch.options,\n      });\n\n  return {\n    ...nextWithReplacements,\n    textGenerationModelSelection: createModelSelection(instanceId, model, options),\n  };\n}\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFS from \"node:fs\";\nimport * as NodeNet from \"node:net\";\nimport * as NodeReadline from \"node:readline\";\nimport type * as NodeStream from \"node:stream\";\n\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { decodeJsonResult } from \"@t3tools/shared/schemaJson\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\n\nexport class BootstrapFdStatError extends Schema.TaggedErrorClass<BootstrapFdStatError>()(\n  \"BootstrapFdStatError\",\n  {\n    fd: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to stat bootstrap file descriptor ${this.fd}.`;\n  }\n}\n\nexport class BootstrapInputStreamOpenError extends Schema.TaggedErrorClass<BootstrapInputStreamOpenError>()(\n  \"BootstrapInputStreamOpenError\",\n  {\n    fd: Schema.Number,\n    platform: Schema.String,\n    fdPath: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    const path = this.fdPath === undefined ? \"\" : ` via '${this.fdPath}'`;\n    return `Failed to open bootstrap input stream for file descriptor ${this.fd}${path} on '${this.platform}'.`;\n  }\n}\n\nexport class BootstrapEnvelopeReadError extends Schema.TaggedErrorClass<BootstrapEnvelopeReadError>()(\n  \"BootstrapEnvelopeReadError\",\n  {\n    fd: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to read bootstrap envelope from file descriptor ${this.fd}.`;\n  }\n}\n\nexport class BootstrapEnvelopeDecodeError extends Schema.TaggedErrorClass<BootstrapEnvelopeDecodeError>()(\n  \"BootstrapEnvelopeDecodeError\",\n  {\n    fd: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to decode bootstrap envelope from file descriptor ${this.fd}.`;\n  }\n}\n\nexport const BootstrapError = Schema.Union([\n  BootstrapFdStatError,\n  BootstrapInputStreamOpenError,\n  BootstrapEnvelopeReadError,\n  BootstrapEnvelopeDecodeError,\n]);\nexport type BootstrapError = typeof BootstrapError.Type;\n\nexport const readBootstrapEnvelope = Effect.fn(\"readBootstrapEnvelope\")(function* <A, I>(\n  schema: Schema.Codec<A, I>,\n  fd: number,\n  options?: {\n    timeoutMs?: number;\n  },\n): Effect.fn.Return<Option.Option<A>, BootstrapError> {\n  const fdReady = yield* isFdReady(fd);\n  if (!fdReady) return Option.none();\n\n  const stream = yield* makeBootstrapInputStream(fd);\n\n  const timeoutMs = options?.timeoutMs ?? 1000;\n\n  return yield* Effect.callback<\n    Option.Option<A>,\n    BootstrapEnvelopeReadError | BootstrapEnvelopeDecodeError\n  >((resume) => {\n    const input = NodeReadline.createInterface({\n      input: stream,\n      crlfDelay: Infinity,\n    });\n\n    const cleanup = () => {\n      stream.removeListener(\"error\", handleError);\n      input.removeListener(\"line\", handleLine);\n      input.removeListener(\"close\", handleClose);\n      input.close();\n      stream.destroy();\n    };\n\n    const handleError = (error: Error) => {\n      if (isUnavailableBootstrapFdError(error)) {\n        resume(Effect.succeedNone);\n        return;\n      }\n      resume(\n        Effect.fail(\n          new BootstrapEnvelopeReadError({\n            fd,\n            cause: error,\n          }),\n        ),\n      );\n    };\n\n    const handleLine = (line: string) => {\n      const parsed = decodeJsonResult(schema)(line);\n      if (Result.isSuccess(parsed)) {\n        resume(Effect.succeedSome(parsed.success));\n      } else {\n        resume(\n          Effect.fail(\n            new BootstrapEnvelopeDecodeError({\n              fd,\n              cause: parsed.failure,\n            }),\n          ),\n        );\n      }\n    };\n\n    const handleClose = () => {\n      resume(Effect.succeedNone);\n    };\n\n    stream.once(\"error\", handleError);\n    input.once(\"line\", handleLine);\n    input.once(\"close\", handleClose);\n\n    return Effect.sync(cleanup);\n  }).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));\n});\n\nconst isUnavailableBootstrapFdError = Predicate.compose(\n  Predicate.hasProperty(\"code\"),\n  (_) => _.code === \"EBADF\" || _.code === \"ENOENT\",\n);\n\nconst isFdReady = (fd: number) =>\n  Effect.try({\n    try: () => NodeFS.fstatSync(fd),\n    catch: (error) =>\n      new BootstrapFdStatError({\n        fd,\n        cause: error,\n      }),\n  }).pipe(\n    Effect.as(true),\n    Effect.catchTags({\n      BootstrapFdStatError: (error) =>\n        isUnavailableBootstrapFdError(error.cause) ? Effect.succeed(false) : Effect.fail(error),\n    }),\n  );\n\nconst makeBootstrapInputStream = (fd: number) =>\n  Effect.gen(function* () {\n    const platform = yield* HostProcessPlatform;\n    const fdPath = resolveFdPath(fd, platform);\n    return yield* Effect.try<NodeStream.Readable, BootstrapInputStreamOpenError>({\n      try: () => {\n        if (fdPath === undefined) {\n          return makeDirectBootstrapStream(fd);\n        }\n\n        let streamFd: number | undefined;\n        try {\n          streamFd = NodeFS.openSync(fdPath, \"r\");\n          return NodeFS.createReadStream(\"\", {\n            fd: streamFd,\n            encoding: \"utf8\",\n            autoClose: true,\n          });\n        } catch (error) {\n          if (isBootstrapFdPathDuplicationError(error)) {\n            if (streamFd !== undefined) {\n              NodeFS.closeSync(streamFd);\n            }\n            return makeDirectBootstrapStream(fd);\n          }\n          throw error;\n        }\n      },\n      catch: (error) =>\n        new BootstrapInputStreamOpenError({\n          fd,\n          platform,\n          ...(fdPath === undefined ? {} : { fdPath }),\n          cause: error,\n        }),\n    });\n  });\n\nconst makeDirectBootstrapStream = (fd: number): NodeStream.Readable => {\n  try {\n    return NodeFS.createReadStream(\"\", {\n      fd,\n      encoding: \"utf8\",\n      autoClose: true,\n    });\n  } catch {\n    const stream = new NodeNet.Socket({\n      fd,\n      readable: true,\n      writable: false,\n    });\n    stream.setEncoding(\"utf8\");\n    return stream;\n  }\n};\n\n// Stdin pipes inherited across the wsl.exe boundary report EACCES when we try\n// to re-open them via /proc/self/fd/0 — fall back to reading the fd directly\n// in that case, the same way we already do for ENXIO/EINVAL/EPERM.\nconst isBootstrapFdPathDuplicationError = Predicate.compose(\n  Predicate.hasProperty(\"code\"),\n  (_) => _.code === \"ENXIO\" || _.code === \"EINVAL\" || _.code === \"EPERM\" || _.code === \"EACCES\",\n);\n\nfunction resolveFdPath(fd: number, platform: NodeJS.Platform): string | undefined {\n  if (platform === \"linux\") {\n    return `/proc/self/fd/${fd}`;\n  }\n  if (platform === \"win32\") {\n    return undefined;\n  }\n  return `/dev/fd/${fd}`;\n}\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeOS from \"node:os\";\nimport * as NodePath from \"node:path\";\nimport * as NodeChildProcess from \"node:child_process\";\nimport * as NodeFS from \"node:fs\";\nimport * as Clock from \"effect/Clock\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\n\nimport { HostProcessEnvironment, HostProcessPlatform } from \"./hostProcess.ts\";\nimport * as Context from \"effect/Context\";\n\nconst PATH_CAPTURE_START = \"__SYNAPTIC_PATH_START__\";\nconst PATH_CAPTURE_END = \"__SYNAPTIC_PATH_END__\";\nconst SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/;\nconst WINDOWS_PATH_DELIMITER = \";\";\nconst POSIX_PATH_DELIMITER = \":\";\nconst WINDOWS_SHELL_CANDIDATES = [\"pwsh.exe\", \"powershell.exe\"] as const;\n\ntype ExecFileSyncLike = (\n  file: string,\n  args: ReadonlyArray<string>,\n  options: { encoding: \"utf8\"; timeout: number },\n) => string;\n\nfunction canExecuteFile(filePath: string): boolean {\n  try {\n    NodeFS.accessSync(filePath, NodeFS.constants.X_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport interface CommandAvailabilityOptions {\n  readonly env?: NodeJS.ProcessEnv;\n  readonly extendEnv?: boolean;\n}\n\nexport type CommandAvailabilityChecker = (\n  command: string,\n  options?: CommandAvailabilityOptions,\n) => Effect.Effect<boolean, never, FileSystem.FileSystem | Path.Path>;\n\nexport class CommandResolutionError extends Data.TaggedError(\"CommandResolutionError\")<{\n  readonly command: string;\n  readonly reason: \"not-found\";\n}> {}\n\nconst WINDOWS_SHELL_META_CHARS = /([()\\][%!^\"`<>&|;, *?])/g;\n\n/**\n * Escapes a single argument for `cmd.exe` shell mode (`spawn(..., { shell: true })`\n * on Windows). Node joins the command and arguments with spaces and hands the\n * resulting string to `cmd.exe` without any quoting, so every dynamic argument\n * must be escaped to survive both cmd.exe parsing and the target program's\n * `CommandLineToArgvW` parsing. Mirrors cross-spawn's argument escaping.\n */\nfunction escapeWindowsShellArg(arg: string): string {\n  // Double up backslashes that precede a double quote, then escape the quote\n  // itself so it survives CommandLineToArgvW.\n  let escaped = arg.replace(/(\\\\*)\"/g, '$1$1\\\\\"');\n  // Double up trailing backslashes so the closing quote is not escaped away.\n  escaped = escaped.replace(/(\\\\*)$/, \"$1$1\");\n  // Quote the whole argument so embedded whitespace is preserved.\n  escaped = `\"${escaped}\"`;\n  // Escape cmd.exe metacharacters so cmd passes them through verbatim.\n  return escaped.replace(WINDOWS_SHELL_META_CHARS, \"^$1\");\n}\n\n/**\n * Escapes arguments for shell-mode spawns: applies {@link escapeWindowsShellArg}\n * when the platform is `win32` (where `shell: true` routes through `cmd.exe`)\n * and returns the arguments untouched everywhere else.\n */\nfunction sanitizeShellModeArgsForPlatform(\n  args: ReadonlyArray<string>,\n  platform: NodeJS.Platform,\n): Array<string> {\n  return platform === \"win32\" ? args.map(escapeWindowsShellArg) : [...args];\n}\n\nexport interface ResolvedSpawnCommand {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly shell: boolean;\n}\n\nexport type SpawnExecutableResolver = (\n  command: string,\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv,\n) => string | undefined;\n\nfunction resolveSpawnExecutableWithNode(\n  command: string,\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv,\n): string | undefined {\n  const path = platform === \"win32\" ? NodePath.win32 : NodePath.posix;\n  const windowsPathExtensions = platform === \"win32\" ? resolveWindowsPathExtensions(env) : [];\n  const candidates = resolveCommandCandidates(\n    command,\n    platform,\n    windowsPathExtensions,\n    path.extname,\n  );\n  const isExecutable = (candidate: string) => {\n    try {\n      if (!NodeFS.statSync(candidate).isFile()) return false;\n      if (platform === \"win32\") {\n        return windowsPathExtensions.includes(path.extname(candidate).toUpperCase());\n      }\n      return canExecuteFile(candidate);\n    } catch {\n      return false;\n    }\n  };\n\n  if (command.includes(\"/\") || command.includes(\"\\\\\")) {\n    return candidates.find(isExecutable);\n  }\n\n  for (const pathEntry of (readEnvPath(env) ?? \"\").split(pathDelimiterForPlatform(platform))) {\n    const normalizedPathEntry = stripWrappingQuotes(pathEntry.trim());\n    if (normalizedPathEntry.length === 0) continue;\n    for (const candidate of candidates) {\n      const candidatePath = path.join(normalizedPathEntry, candidate);\n      if (isExecutable(candidatePath)) return candidatePath;\n    }\n  }\n  return undefined;\n}\n\nexport const SpawnExecutableResolution = Context.Reference<SpawnExecutableResolver>(\n  \"@t3tools/shared/shell/SpawnExecutableResolution\",\n  {\n    defaultValue: () => resolveSpawnExecutableWithNode,\n  },\n);\n\nexport interface WindowsEnvironmentProbeOptions {\n  readonly loadProfile?: boolean;\n}\n\nfunction trimNonEmpty(value: string | null | undefined): string | undefined {\n  const trimmed = value?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction readUserLoginShell(): string | undefined {\n  try {\n    return trimNonEmpty(NodeOS.userInfo().shell);\n  } catch {\n    return undefined;\n  }\n}\n\nexport function listLoginShellCandidates(\n  platform: NodeJS.Platform,\n  shell: string | undefined,\n  userShell = readUserLoginShell(),\n): ReadonlyArray<string> {\n  const fallbackShell =\n    platform === \"darwin\" ? \"/bin/zsh\" : platform === \"linux\" ? \"/bin/bash\" : undefined;\n  const seen = new Set<string>();\n  const candidates: string[] = [];\n\n  for (const candidate of [trimNonEmpty(shell), trimNonEmpty(userShell), fallbackShell]) {\n    if (!candidate || seen.has(candidate)) {\n      continue;\n    }\n    seen.add(candidate);\n    candidates.push(candidate);\n  }\n\n  return candidates;\n}\n\nexport function extractPathFromShellOutput(output: string): string | null {\n  const startIndex = output.indexOf(PATH_CAPTURE_START);\n  if (startIndex === -1) return null;\n\n  const valueStartIndex = startIndex + PATH_CAPTURE_START.length;\n  const endIndex = output.indexOf(PATH_CAPTURE_END, valueStartIndex);\n  if (endIndex === -1) return null;\n\n  const pathValue = output.slice(valueStartIndex, endIndex).trim();\n  return pathValue.length > 0 ? pathValue : null;\n}\n\nexport function readPathFromLoginShell(\n  shell: string,\n  execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,\n): string | undefined {\n  return readEnvironmentFromLoginShell(shell, [\"PATH\"], execFile).PATH;\n}\n\nexport function readPathFromLaunchctl(\n  execFile: ExecFileSyncLike = NodeChildProcess.execFileSync,\n): string | undefined {\n  try {\n    return trimNonEmpty(\n      execFile(\"/bin/launchctl\", [\"getenv\", \"PATH\"], {\n        encoding: \"utf8\",\n        timeout: 2000,\n      }),\n    );\n  } catch {\n    return undefined;\n  }\n}\n\nexport function mergePathEntries(\n  preferredPath: string | undefined,\n  inheritedPath: string | undefined,\n  platform: NodeJS.Platform,\n): string | undefined {\n  const delimiter = platform === \"win32\" ? \";\" : \":\";\n  const merged: string[] = [];\n  const seen = new Set<string>();\n\n  for (const pathValue of [preferredPath, inheritedPath]) {\n    if (!pathValue) continue;\n    for (const entry of pathValue.split(delimiter)) {\n      const trimmedEntry = entry.trim();\n      if (!trimmedEntry || seen.has(trimmedEntry)) {\n        continue;\n      }\n      seen.add(trimmedEntry);\n      merged.push(trimmedEntry);\n    }\n  }\n\n  return merged.length > 0 ? merged.join(delimiter) : undefined;\n}\n\nfunction envCaptureStart(name: string): string {\n  return `__SYNAPTIC_ENV_${name}_START__`;\n}\n\nfunction envCaptureEnd(name: string): string {\n  return `__SYNAPTIC_ENV_${name}_END__`;\n}\n\nfunction buildEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {\n  return names\n    .map((name) => {\n      if (!SHELL_ENV_NAME_PATTERN.test(name)) {\n        throw new Error(`Unsupported environment variable name: ${name}`);\n      }\n\n      return [\n        `printf '%s\\\\n' '${envCaptureStart(name)}'`,\n        `printenv ${name} || true`,\n        `printf '%s\\\\n' '${envCaptureEnd(name)}'`,\n      ].join(\"; \");\n    })\n    .join(\"; \");\n}\n\nfunction buildWindowsEnvironmentCaptureCommand(names: ReadonlyArray<string>): string {\n  return [\n    \"$ErrorActionPreference = 'Stop'\",\n    ...names.flatMap((name) => {\n      if (!SHELL_ENV_NAME_PATTERN.test(name)) {\n        throw new Error(`Unsupported environment variable name: ${name}`);\n      }\n\n      return [\n        `Write-Output '${envCaptureStart(name)}'`,\n        `$value = [Environment]::GetEnvironmentVariable('${name}')`,\n        \"if ($null -ne $value -and $value.Length -gt 0) { Write-Output $value }\",\n        `Write-Output '${envCaptureEnd(name)}'`,\n      ];\n    }),\n  ].join(\"; \");\n}\n\nfunction extractEnvironmentValue(output: string, name: string): string | undefined {\n  const startMarker = envCaptureStart(name);\n  const endMarker = envCaptureEnd(name);\n  const startIndex = output.indexOf(startMarker);\n  if (startIndex === -1) return undefined;\n\n  const valueStartIndex = startIndex + startMarker.length;\n  const endIndex = output.indexOf(endMarker, valueStartIndex);\n  if (endIndex === -1) return undefined;\n\n  const value = output\n    .slice(valueStartIndex, endIndex)\n    .replace(/^\\r?\\n/, \"\")\n    .replace(/\\r?\\n$/, \"\");\n\n  return value.length > 0 ? value : undefined;\n}\n\nexport type ShellEnvironmentReader = (\n  shell: string,\n  names: ReadonlyArray<string>,\n  execFile?: ExecFileSyncLike,\n) => Partial<Record<string, string>>;\n\nexport const readEnvironmentFromLoginShell: ShellEnvironmentReader = (\n  shell,\n  names,\n  execFile = NodeChildProcess.execFileSync,\n) => {\n  if (names.length === 0) {\n    return {};\n  }\n\n  const output = execFile(shell, [\"-ilc\", buildEnvironmentCaptureCommand(names)], {\n    encoding: \"utf8\",\n    timeout: 5000,\n  });\n\n  const environment: Partial<Record<string, string>> = {};\n  for (const name of names) {\n    const value = extractEnvironmentValue(output, name);\n    if (value !== undefined) {\n      environment[name] = value;\n    }\n  }\n\n  return environment;\n};\n\nexport type WindowsShellEnvironmentReader = (\n  names: ReadonlyArray<string>,\n  options?: WindowsEnvironmentProbeOptions,\n) => Partial<Record<string, string>>;\n\nexport const WindowsShellEnvironment = Context.Reference<WindowsShellEnvironmentReader>(\n  \"@t3tools/shared/shell/WindowsShellEnvironment\",\n  {\n    defaultValue: () => readEnvironmentFromWindowsShell,\n  },\n);\n\nexport const CommandAvailability = Context.Reference<CommandAvailabilityChecker>(\n  \"@t3tools/shared/shell/CommandAvailability\",\n  {\n    defaultValue: () => isCommandAvailable,\n  },\n);\n\nexport function readEnvironmentFromWindowsShell(\n  names: ReadonlyArray<string>,\n  execFile?: ExecFileSyncLike,\n): Partial<Record<string, string>>;\nexport function readEnvironmentFromWindowsShell(\n  names: ReadonlyArray<string>,\n  options?: WindowsEnvironmentProbeOptions,\n  execFile?: ExecFileSyncLike,\n): Partial<Record<string, string>>;\nexport function readEnvironmentFromWindowsShell(\n  names: ReadonlyArray<string>,\n  optionsOrExecFile?: WindowsEnvironmentProbeOptions | ExecFileSyncLike,\n  maybeExecFile?: ExecFileSyncLike,\n): Partial<Record<string, string>> {\n  if (names.length === 0) {\n    return {};\n  }\n\n  const options =\n    typeof optionsOrExecFile === \"function\"\n      ? ({} satisfies WindowsEnvironmentProbeOptions)\n      : (optionsOrExecFile ?? {});\n  const execFile: ExecFileSyncLike =\n    typeof optionsOrExecFile === \"function\"\n      ? optionsOrExecFile\n      : (maybeExecFile ?? (NodeChildProcess.execFileSync as ExecFileSyncLike));\n  const command = buildWindowsEnvironmentCaptureCommand(names);\n  const args = [\n    \"-NoLogo\",\n    ...(options.loadProfile ? ([] as const) : ([\"-NoProfile\"] as const)),\n    \"-NonInteractive\",\n    \"-Command\",\n    command,\n  ];\n  for (const shell of WINDOWS_SHELL_CANDIDATES) {\n    try {\n      const output = execFile(shell, args, { encoding: \"utf8\", timeout: 5000 });\n\n      const environment: Partial<Record<string, string>> = {};\n      for (const name of names) {\n        const value = extractEnvironmentValue(output, name);\n        if (value !== undefined) {\n          environment[name] = value;\n        }\n      }\n      return environment;\n    } catch {\n      continue;\n    }\n  }\n\n  return {};\n}\n\nfunction stripWrappingQuotes(value: string): string {\n  return value.replace(/^\"+|\"+$/g, \"\");\n}\n\nfunction pathDelimiterForPlatform(platform: NodeJS.Platform): string {\n  return platform === \"win32\" ? WINDOWS_PATH_DELIMITER : POSIX_PATH_DELIMITER;\n}\n\nfunction normalizePathEntryForComparison(entry: string, platform: NodeJS.Platform): string {\n  const normalized = stripWrappingQuotes(entry.trim());\n  return platform === \"win32\" ? normalized.toLowerCase() : normalized;\n}\n\nexport function mergePathValues(\n  preferredPath: string | undefined,\n  inheritedPath: string | undefined,\n  platform: NodeJS.Platform,\n): string | undefined {\n  const delimiter = pathDelimiterForPlatform(platform);\n  const merged: string[] = [];\n  const seen = new Set<string>();\n\n  for (const rawValue of [preferredPath, inheritedPath]) {\n    if (!rawValue) continue;\n\n    for (const entry of rawValue.split(delimiter)) {\n      const trimmed = entry.trim();\n      if (trimmed.length === 0) continue;\n\n      const normalized = normalizePathEntryForComparison(trimmed, platform);\n      if (normalized.length === 0 || seen.has(normalized)) continue;\n\n      seen.add(normalized);\n      merged.push(trimmed);\n    }\n  }\n\n  return merged.length > 0 ? merged.join(delimiter) : undefined;\n}\n\nfunction readEnvPath(env: NodeJS.ProcessEnv): string | undefined {\n  return env.PATH ?? env.Path ?? env.path;\n}\n\nfunction resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {\n  return readEnvPath(env) ?? \"\";\n}\n\nfunction resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {\n  const rawValue = env.PATHEXT;\n  const fallback = [\".COM\", \".EXE\", \".BAT\", \".CMD\"];\n  if (!rawValue) return fallback;\n\n  const parsed: string[] = [];\n  for (const entry of rawValue.split(\";\")) {\n    const trimmed = entry.trim();\n    if (trimmed.length === 0) continue;\n    parsed.push(trimmed.startsWith(\".\") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);\n  }\n  return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;\n}\n\nfunction resolveCommandCandidates(\n  command: string,\n  platform: NodeJS.Platform,\n  windowsPathExtensions: ReadonlyArray<string>,\n  extname: (path: string) => string,\n): ReadonlyArray<string> {\n  if (platform !== \"win32\") return [command];\n  const extension = extname(command);\n  const normalizedExtension = extension.toUpperCase();\n\n  if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {\n    const commandWithoutExtension = command.slice(0, -extension.length);\n    return Array.from(\n      new Set([\n        command,\n        `${commandWithoutExtension}${normalizedExtension}`,\n        `${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,\n      ]),\n    );\n  }\n\n  const candidates: string[] = [];\n  for (const candidateExtension of windowsPathExtensions) {\n    candidates.push(`${command}${candidateExtension}`);\n    candidates.push(`${command}${candidateExtension.toLowerCase()}`);\n  }\n  return Array.from(new Set(candidates));\n}\n\n// Session bootstrap resolves the same commands over and over, each PATH scan\n// costing hundreds of 'shell.isExecutableFile' filesystem probes (tens of\n// thousands per connect). Memoize the scan outcome per\n// (platform, PATH, PATHEXT, command) for a short window: repeat scans hit the\n// cache while any change to the search environment invalidates immediately.\n// Explicit-path resolution is never cached - callers probe paths they have\n// just written (e.g. managed binary installs). A \"not-found\" outcome is also\n// cached for the TTL, so a just-installed binary can stay invisible for up to\n// 30s unless resolved by explicit path.\n// TTL expiry uses the monotonic clock (Clock.currentTimeNanos) so backward\n// wall-clock adjustments cannot keep expired entries alive.\nconst COMMAND_RESOLUTION_CACHE_TTL_NANOS = 30_000_000_000n;\nconst COMMAND_RESOLUTION_CACHE_MAX_ENTRIES = 512;\nconst COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR = String.fromCharCode(0);\n\ninterface CommandResolutionCacheEntry {\n  readonly resolvedPath: string | null;\n  readonly expiresAtNanos: bigint;\n}\n\n// The cache lives in the Effect environment (like HostProcessPlatform above)\n// so tests and embedders can provide an isolated instance; the default is a\n// single process-wide map shared by all consumers.\nexport const CommandResolutionCache = Context.Reference<Map<string, CommandResolutionCacheEntry>>(\n  \"@t3tools/shared/shell/CommandResolutionCache\",\n  {\n    defaultValue: () => new Map(),\n  },\n);\n\nfunction cacheCommandResolution(\n  cache: Map<string, CommandResolutionCacheEntry>,\n  cacheKey: string,\n  resolvedPath: string | null,\n  nowNanos: bigint,\n): void {\n  if (cache.size >= COMMAND_RESOLUTION_CACHE_MAX_ENTRIES) {\n    const oldestKey = cache.keys().next().value;\n    if (oldestKey !== undefined) {\n      cache.delete(oldestKey);\n    }\n  }\n  cache.set(cacheKey, {\n    resolvedPath,\n    expiresAtNanos: nowNanos + COMMAND_RESOLUTION_CACHE_TTL_NANOS,\n  });\n}\n\nconst isExecutableFile = Effect.fn(\"shell.isExecutableFile\")(function* (\n  filePath: string,\n  platform: NodeJS.Platform,\n  windowsPathExtensions: ReadonlyArray<string>,\n): Effect.fn.Return<boolean, never, FileSystem.FileSystem | Path.Path> {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const stat = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));\n  if (stat === null || stat.type !== \"File\") return false;\n\n  if (platform === \"win32\") {\n    const extension = path.extname(filePath);\n    if (extension.length === 0) return false;\n    return windowsPathExtensions.includes(extension.toUpperCase());\n  }\n\n  return canExecuteFile(filePath);\n});\n\nconst resolveCommandPathForPlatform = Effect.fn(\"shell.resolveCommandPathForPlatform\")(function* (\n  command: string,\n  options: CommandAvailabilityOptions & { readonly platform: NodeJS.Platform },\n): Effect.fn.Return<string, CommandResolutionError, FileSystem.FileSystem | Path.Path> {\n  const path = yield* Path.Path;\n  const platform = options.platform;\n  const env = options.env ?? process.env;\n  const windowsPathExtensions = platform === \"win32\" ? resolveWindowsPathExtensions(env) : [];\n  const commandCandidates = resolveCommandCandidates(\n    command,\n    platform,\n    windowsPathExtensions,\n    path.extname,\n  );\n\n  if (command.includes(\"/\") || command.includes(\"\\\\\")) {\n    for (const candidate of commandCandidates) {\n      if (yield* isExecutableFile(candidate, platform, windowsPathExtensions)) {\n        return candidate;\n      }\n    }\n    return yield* new CommandResolutionError({ command, reason: \"not-found\" });\n  }\n\n  const pathValue = resolvePathEnvironmentVariable(env);\n  if (pathValue.length === 0) {\n    return yield* new CommandResolutionError({ command, reason: \"not-found\" });\n  }\n\n  const cacheKey = [platform, pathValue, windowsPathExtensions.join(\";\"), command].join(\n    COMMAND_RESOLUTION_CACHE_KEY_SEPARATOR,\n  );\n  const cache = yield* CommandResolutionCache;\n  const nowNanos = yield* Clock.currentTimeNanos;\n  const cached = cache.get(cacheKey);\n  if (cached !== undefined && cached.expiresAtNanos > nowNanos) {\n    if (cached.resolvedPath === null) {\n      return yield* new CommandResolutionError({ command, reason: \"not-found\" });\n    }\n    return cached.resolvedPath;\n  }\n\n  const pathEntries: string[] = [];\n  for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {\n    const pathEntry = stripWrappingQuotes(entry.trim());\n    if (pathEntry.length > 0) {\n      pathEntries.push(pathEntry);\n    }\n  }\n\n  for (const pathEntry of pathEntries) {\n    for (const candidate of commandCandidates) {\n      const candidatePath = path.join(pathEntry, candidate);\n      if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) {\n        cacheCommandResolution(cache, cacheKey, candidatePath, nowNanos);\n        return candidatePath;\n      }\n    }\n  }\n  cacheCommandResolution(cache, cacheKey, null, nowNanos);\n  return yield* new CommandResolutionError({ command, reason: \"not-found\" });\n});\n\nexport const resolveCommandPath = Effect.fn(\"shell.resolveCommandPath\")(function* (\n  command: string,\n  options: CommandAvailabilityOptions = {},\n) {\n  return yield* resolveCommandPathForPlatform(command, {\n    env: options.env ?? (yield* HostProcessEnvironment),\n    platform: yield* HostProcessPlatform,\n  });\n});\n\nexport const resolveSpawnCommand = Effect.fn(\"shell.resolveSpawnCommand\")(function* (\n  command: string,\n  args: ReadonlyArray<string>,\n  options: CommandAvailabilityOptions = {},\n): Effect.fn.Return<ResolvedSpawnCommand> {\n  const platform = yield* HostProcessPlatform;\n  if (platform !== \"win32\") {\n    return { command, args: [...args], shell: false };\n  }\n\n  const hostEnvironment = yield* HostProcessEnvironment;\n  const env =\n    options.env === undefined\n      ? hostEnvironment\n      : options.extendEnv\n        ? { ...hostEnvironment, ...options.env }\n        : options.env;\n  const resolveExecutable = yield* SpawnExecutableResolution;\n  const resolvedCommand = resolveExecutable(command, platform, env) ?? command;\n  const extension = NodePath.win32.extname(resolvedCommand).toLowerCase();\n  if (extension !== \".cmd\" && extension !== \".bat\") {\n    return { command: resolvedCommand, args: [...args], shell: false };\n  }\n\n  return {\n    command: escapeWindowsShellArg(resolvedCommand),\n    args: sanitizeShellModeArgsForPlatform(args, platform),\n    shell: true,\n  };\n});\n\nexport const isCommandAvailable = Effect.fn(\"shell.isCommandAvailable\")(function* (\n  command: string,\n  options: CommandAvailabilityOptions = {},\n) {\n  return yield* resolveCommandPath(command, options).pipe(\n    Effect.as(true),\n    Effect.catchTag(\"CommandResolutionError\", () => Effect.succeed(false)),\n  );\n});\n\nexport function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray<string> {\n  const appData = env.APPDATA?.trim();\n  const localAppData = env.LOCALAPPDATA?.trim();\n  const userProfile = env.USERPROFILE?.trim();\n\n  return [\n    ...(appData ? [`${appData}\\\\npm`] : []),\n    ...(localAppData ? [`${localAppData}\\\\Programs\\\\nodejs`, `${localAppData}\\\\Volta\\\\bin`] : []),\n    ...(localAppData ? [`${localAppData}\\\\pnpm`] : []),\n    ...(userProfile ? [`${userProfile}\\\\.bun\\\\bin`, `${userProfile}\\\\scoop\\\\shims`] : []),\n  ];\n}\n\nfunction readWindowsEnvironmentSafely(\n  readEnvironment: WindowsShellEnvironmentReader,\n  names: ReadonlyArray<string>,\n  options?: WindowsEnvironmentProbeOptions,\n): Partial<Record<string, string>> {\n  try {\n    return readEnvironment(names, options);\n  } catch {\n    return {};\n  }\n}\n\nfunction mergeWindowsEnv(\n  currentEnv: NodeJS.ProcessEnv,\n  patch: Partial<Record<string, string>>,\n): NodeJS.ProcessEnv {\n  const nextEnv: NodeJS.ProcessEnv = { ...currentEnv };\n  for (const [key, value] of Object.entries(patch)) {\n    if (value !== undefined) {\n      nextEnv[key] = value;\n    }\n  }\n  return nextEnv;\n}\n\nexport const resolveWindowsEnvironment = Effect.fn(\"shell.resolveWindowsEnvironment\")(function* (\n  env: NodeJS.ProcessEnv,\n): Effect.fn.Return<Partial<NodeJS.ProcessEnv>, never, FileSystem.FileSystem | Path.Path> {\n  const readEnvironment = yield* WindowsShellEnvironment;\n  const commandAvailable = yield* CommandAvailability;\n  const inheritedPath = readEnvPath(env);\n  const shellPath = readWindowsEnvironmentSafely(readEnvironment, [\"PATH\"], {\n    loadProfile: false,\n  }).PATH;\n  const mergedPath = mergePathValues(shellPath, inheritedPath, \"win32\");\n  const knownCliPath = resolveKnownWindowsCliDirs(env).join(WINDOWS_PATH_DELIMITER);\n  const baselinePath = mergePathValues(knownCliPath, mergedPath, \"win32\");\n  const baselinePatch: Partial<NodeJS.ProcessEnv> = baselinePath ? { PATH: baselinePath } : {};\n  const baselineEnv = mergeWindowsEnv(env, baselinePatch);\n\n  if (yield* commandAvailable(\"node\", { env: baselineEnv })) {\n    return baselinePatch;\n  }\n\n  const profiledEnvironment = readWindowsEnvironmentSafely(\n    readEnvironment,\n    [\"PATH\", \"FNM_DIR\", \"FNM_MULTISHELL_PATH\"],\n    { loadProfile: true },\n  );\n  const profiledPath = mergePathValues(profiledEnvironment.PATH, baselinePath, \"win32\");\n  const profiledPatch: Partial<NodeJS.ProcessEnv> = {\n    ...(profiledPath ? { PATH: profiledPath } : {}),\n    ...(profiledEnvironment.FNM_DIR ? { FNM_DIR: profiledEnvironment.FNM_DIR } : {}),\n    ...(profiledEnvironment.FNM_MULTISHELL_PATH\n      ? { FNM_MULTISHELL_PATH: profiledEnvironment.FNM_MULTISHELL_PATH }\n      : {}),\n  };\n  return Object.keys(profiledPatch).length > 0\n    ? { ...baselinePatch, ...profiledPatch }\n    : baselinePatch;\n});\n","import { HostProcessEnvironment, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport {\n  listLoginShellCandidates,\n  mergePathEntries,\n  readPathFromLoginShell,\n  readPathFromLaunchctl,\n  resolveWindowsEnvironment,\n} from \"@t3tools/shared/shell\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as NodeOS from \"node:os\";\n\nfunction logPathHydrationWarning(message: string, error?: unknown): void {\n  process.stderr.write(\n    `[server] ${message} ${error instanceof Error ? error.message : (error ?? \"\")}\\n`,\n  );\n}\n\nfunction hydratePosixPath(env: NodeJS.ProcessEnv, platform: NodeJS.Platform): void {\n  let shellPath: string | undefined;\n  for (const shell of listLoginShellCandidates(platform, env.SHELL)) {\n    try {\n      shellPath = readPathFromLoginShell(shell);\n    } catch (error) {\n      logPathHydrationWarning(`Failed to read PATH from login shell ${shell}.`, error);\n    }\n\n    if (shellPath) break;\n  }\n\n  const launchctlPath = platform === \"darwin\" && !shellPath ? readPathFromLaunchctl() : undefined;\n  const mergedPath = mergePathEntries(shellPath ?? launchctlPath, env.PATH, platform);\n  if (mergedPath) {\n    env.PATH = mergedPath;\n  }\n}\n\nexport function hydratePosixHome(\n  env: NodeJS.ProcessEnv,\n  resolveHomeDir = () => NodeOS.userInfo().homedir,\n): void {\n  if ((env.HOME?.trim() ?? \"\").length > 0) return;\n\n  const homeDir = resolveHomeDir();\n  if (homeDir.length > 0) {\n    env.HOME = homeDir;\n  }\n}\n\nexport const fixPath = Effect.fn(\"fixPath\")(function* (): Effect.fn.Return<\n  void,\n  never,\n  FileSystem.FileSystem | Path.Path\n> {\n  const platform = yield* HostProcessPlatform;\n  const env = yield* HostProcessEnvironment;\n\n  if (platform === \"win32\") {\n    const repairedEnvironment = yield* resolveWindowsEnvironment(env).pipe(\n      Effect.catchDefect((defect) =>\n        Effect.sync(() => {\n          logPathHydrationWarning(\"Failed to hydrate PATH from the user environment.\", defect);\n          return {} as Partial<NodeJS.ProcessEnv>;\n        }),\n      ),\n    );\n    for (const [key, value] of Object.entries(repairedEnvironment)) {\n      if (value !== undefined) {\n        env[key] = value;\n      }\n    }\n    return;\n  }\n\n  if (platform !== \"darwin\" && platform !== \"linux\") return;\n\n  yield* Effect.sync(() => hydratePosixHome(env)).pipe(\n    Effect.catchDefect((defect) =>\n      Effect.sync(() => {\n        logPathHydrationWarning(\"Failed to hydrate HOME from the user account.\", defect);\n      }),\n    ),\n  );\n  yield* Effect.sync(() => hydratePosixPath(env, platform)).pipe(\n    Effect.catchDefect((defect) =>\n      Effect.sync(() => {\n        logPathHydrationWarning(\"Failed to hydrate PATH from the user environment.\", defect);\n      }),\n    ),\n  );\n});\n\nexport const expandHomePath = Effect.fn(function* (input: string) {\n  const { join } = yield* Path.Path;\n  if (input === \"~\") {\n    return NodeOS.homedir();\n  }\n  if (input.startsWith(\"~/\") || input.startsWith(\"~\\\\\")) {\n    return join(NodeOS.homedir(), input.slice(2));\n  }\n  return input;\n});\n\nexport const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {\n  const { join, resolve } = yield* Path.Path;\n  if (!raw || raw.trim().length === 0) {\n    return join(NodeOS.homedir(), \".synaptic\");\n  }\n  return resolve(yield* expandHomePath(raw.trim()));\n});\n","import * as NetService from \"@t3tools/shared/Net\";\nimport { parsePersistedServerObservabilitySettings } from \"@t3tools/shared/serverSettings\";\nimport { DesktopBackendBootstrap, PortSchema } from \"@t3tools/contracts\";\nimport * as Config from \"effect/Config\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as LogLevel from \"effect/LogLevel\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport { Argument, Flag } from \"effect/unstable/cli\";\n\nimport { readBootstrapEnvelope } from \"../bootstrap.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport { expandHomePath, resolveBaseDir } from \"../os-jank.ts\";\n\nexport const modeFlag = Flag.choice(\"mode\", ServerConfig.RuntimeMode.literals).pipe(\n  Flag.withDescription(\"Runtime mode. `desktop` keeps loopback defaults unless overridden.\"),\n  Flag.optional,\n);\nexport const portFlag = Flag.integer(\"port\").pipe(\n  Flag.withSchema(PortSchema),\n  Flag.withDescription(\"Port for the HTTP/WebSocket server.\"),\n  Flag.optional,\n);\nexport const hostFlag = Flag.string(\"host\").pipe(\n  Flag.withDescription(\"Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP).\"),\n  Flag.optional,\n);\nexport const baseDirFlag = Flag.string(\"base-dir\").pipe(\n  Flag.withDescription(\n    \"Explicit Synaptic Code data directory; runtime state is stored under userdata (equivalent to SYNAPTIC_HOME).\",\n  ),\n  Flag.optional,\n);\nexport const devUrlFlag = Flag.string(\"dev-url\").pipe(\n  Flag.withSchema(Schema.URLFromString),\n  Flag.withDescription(\"Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL).\"),\n  Flag.optional,\n);\nexport const noBrowserFlag = Flag.boolean(\"no-browser\").pipe(\n  Flag.withDescription(\"Disable automatic browser opening.\"),\n  Flag.optional,\n);\nexport const bootstrapFdFlag = Flag.integer(\"bootstrap-fd\").pipe(\n  Flag.withSchema(Schema.Int),\n  Flag.withDescription(\"Read one-time bootstrap secrets from the given file descriptor.\"),\n  Flag.optional,\n);\nexport const autoBootstrapProjectFromCwdFlag = Flag.boolean(\"auto-bootstrap-project-from-cwd\").pipe(\n  Flag.withDescription(\n    \"Create a project for the current working directory on startup when missing.\",\n  ),\n  Flag.optional,\n);\nexport const logWebSocketEventsFlag = Flag.boolean(\"log-websocket-events\").pipe(\n  Flag.withDescription(\n    \"Emit server-side logs for outbound WebSocket push traffic (equivalent to SYNAPTIC_LOG_WS_EVENTS).\",\n  ),\n  Flag.withAlias(\"log-ws-events\"),\n  Flag.optional,\n);\nexport const tailscaleServeFlag = Flag.boolean(\"tailscale-serve\").pipe(\n  Flag.withDescription(\n    \"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.\",\n  ),\n  Flag.optional,\n);\nexport const tailscaleServePortFlag = Flag.integer(\"tailscale-serve-port\").pipe(\n  Flag.withSchema(PortSchema),\n  Flag.withDescription(\"HTTPS port for Tailscale Serve when --tailscale-serve is enabled.\"),\n  Flag.optional,\n);\n\nconst EnvServerConfig = Config.all({\n  logLevel: Config.logLevel(\"SYNAPTIC_LOG_LEVEL\").pipe(Config.withDefault(\"Info\")),\n  traceMinLevel: Config.logLevel(\"SYNAPTIC_TRACE_MIN_LEVEL\").pipe(Config.withDefault(\"Info\")),\n  traceTimingEnabled: Config.boolean(\"SYNAPTIC_TRACE_TIMING_ENABLED\").pipe(\n    Config.withDefault(true),\n  ),\n  traceFile: Config.string(\"SYNAPTIC_TRACE_FILE\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  traceMaxBytes: Config.int(\"SYNAPTIC_TRACE_MAX_BYTES\").pipe(Config.withDefault(10 * 1024 * 1024)),\n  traceMaxFiles: Config.int(\"SYNAPTIC_TRACE_MAX_FILES\").pipe(Config.withDefault(10)),\n  traceBatchWindowMs: Config.int(\"SYNAPTIC_TRACE_BATCH_WINDOW_MS\").pipe(Config.withDefault(1_000)),\n  otlpTracesUrl: Config.string(\"SYNAPTIC_OTLP_TRACES_URL\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  otlpMetricsUrl: Config.string(\"SYNAPTIC_OTLP_METRICS_URL\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  otlpExportIntervalMs: Config.int(\"SYNAPTIC_OTLP_EXPORT_INTERVAL_MS\").pipe(\n    Config.withDefault(10_000),\n  ),\n  otlpServiceName: Config.string(\"SYNAPTIC_OTLP_SERVICE_NAME\").pipe(\n    Config.withDefault(\"t3-server\"),\n  ),\n  mode: Config.schema(ServerConfig.RuntimeMode, \"SYNAPTIC_MODE\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  port: Config.port(\"SYNAPTIC_PORT\").pipe(Config.option, Config.map(Option.getOrUndefined)),\n  host: Config.string(\"SYNAPTIC_HOST\").pipe(Config.option, Config.map(Option.getOrUndefined)),\n  t3Home: Config.string(\"SYNAPTIC_HOME\").pipe(Config.option, Config.map(Option.getOrUndefined)),\n  devUrl: Config.url(\"VITE_DEV_SERVER_URL\").pipe(Config.option, Config.map(Option.getOrUndefined)),\n  devAllowedOrigins: Config.string(\"SYNAPTIC_DEV_ALLOWED_ORIGINS\").pipe(\n    Config.withDefault(\"\"),\n    Config.map((value) =>\n      value\n        .split(\",\")\n        .map((entry) => entry.trim())\n        .filter((entry) => entry.length > 0),\n    ),\n  ),\n  noBrowser: Config.boolean(\"SYNAPTIC_NO_BROWSER\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  bootstrapFd: Config.int(\"SYNAPTIC_BOOTSTRAP_FD\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  autoBootstrapProjectFromCwd: Config.boolean(\"SYNAPTIC_AUTO_BOOTSTRAP_PROJECT_FROM_CWD\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  logWebSocketEvents: Config.boolean(\"SYNAPTIC_LOG_WS_EVENTS\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  tailscaleServeEnabled: Config.boolean(\"SYNAPTIC_TAILSCALE_SERVE\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n  tailscaleServePort: Config.port(\"SYNAPTIC_TAILSCALE_SERVE_PORT\").pipe(\n    Config.option,\n    Config.map(Option.getOrUndefined),\n  ),\n});\n\nexport interface CliServerFlags {\n  readonly mode: Option.Option<ServerConfig.RuntimeMode>;\n  readonly port: Option.Option<number>;\n  readonly host: Option.Option<string>;\n  readonly baseDir: Option.Option<string>;\n  readonly cwd: Option.Option<string>;\n  readonly devUrl: Option.Option<URL>;\n  readonly noBrowser: Option.Option<boolean>;\n  readonly bootstrapFd: Option.Option<number>;\n  readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;\n  readonly logWebSocketEvents: Option.Option<boolean>;\n  readonly tailscaleServeEnabled: Option.Option<boolean>;\n  readonly tailscaleServePort: Option.Option<number>;\n}\n\nexport interface CliAuthLocationFlags {\n  readonly baseDir: Option.Option<string>;\n  readonly devUrl?: Option.Option<URL>;\n}\n\nexport const sharedServerLocationFlags = {\n  baseDir: baseDirFlag,\n  devUrl: devUrlFlag,\n} as const;\n\nexport const projectLocationFlags = {\n  baseDir: baseDirFlag,\n} as const;\n\nexport const sharedServerCommandFlags = {\n  mode: modeFlag,\n  port: portFlag,\n  host: hostFlag,\n  baseDir: baseDirFlag,\n  cwd: Argument.string(\"cwd\").pipe(\n    Argument.withDescription(\n      \"Working directory for provider sessions (defaults to the current directory).\",\n    ),\n    Argument.optional,\n  ),\n  devUrl: devUrlFlag,\n  noBrowser: noBrowserFlag,\n  bootstrapFd: bootstrapFdFlag,\n  autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,\n  logWebSocketEvents: logWebSocketEventsFlag,\n  tailscaleServeEnabled: tailscaleServeFlag,\n  tailscaleServePort: tailscaleServePortFlag,\n} as const;\n\nexport const authLocationFlags = sharedServerLocationFlags;\n\nconst resolveOptionPrecedence = <Value>(\n  ...values: ReadonlyArray<Option.Option<Value>>\n): Option.Option<Value> => Option.firstSomeOf(values);\n\nconst loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {\n  const fs = yield* FileSystem.FileSystem;\n  const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));\n  if (!exists) {\n    return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };\n  }\n\n  const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => \"\"));\n  return parsePersistedServerObservabilitySettings(raw);\n});\n\nexport const resolveServerConfig = (\n  flags: CliServerFlags,\n  cliLogLevel: Option.Option<LogLevel.LogLevel>,\n  options?: {\n    readonly startupPresentation?: ServerConfig.StartupPresentation;\n    readonly forceAutoBootstrapProjectFromCwd?: boolean;\n  },\n) =>\n  Effect.gen(function* () {\n    const { findAvailablePort } = yield* NetService.NetService;\n    const path = yield* Path.Path;\n    const fs = yield* FileSystem.FileSystem;\n    const env = yield* EnvServerConfig;\n    const normalizedFlags = {\n      mode: flags.mode ?? Option.none(),\n      port: flags.port ?? Option.none(),\n      host: flags.host ?? Option.none(),\n      baseDir: flags.baseDir ?? Option.none(),\n      cwd: flags.cwd ?? Option.none(),\n      devUrl: flags.devUrl ?? Option.none(),\n      noBrowser: flags.noBrowser ?? Option.none(),\n      bootstrapFd: flags.bootstrapFd ?? Option.none(),\n      autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),\n      logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),\n      tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),\n      tailscaleServePort: flags.tailscaleServePort ?? Option.none(),\n    } satisfies CliServerFlags;\n    const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;\n    const bootstrapEnvelope =\n      bootstrapFd !== undefined\n        ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)\n        : Option.none();\n    const bootstrap = Option.getOrUndefined(bootstrapEnvelope);\n\n    const mode: ServerConfig.RuntimeMode = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.mode,\n        Option.fromUndefinedOr(env.mode),\n        Option.fromUndefinedOr(bootstrap?.mode),\n      ),\n      () => \"web\",\n    );\n\n    const port = yield* Option.match(\n      resolveOptionPrecedence(\n        normalizedFlags.port,\n        Option.fromUndefinedOr(env.port),\n        Option.fromUndefinedOr(bootstrap?.port),\n      ),\n      {\n        onSome: (value) => Effect.succeed(value),\n        onNone: () => {\n          if (mode === \"desktop\") {\n            return Effect.succeed(ServerConfig.DEFAULT_PORT);\n          }\n          return findAvailablePort(ServerConfig.DEFAULT_PORT);\n        },\n      },\n    );\n    const devUrl = Option.getOrElse(\n      resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),\n      () => undefined,\n    );\n    const explicitBaseDir = resolveOptionPrecedence(\n      normalizedFlags.baseDir,\n      Option.fromUndefinedOr(env.t3Home),\n    ).pipe(Option.filter((value) => value.trim().length > 0));\n    const baseDir = yield* resolveBaseDir(\n      Option.getOrUndefined(\n        resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),\n      ),\n    );\n    const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());\n    const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));\n    yield* fs.makeDirectory(cwd, { recursive: true });\n    const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {\n      baseDirIsExplicit: Option.isSome(explicitBaseDir),\n    });\n    yield* ServerConfig.ensureServerDirectories(derivedPaths);\n    const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(\n      derivedPaths.settingsPath,\n    );\n    const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;\n    yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });\n    const startupPresentation = options?.startupPresentation ?? \"browser\";\n    const isHeadlessStartup = startupPresentation === \"headless\";\n    const noBrowser = Option.getOrElse(\n      resolveOptionPrecedence(\n        isHeadlessStartup ? Option.some(true) : Option.none(),\n        normalizedFlags.noBrowser,\n        Option.fromUndefinedOr(env.noBrowser),\n        Option.fromUndefinedOr(bootstrap?.noBrowser),\n      ),\n      () => mode === \"desktop\",\n    );\n    const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;\n    const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;\n    const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;\n    const resourceMonitorPath = bootstrap?.resourceMonitorPath;\n    const autoBootstrapProjectFromCwd = Option.getOrElse(\n      resolveOptionPrecedence(\n        Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),\n        isHeadlessStartup ? Option.some(false) : Option.none(),\n        normalizedFlags.autoBootstrapProjectFromCwd,\n        Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),\n      ),\n      () => mode === \"web\",\n    );\n    const logWebSocketEvents = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.logWebSocketEvents,\n        Option.fromUndefinedOr(env.logWebSocketEvents),\n      ),\n      () => Boolean(devUrl),\n    );\n    const tailscaleServeEnabled = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.tailscaleServeEnabled,\n        Option.fromUndefinedOr(env.tailscaleServeEnabled),\n        Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),\n      ),\n      () => false,\n    );\n    const tailscaleServePort = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.tailscaleServePort,\n        Option.fromUndefinedOr(env.tailscaleServePort),\n        Option.fromUndefinedOr(bootstrap?.tailscaleServePort),\n      ),\n      () => 443,\n    );\n    const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();\n    const host = Option.getOrElse(\n      resolveOptionPrecedence(\n        normalizedFlags.host,\n        Option.fromUndefinedOr(env.host),\n        Option.fromUndefinedOr(bootstrap?.host),\n      ),\n      () => (mode === \"desktop\" ? \"127.0.0.1\" : undefined),\n    );\n    const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);\n\n    const config: ServerConfig.ServerConfig[\"Service\"] = {\n      logLevel,\n      traceMinLevel: env.traceMinLevel,\n      traceTimingEnabled: env.traceTimingEnabled,\n      traceBatchWindowMs: env.traceBatchWindowMs,\n      traceMaxBytes: env.traceMaxBytes,\n      traceMaxFiles: env.traceMaxFiles,\n      otlpTracesUrl:\n        env.otlpTracesUrl ??\n        bootstrap?.otlpTracesUrl ??\n        persistedObservabilitySettings.otlpTracesUrl,\n      otlpMetricsUrl:\n        env.otlpMetricsUrl ??\n        bootstrap?.otlpMetricsUrl ??\n        persistedObservabilitySettings.otlpMetricsUrl,\n      otlpExportIntervalMs: env.otlpExportIntervalMs,\n      otlpServiceName: env.otlpServiceName,\n      mode,\n      port,\n      cwd,\n      baseDir,\n      ...derivedPaths,\n      serverTracePath,\n      host,\n      staticDir,\n      devUrl,\n      devAllowedOrigins: env.devAllowedOrigins,\n      noBrowser,\n      startupPresentation,\n      desktopBootstrapToken,\n      desktopTelemetryFd,\n      desktopTelemetryControlFd,\n      resourceMonitorPath,\n      autoBootstrapProjectFromCwd,\n      logWebSocketEvents,\n      tailscaleServeEnabled,\n      tailscaleServePort,\n    };\n\n    return config;\n  });\n\nexport const resolveCliAuthConfig = (\n  flags: CliAuthLocationFlags,\n  cliLogLevel: Option.Option<LogLevel.LogLevel>,\n) =>\n  resolveServerConfig(\n    {\n      mode: Option.none(),\n      port: Option.none(),\n      host: Option.none(),\n      baseDir: flags.baseDir,\n      cwd: Option.none(),\n      devUrl: flags.devUrl ?? Option.none(),\n      noBrowser: Option.none(),\n      bootstrapFd: Option.none(),\n      autoBootstrapProjectFromCwd: Option.none(),\n      logWebSocketEvents: Option.none(),\n      tailscaleServeEnabled: Option.none(),\n      tailscaleServePort: Option.none(),\n    },\n    cliLogLevel,\n  );\n\nconst DurationShorthandPattern = /^(?<value>\\d+)(?<unit>ms|s|m|h|d|w)$/i;\n\nconst parseDurationInput = (value: string): Duration.Duration | null => {\n  const trimmed = value.trim();\n  if (trimmed.length === 0) return null;\n\n  const shorthand = DurationShorthandPattern.exec(trimmed);\n  const normalizedInput = shorthand?.groups\n    ? (() => {\n        const amountText = shorthand.groups.value;\n        const unitText = shorthand.groups.unit;\n        if (typeof amountText !== \"string\" || typeof unitText !== \"string\") {\n          return null;\n        }\n\n        const amount = Number.parseInt(amountText, 10);\n        if (!Number.isFinite(amount)) return null;\n\n        switch (unitText.toLowerCase()) {\n          case \"ms\":\n            return `${amount} millis`;\n          case \"s\":\n            return `${amount} seconds`;\n          case \"m\":\n            return `${amount} minutes`;\n          case \"h\":\n            return `${amount} hours`;\n          case \"d\":\n            return `${amount} days`;\n          case \"w\":\n            return `${amount} weeks`;\n          default:\n            return null;\n        }\n      })()\n    : (trimmed as Duration.Input);\n\n  if (normalizedInput === null) return null;\n\n  const decoded = Duration.fromInput(normalizedInput as Duration.Input);\n  return Option.isSome(decoded) ? decoded.value : null;\n};\n\nexport const DurationFromString = Schema.String.pipe(\n  Schema.decodeTo(\n    Schema.Duration,\n    SchemaTransformation.transformOrFail({\n      decode: (value) => {\n        const duration = parseDurationInput(value);\n        if (duration !== null) {\n          return Effect.succeed(duration);\n        }\n        return Effect.fail(\n          new SchemaIssue.InvalidValue({\n            message: \"Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.\",\n          }),\n        );\n      },\n      encode: (duration) => Effect.succeed(Duration.format(duration)),\n    }),\n  ),\n);\n","import {\n  AuthAdministrativeScopes,\n  AuthSessionId,\n  AuthStandardClientScopes,\n} from \"@t3tools/contracts\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as References from \"effect/References\";\nimport { Argument, Command, Flag, GlobalFlag } from \"effect/unstable/cli\";\n\nimport * as EnvironmentAuth from \"../auth/EnvironmentAuth.ts\";\n\nimport {\n  formatIssuedPairingCredential,\n  formatIssuedSession,\n  formatPairingCredentialList,\n  formatSessionList,\n} from \"../cliAuthFormat.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport {\n  authLocationFlags,\n  type CliAuthLocationFlags,\n  DurationFromString,\n  resolveCliAuthConfig,\n} from \"./config.ts\";\n\nconst runWithEnvironmentAuth = <A, E>(\n  flags: CliAuthLocationFlags,\n  run: (environmentAuth: EnvironmentAuth.EnvironmentAuth[\"Service\"]) => Effect.Effect<A, E>,\n  options?: {\n    readonly quietLogs?: boolean;\n  },\n) =>\n  Effect.gen(function* () {\n    const logLevel = yield* GlobalFlag.LogLevel;\n    const config = yield* resolveCliAuthConfig(flags, logLevel);\n    const minimumLogLevel = options?.quietLogs ? \"Error\" : config.logLevel;\n    return yield* Effect.gen(function* () {\n      const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;\n      return yield* run(environmentAuth);\n    }).pipe(\n      Effect.provide(\n        Layer.mergeAll(EnvironmentAuth.runtimeLayer).pipe(\n          Layer.provide(ServerConfig.layer(config)),\n          Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),\n        ),\n      ),\n    );\n  });\n\nconst ttlFlag = Flag.string(\"ttl\").pipe(\n  Flag.withSchema(DurationFromString),\n  Flag.withDescription(\"TTL, for example `5m`, `1h`, `30d`, or `15 minutes`.\"),\n  Flag.optional,\n);\n\nconst jsonFlag = Flag.boolean(\"json\").pipe(\n  Flag.withDescription(\"Emit JSON instead of human-readable output.\"),\n  Flag.withDefault(false),\n);\n\nconst labelFlag = Flag.string(\"label\").pipe(\n  Flag.withDescription(\"Optional human-readable label.\"),\n  Flag.optional,\n);\n\nconst subjectFlag = Flag.string(\"subject\").pipe(\n  Flag.withDescription(\"Optional session subject.\"),\n  Flag.optional,\n);\n\nconst baseUrlFlag = Flag.string(\"base-url\").pipe(\n  Flag.withDescription(\"Optional public base URL used to print a ready `/pair#token=...` link.\"),\n  Flag.optional,\n);\n\nconst tokenOnlyFlag = Flag.boolean(\"token-only\").pipe(\n  Flag.withDescription(\"Print only the issued bearer token.\"),\n  Flag.withDefault(false),\n);\n\nconst pairingCreateCommand = Command.make(\"create\", {\n  ...authLocationFlags,\n  ttl: ttlFlag,\n  label: labelFlag,\n  baseUrl: baseUrlFlag,\n  json: jsonFlag,\n}).pipe(\n  Command.withDescription(\"Issue a new client pairing token.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(\n      flags,\n      (environmentAuth) =>\n        Effect.gen(function* () {\n          const issued = yield* environmentAuth.createPairingLink({\n            scopes: AuthStandardClientScopes,\n            subject: \"one-time-token\",\n            ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),\n            ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),\n          });\n          const output = formatIssuedPairingCredential(issued, {\n            json: flags.json,\n            ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),\n          });\n          yield* Console.log(output);\n        }),\n      {\n        quietLogs: flags.json,\n      },\n    ),\n  ),\n);\n\nconst pairingListCommand = Command.make(\"list\", {\n  ...authLocationFlags,\n  json: jsonFlag,\n}).pipe(\n  Command.withDescription(\"List active client pairing tokens without revealing their secrets.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(\n      flags,\n      (environmentAuth) =>\n        Effect.gen(function* () {\n          const pairingLinks = yield* environmentAuth.listPairingLinks({\n            excludeSubjects: [EnvironmentAuth.INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT],\n          });\n          yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));\n        }),\n      {\n        quietLogs: flags.json,\n      },\n    ),\n  ),\n);\n\nconst pairingRevokeCommand = Command.make(\"revoke\", {\n  ...authLocationFlags,\n  id: Argument.string(\"id\").pipe(Argument.withDescription(\"Pairing credential id to revoke.\")),\n}).pipe(\n  Command.withDescription(\"Revoke an active client pairing token.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(flags, (environmentAuth) =>\n      Effect.gen(function* () {\n        const revoked = yield* environmentAuth.revokePairingLink(flags.id);\n        yield* Console.log(\n          revoked\n            ? `Revoked pairing credential ${flags.id}.\\n`\n            : `No active pairing credential found for ${flags.id}.\\n`,\n        );\n      }),\n    ),\n  ),\n);\n\nconst pairingCommand = Command.make(\"pairing\").pipe(\n  Command.withDescription(\"Manage one-time client pairing tokens.\"),\n  Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),\n);\n\nconst sessionIssueCommand = Command.make(\"issue\", {\n  ...authLocationFlags,\n  ttl: ttlFlag,\n  label: labelFlag,\n  subject: subjectFlag,\n  tokenOnly: tokenOnlyFlag,\n  json: jsonFlag,\n}).pipe(\n  Command.withDescription(\"Issue a scoped bearer access token for headless or remote clients.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(\n      flags,\n      (environmentAuth) =>\n        Effect.gen(function* () {\n          const issued = yield* environmentAuth.issueSession({\n            scopes: AuthAdministrativeScopes,\n            ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),\n            ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),\n            ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),\n          });\n          yield* Console.log(\n            formatIssuedSession(issued, {\n              json: flags.json,\n              tokenOnly: flags.tokenOnly,\n            }),\n          );\n        }),\n      {\n        quietLogs: flags.json || flags.tokenOnly,\n      },\n    ),\n  ),\n);\n\nconst sessionListCommand = Command.make(\"list\", {\n  ...authLocationFlags,\n  json: jsonFlag,\n}).pipe(\n  Command.withDescription(\"List active sessions without revealing bearer tokens.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(\n      flags,\n      (environmentAuth) =>\n        Effect.gen(function* () {\n          const sessions = yield* environmentAuth.listSessions();\n          yield* Console.log(formatSessionList(sessions, { json: flags.json }));\n        }),\n      {\n        quietLogs: flags.json,\n      },\n    ),\n  ),\n);\n\nconst sessionRevokeCommand = Command.make(\"revoke\", {\n  ...authLocationFlags,\n  sessionId: Argument.string(\"session-id\").pipe(\n    Argument.withDescription(\"Session id to revoke.\"),\n    Argument.withSchema(AuthSessionId),\n  ),\n}).pipe(\n  Command.withDescription(\"Revoke an active session.\"),\n  Command.withHandler((flags) =>\n    runWithEnvironmentAuth(flags, (environmentAuth) =>\n      Effect.gen(function* () {\n        const revoked = yield* environmentAuth.revokeSession(flags.sessionId);\n        yield* Console.log(\n          revoked\n            ? `Revoked session ${flags.sessionId}.\\n`\n            : `No active session found for ${flags.sessionId}.\\n`,\n        );\n      }),\n    ),\n  ),\n);\n\nconst sessionCommand = Command.make(\"session\").pipe(\n  Command.withDescription(\"Manage bearer sessions.\"),\n  Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),\n);\n\nexport const authCommand = Command.make(\"auth\").pipe(\n  Command.withDescription(\"Manage the local auth control plane for headless deployments.\"),\n  Command.withSubcommands([pairingCommand, sessionCommand]),\n);\n","/**\n * Where development state lives, and how to keep it away from the shared\n * `~/.synaptic` that a user's installed Synaptic Code runs against.\n *\n * A linked git worktree gets its own (gitignored) `.synaptic`: feature work in a\n * throwaway branch must not share a database with the real app, and an ambient\n * `SYNAPTIC_HOME` counts as an explicit base dir — flipping the state directory\n * from `<base>/dev` to `<base>/userdata`, the live production database.\n */\n\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\n\n/**\n * A `.git` file points at the real git directory. A linked worktree's lives at\n * `<common-dir>/worktrees/<name>`; a submodule's at\n * `<super-git-dir>/modules/<name>`. Both are files, so the pointer — not the\n * file-vs-directory distinction alone — is what identifies a worktree.\n *\n * The common dir is not necessarily named `.git`: a worktree of a bare repo\n * points at `<repo>.git/worktrees/<name>`, and `$GIT_COMMON_DIR` can be\n * anything. So match on the `worktrees/<name>` tail, which git always uses,\n * rather than on the name of the directory containing it.\n */\nconst pointsAtLinkedWorktree = (gitFileContents: string, path: Path.Path): boolean => {\n  const gitdir = gitFileContents\n    .split(/\\r?\\n/)\n    .map((line) => line.trim())\n    .find((line) => line.startsWith(\"gitdir:\"))\n    ?.slice(\"gitdir:\".length)\n    .trim();\n  if (gitdir === undefined || gitdir.length === 0) {\n    return false;\n  }\n  // Compare as path segments so a directory merely named `…worktrees…` cannot\n  // match as a substring. Trailing separators normalize away first.\n  const segments = path\n    .normalize(gitdir.replaceAll(\"\\\\\", \"/\"))\n    .split(/[/\\\\]/)\n    .filter((segment) => segment.length > 0);\n  // `<common-dir>/worktrees/<name>`: `worktrees` is the penultimate segment,\n  // and something must precede it. This excludes `<git-dir>/modules/<name>`.\n  return segments.length >= 3 && segments.at(-2) === \"worktrees\";\n};\n\n/**\n * The path of the linked git worktree containing `cwd`, or undefined when\n * `cwd` is not inside one. Git marks a linked worktree by making `.git` a file\n * whose `gitdir:` points into the repository's `.git/worktrees`.\n *\n * Walks up to the repository root, so running from a subdirectory resolves the\n * same worktree as running from the top.\n */\nexport const resolveGitWorktreePath = (\n  cwd: string,\n): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>\n  Effect.gen(function* () {\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n\n    let directory = path.resolve(cwd);\n    for (;;) {\n      const gitPath = path.join(directory, \".git\");\n      const info = yield* fileSystem.stat(gitPath).pipe(Effect.option);\n      if (Option.isSome(info)) {\n        // A directory means the main checkout. Stop either way: nesting one\n        // repository inside another does not make the outer one this root.\n        if (info.value.type !== \"File\") {\n          return undefined;\n        }\n        // A submodule also has a `.git` file, but it is not a worktree of this\n        // repository and gets no worktree-local home.\n        const contents = yield* fileSystem\n          .readFileString(gitPath)\n          .pipe(Effect.orElseSucceed(() => \"\"));\n        return pointsAtLinkedWorktree(contents, path) ? directory : undefined;\n      }\n      const parent = path.dirname(directory);\n      if (parent === directory) {\n        return undefined;\n      }\n      directory = parent;\n    }\n  });\n\n/**\n * The worktree-local data directory for `cwd`, or undefined outside a linked\n * worktree. Deliberately does not require the directory to exist yet: falling\n * back because it is missing would send callers at the shared home.\n */\nexport const resolveWorktreeT3Home = (\n  cwd: string,\n): Effect.Effect<string | undefined, never, FileSystem.FileSystem | Path.Path> =>\n  Effect.gen(function* () {\n    const worktreePath = yield* resolveGitWorktreePath(cwd);\n    if (worktreePath === undefined) {\n      return undefined;\n    }\n    const path = yield* Path.Path;\n    return path.join(worktreePath, \".synaptic\");\n  });\n","import { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nexport const DEFAULT_TAILSCALE_SERVE_PORT = 443;\nexport const TAILSCALE_STATUS_TIMEOUT = Duration.millis(1_500);\nexport const TAILSCALE_SERVE_TIMEOUT = Duration.seconds(10);\nexport const TAILSCALE_PROBE_TIMEOUT = Duration.millis(2_500);\n\n// tailscale is a real executable everywhere (`tailscale.exe` on Windows), so\n// it is always spawned directly rather than through cmd.exe shell mode.\nconst tailscaleCommandForPlatform = (platform: NodeJS.Platform): \"tailscale\" | \"tailscale.exe\" =>\n  platform === \"win32\" ? \"tailscale.exe\" : \"tailscale\";\n\nconst TailscaleCommandContext = {\n  executable: Schema.Literals([\"tailscale\", \"tailscale.exe\"]),\n  subcommand: Schema.Literals([\"status\", \"serve\"]),\n  argumentCount: Schema.Number,\n};\n\n/**\n * Failure kinds we can name without quoting the CLI. Anything unrecognized\n * becomes \"unknown\" rather than falling back to raw text — stderr can contain\n * auth keys (`tskey-…`) and node names, and these labels are logged.\n */\nexport const TailscaleStderrDiagnostic = Schema.Literals([\n  \"no-existing-handler\",\n  \"not-logged-in\",\n  \"permission-denied\",\n  \"unknown\",\n]);\nexport type TailscaleStderrDiagnostic = typeof TailscaleStderrDiagnostic.Type;\n\n// Matched against stderr, most specific first. Patterns are deliberately short\n// and anchored on tailscale's own wording.\nconst STDERR_DIAGNOSTIC_PATTERNS: ReadonlyArray<\n  readonly [RegExp, Exclude<TailscaleStderrDiagnostic, \"unknown\">]\n> = [\n  [/handler does not exist/i, \"no-existing-handler\"],\n  [/not logged in|logged out|needs? login/i, \"not-logged-in\"],\n  [/permission denied|access denied|must be root|operation not permitted/i, \"permission-denied\"],\n];\n\n/** Classifies stderr into a safe label, dropping the text itself. */\nexport const stderrDiagnosticOf = (stderr: string): TailscaleStderrDiagnostic | undefined => {\n  if (stderr.trim().length === 0) {\n    return undefined;\n  }\n  return STDERR_DIAGNOSTIC_PATTERNS.find(([pattern]) => pattern.test(stderr))?.[1] ?? \"unknown\";\n};\n\nexport class TailscaleCommandSpawnError extends Schema.TaggedErrorClass<TailscaleCommandSpawnError>()(\n  \"TailscaleCommandSpawnError\",\n  {\n    ...TailscaleCommandContext,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to spawn tailscale ${this.subcommand}.`;\n  }\n}\n\nexport class TailscaleCommandOutputError extends Schema.TaggedErrorClass<TailscaleCommandOutputError>()(\n  \"TailscaleCommandOutputError\",\n  {\n    ...TailscaleCommandContext,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to read output from tailscale ${this.subcommand}.`;\n  }\n}\n\nexport class TailscaleCommandExitError extends Schema.TaggedErrorClass<TailscaleCommandExitError>()(\n  \"TailscaleCommandExitError\",\n  {\n    ...TailscaleCommandContext,\n    exitCode: Schema.Number,\n    stdoutLength: Schema.optional(Schema.Number),\n    stderrLength: Schema.Number,\n    // A classified diagnostic, never raw CLI output. `tailscale` prints auth\n    // keys and node identifiers into stderr, and this field is surfaced in\n    // dev-runner logs — so it carries only a known-safe label from the closed\n    // set below. Callers that need to recognize a specific failure (e.g.\n    // `serve off` on a port with no mapping) match on the label.\n    stderrDiagnostic: Schema.optional(TailscaleStderrDiagnostic),\n  },\n) {\n  override get message(): string {\n    return `tailscale ${this.subcommand} exited with code ${this.exitCode}.`;\n  }\n}\n\nexport class TailscaleCommandTimeoutError extends Schema.TaggedErrorClass<TailscaleCommandTimeoutError>()(\n  \"TailscaleCommandTimeoutError\",\n  {\n    ...TailscaleCommandContext,\n    timeoutMs: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `tailscale ${this.subcommand} timed out after ${this.timeoutMs}ms.`;\n  }\n}\n\nexport const TailscaleCommandError = Schema.Union([\n  TailscaleCommandSpawnError,\n  TailscaleCommandOutputError,\n  TailscaleCommandExitError,\n  TailscaleCommandTimeoutError,\n]);\nexport type TailscaleCommandError = typeof TailscaleCommandError.Type;\n\nexport class TailscaleStatusParseError extends Schema.TaggedErrorClass<TailscaleStatusParseError>()(\n  \"TailscaleStatusParseError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Failed to decode tailscale status JSON.\";\n  }\n}\n\nconst TailscaleStatusSelf = Schema.Struct({\n  DNSName: Schema.optional(Schema.Unknown),\n  TailscaleIPs: Schema.optional(Schema.Unknown),\n});\n\nconst TailscaleStatusJson = Schema.Struct({\n  Self: Schema.optional(TailscaleStatusSelf),\n});\n\nexport type TailscaleStatusSelf = typeof TailscaleStatusSelf.Type;\nexport type TailscaleStatusJson = typeof TailscaleStatusJson.Type;\n\nexport interface TailscaleStatus {\n  readonly magicDnsName: string | null;\n  readonly tailnetIpv4Addresses: readonly string[];\n}\n\nconst collectStdout = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>\n  stream.pipe(\n    Stream.decodeText(),\n    Stream.runFold(\n      () => \"\",\n      (acc, chunk) => acc + chunk,\n    ),\n  );\n\nconst collectStderr = collectStdout;\n\nconst decodeTailscaleStatusJson = Schema.decodeEffect(Schema.fromJsonString(TailscaleStatusJson));\n\nfunction normalizeMagicDnsName(status: TailscaleStatusJson): string | null {\n  const dnsName = status.Self?.DNSName;\n  if (typeof dnsName !== \"string\") {\n    return null;\n  }\n\n  const normalized = dnsName.trim().replace(/\\.$/u, \"\");\n  return normalized.length > 0 ? normalized : null;\n}\n\nexport const parseTailscaleMagicDnsName = (\n  rawStatusJson: string,\n): Effect.Effect<string | null, TailscaleStatusParseError> =>\n  decodeTailscaleStatusJson(rawStatusJson).pipe(\n    Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),\n    Effect.map(normalizeMagicDnsName),\n  );\n\nexport function isTailscaleIpv4Address(address: string): boolean {\n  const parts = address.split(\".\");\n  if (parts.length !== 4) {\n    return false;\n  }\n  const [first, second, third, fourth] = parts.map((part) => Number.parseInt(part, 10));\n  if (\n    first === undefined ||\n    second === undefined ||\n    third === undefined ||\n    fourth === undefined ||\n    [first, second, third, fourth].some((part) => !Number.isInteger(part) || part < 0 || part > 255)\n  ) {\n    return false;\n  }\n  return first === 100 && second >= 64 && second <= 127;\n}\n\nexport const parseTailscaleStatus = (\n  rawStatusJson: string,\n): Effect.Effect<TailscaleStatus, TailscaleStatusParseError> =>\n  decodeTailscaleStatusJson(rawStatusJson).pipe(\n    Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),\n    Effect.map((parsed) => {\n      const rawIps = parsed.Self?.TailscaleIPs;\n      const tailnetIpv4Addresses: Array<string> = [];\n      if (Array.isArray(rawIps)) {\n        for (const address of rawIps) {\n          if (typeof address === \"string\" && isTailscaleIpv4Address(address)) {\n            tailnetIpv4Addresses.push(address);\n          }\n        }\n      }\n\n      return {\n        magicDnsName: normalizeMagicDnsName(parsed),\n        tailnetIpv4Addresses,\n      };\n    }),\n  );\n\nexport const readTailscaleStatus = Effect.gen(function* () {\n  const args = [\"status\", \"--json\"];\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const hostPlatform = yield* HostProcessPlatform;\n  const executable = tailscaleCommandForPlatform(hostPlatform);\n  const commandContext = {\n    executable,\n    subcommand: \"status\" as const,\n    argumentCount: args.length,\n  };\n  return yield* Effect.gen(function* () {\n    const child = yield* spawner\n      .spawn(ChildProcess.make(executable, args))\n      .pipe(\n        Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),\n      );\n    const [stdout, stderr, exitCode] = yield* Effect.all(\n      [\n        collectStdout(child.stdout),\n        collectStderr(child.stderr),\n        child.exitCode.pipe(Effect.map(Number)),\n      ],\n      { concurrency: \"unbounded\" },\n    ).pipe(\n      Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),\n    );\n    if (exitCode !== 0) {\n      return yield* new TailscaleCommandExitError({\n        ...commandContext,\n        exitCode,\n        stdoutLength: stdout.length,\n        stderrLength: stderr.length,\n        ...(stderrDiagnosticOf(stderr) !== undefined\n          ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }\n          : {}),\n      });\n    }\n    return yield* parseTailscaleStatus(stdout);\n  }).pipe(\n    Effect.scoped,\n    Effect.timeout(TAILSCALE_STATUS_TIMEOUT),\n    Effect.catchTags({\n      TimeoutError: (cause) =>\n        Effect.fail(\n          new TailscaleCommandTimeoutError({\n            ...commandContext,\n            timeoutMs: Duration.toMillis(TAILSCALE_STATUS_TIMEOUT),\n            cause,\n          }),\n        ),\n    }),\n  );\n});\n\nexport function buildTailscaleHttpsBaseUrl(input: {\n  readonly magicDnsName: string;\n  readonly servePort?: number;\n}): string {\n  const url = new URL(`https://${input.magicDnsName}`);\n  const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;\n  if (servePort !== DEFAULT_TAILSCALE_SERVE_PORT) {\n    url.port = String(servePort);\n  }\n  url.pathname = \"/\";\n  return url.toString();\n}\n\nconst runTailscaleCommand = (\n  args: readonly string[],\n  timeoutInput: Duration.Input,\n): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>\n  Effect.gen(function* () {\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const hostPlatform = yield* HostProcessPlatform;\n    const executable = tailscaleCommandForPlatform(hostPlatform);\n    const commandContext = {\n      executable,\n      subcommand: \"serve\" as const,\n      argumentCount: args.length,\n    };\n    const timeout = Duration.fromInputUnsafe(timeoutInput);\n    return yield* Effect.gen(function* () {\n      const child = yield* spawner\n        .spawn(ChildProcess.make(executable, args))\n        .pipe(\n          Effect.mapError((cause) => new TailscaleCommandSpawnError({ ...commandContext, cause })),\n        );\n      const [stderr, exitCode] = yield* Effect.all(\n        [collectStderr(child.stderr), child.exitCode.pipe(Effect.map(Number))],\n        { concurrency: \"unbounded\" },\n      ).pipe(\n        Effect.mapError((cause) => new TailscaleCommandOutputError({ ...commandContext, cause })),\n      );\n      if (exitCode !== 0) {\n        return yield* new TailscaleCommandExitError({\n          ...commandContext,\n          exitCode,\n          stderrLength: stderr.length,\n          ...(stderrDiagnosticOf(stderr) !== undefined\n            ? { stderrDiagnostic: stderrDiagnosticOf(stderr) }\n            : {}),\n        });\n      }\n    }).pipe(\n      Effect.scoped,\n      Effect.timeout(timeout),\n      Effect.catchTags({\n        TimeoutError: (cause) =>\n          Effect.fail(\n            new TailscaleCommandTimeoutError({\n              ...commandContext,\n              timeoutMs: Duration.toMillis(timeout),\n              cause,\n            }),\n          ),\n      }),\n    );\n  });\n\nexport const ensureTailscaleServe = (input: {\n  readonly localPort: number;\n  readonly servePort?: number;\n  readonly localHost?: string;\n}): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> => {\n  const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;\n  const localHost = input.localHost ?? \"127.0.0.1\";\n  const args = [\"serve\", \"--bg\", `--https=${servePort}`, `http://${localHost}:${input.localPort}`];\n  return runTailscaleCommand(args, TAILSCALE_SERVE_TIMEOUT);\n};\n\nexport const disableTailscaleServe = (\n  input: {\n    readonly servePort?: number;\n  } = {},\n): Effect.Effect<void, TailscaleCommandError, ChildProcessSpawner.ChildProcessSpawner> =>\n  Effect.gen(function* () {\n    const servePort = input.servePort ?? DEFAULT_TAILSCALE_SERVE_PORT;\n    return yield* runTailscaleCommand(\n      [\"serve\", `--https=${servePort}`, \"off\"],\n      TAILSCALE_SERVE_TIMEOUT,\n    );\n  });\n\nexport const probeTailscaleHttpsEndpoint = (input: {\n  readonly baseUrl: string;\n  readonly timeout?: Duration.Input;\n}): Effect.Effect<boolean, never, HttpClient.HttpClient> =>\n  Effect.gen(function* () {\n    const client = yield* HttpClient.HttpClient;\n    const response = yield* Effect.gen(function* () {\n      const url = new URL(\"/.well-known/t3/environment\", input.baseUrl);\n      const request = HttpClientRequest.get(url.toString());\n      return yield* client.execute(request);\n    }).pipe(Effect.timeoutOption(input.timeout ?? TAILSCALE_PROBE_TIMEOUT));\n\n    return Option.match(response, {\n      onNone: () => false,\n      onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,\n    });\n  }).pipe(Effect.orElseSucceed(() => false));\n\nexport const resolveTailscaleHttpsBaseUrl = (\n  input: {\n    readonly servePort?: number;\n  } = {},\n): Effect.Effect<\n  string | null,\n  TailscaleCommandError | TailscaleStatusParseError,\n  ChildProcessSpawner.ChildProcessSpawner\n> =>\n  readTailscaleStatus.pipe(\n    Effect.map((status) =>\n      status.magicDnsName\n        ? buildTailscaleHttpsBaseUrl({\n            magicDnsName: status.magicDnsName,\n            ...(input.servePort === undefined ? {} : { servePort: input.servePort }),\n          })\n        : null,\n    ),\n  );\n","import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\n\nexport const writeFileStringAtomically = (input: {\n  readonly filePath: string;\n  readonly contents: string;\n}) =>\n  Effect.scoped(\n    Effect.gen(function* () {\n      const fs = yield* FileSystem.FileSystem;\n      const path = yield* Path.Path;\n      const targetDirectory = path.dirname(input.filePath);\n\n      yield* fs.makeDirectory(targetDirectory, { recursive: true });\n      const tempDirectory = yield* fs.makeTempDirectoryScoped({\n        directory: targetDirectory,\n        prefix: `${path.basename(input.filePath)}.`,\n      });\n      const tempPath = path.join(tempDirectory, \"contents.tmp\");\n\n      yield* fs.writeFileString(tempPath, input.contents);\n      yield* fs.rename(tempPath, input.filePath);\n    }),\n  );\n","/* oxlint-disable eslint/no-useless-escape */\n/*\n * QR Code generator library (TypeScript)\n *\n * Copyright (c) Project Nayuki. (MIT License)\n * https://www.nayuki.io/page/qr-code-generator-library\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of\n * this software and associated documentation files (the \"Software\"), to deal in\n * the Software without restriction, including without limitation the rights to\n * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n * the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n * - The above copyright notice and this permission notice shall be included in\n *   all copies or substantial portions of the Software.\n * - The Software is provided \"as is\", without warranty of any kind, express or\n *   implied, including but not limited to the warranties of merchantability,\n *   fitness for a particular purpose and noninfringement. In no event shall the\n *   authors or copyright holders be liable for any claim, damages or other\n *   liability, whether in an action of contract, tort or otherwise, arising from,\n *   out of or in connection with the Software or the use or other dealings in the\n *   Software.\n */\n\n\"use strict\";\n\ntype bit = number;\ntype byte = number;\ntype int = number;\n\n/*---- QR Code symbol class ----*/\n\n/*\n * A QR Code symbol, which is a type of two-dimension barcode.\n * Invented by Denso Wave and described in the ISO/IEC 18004 standard.\n * Instances of this class represent an immutable square grid of dark and light cells.\n * The class provides static factory functions to create a QR Code from text or binary data.\n * The class covers the QR Code Model 2 specification, supporting all versions (sizes)\n * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.\n *\n * Ways to create a QR Code object:\n * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().\n * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().\n * - Low level: Custom-make the array of data codeword bytes (including\n *   segment headers and final padding, excluding error correction codewords),\n *   supply the appropriate version number, and call the QrCode() constructor.\n * (Note that all ways require supplying the desired error correction level.)\n */\nexport class QrCode {\n  public static Ecc: typeof QrCodeEcc;\n\n  /*-- Static factory functions (high level) --*/\n\n  // Returns a QR Code representing the given Unicode text string at the given error correction level.\n  // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer\n  // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible\n  // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the\n  // ecl argument if it can be done without increasing the version.\n  public static encodeText(text: string, ecl: QrCodeEcc): QrCode {\n    const segs: Array<QrSegment> = QrSegment.makeSegments(text);\n    return QrCode.encodeSegments(segs, ecl);\n  }\n\n  // Returns a QR Code representing the given binary data at the given error correction level.\n  // This function always encodes using the binary segment mode, not any text mode. The maximum number of\n  // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.\n  // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.\n  public static encodeBinary(data: Readonly<Array<byte>>, ecl: QrCodeEcc): QrCode {\n    const seg: QrSegment = QrSegment.makeBytes(data);\n    return QrCode.encodeSegments([seg], ecl);\n  }\n\n  /*-- Static factory functions (mid level) --*/\n\n  // Returns a QR Code representing the given segments with the given encoding parameters.\n  // The smallest possible QR Code version within the given range is automatically\n  // chosen for the output. Iff boostEcl is true, then the ECC level of the result\n  // may be higher than the ecl argument if it can be done without increasing the\n  // version. The mask number is either between 0 to 7 (inclusive) to force that\n  // mask, or -1 to automatically choose an appropriate mask (which may be slow).\n  // This function allows the user to create a custom sequence of segments that switches\n  // between modes (such as alphanumeric and byte) to encode text in less space.\n  // This is a mid-level API; the high-level API is encodeText() and encodeBinary().\n  public static encodeSegments(\n    segs: Readonly<Array<QrSegment>>,\n    ecl: QrCodeEcc,\n    minVersion: int = 1,\n    maxVersion: int = 40,\n    mask: int = -1,\n    boostEcl: boolean = true,\n  ): QrCode {\n    if (\n      !(\n        QrCode.MIN_VERSION <= minVersion &&\n        minVersion <= maxVersion &&\n        maxVersion <= QrCode.MAX_VERSION\n      ) ||\n      mask < -1 ||\n      mask > 7\n    )\n      throw new RangeError(\"Invalid value\");\n\n    // Find the minimal version number to use\n    let version: int;\n    let dataUsedBits: int;\n    for (version = minVersion; ; version++) {\n      const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available\n      const usedBits: number = QrSegment.getTotalBits(segs, version);\n      if (usedBits <= dataCapacityBits) {\n        dataUsedBits = usedBits;\n        break; // This version number is found to be suitable\n      }\n      if (version >= maxVersion)\n        // All versions in the range could not fit the given data\n        throw new RangeError(\"Data too long\");\n    }\n\n    // Increase the error correction level while the data still fits in the current version number\n    for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) {\n      // From low to high\n      if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) ecl = newEcl;\n    }\n\n    // Concatenate all segments to create the data bit string\n    let bb: Array<bit> = [];\n    for (const seg of segs) {\n      appendBits(seg.mode.modeBits, 4, bb);\n      appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);\n      for (const b of seg.getData()) bb.push(b);\n    }\n    assert(bb.length == dataUsedBits);\n\n    // Add terminator and pad up to a byte if applicable\n    const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8;\n    assert(bb.length <= dataCapacityBits);\n    appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);\n    appendBits(0, (8 - (bb.length % 8)) % 8, bb);\n    assert(bb.length % 8 == 0);\n\n    // Pad with alternating bytes until data capacity is reached\n    for (let padByte = 0xec; bb.length < dataCapacityBits; padByte ^= 0xec ^ 0x11)\n      appendBits(padByte, 8, bb);\n\n    // Pack bits into bytes in big endian\n    let dataCodewords: Array<byte> = [];\n    while (dataCodewords.length * 8 < bb.length) dataCodewords.push(0);\n    bb.forEach((b: bit, i: int) => (dataCodewords[i >>> 3]! |= b << (7 - (i & 7))));\n\n    // Create the QR Code object\n    return new QrCode(version, ecl, dataCodewords, mask);\n  }\n\n  /*-- Fields --*/\n\n  // The width and height of this QR Code, measured in modules, between\n  // 21 and 177 (inclusive). This is equal to version * 4 + 17.\n  public readonly version: int;\n  public readonly errorCorrectionLevel: QrCodeEcc;\n  public readonly size: int;\n\n  // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).\n  // Even if a QR Code is created with automatic masking requested (mask = -1),\n  // the resulting object still has a mask value between 0 and 7.\n  public readonly mask: int;\n\n  // The modules of this QR Code (false = light, true = dark).\n  // Immutable after constructor finishes. Accessed through getModule().\n  private readonly modules: Array<Array<boolean>> = [];\n\n  // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.\n  private readonly isFunction: Array<Array<boolean>> = [];\n\n  /*-- Constructor (low level) and fields --*/\n\n  // Creates a new QR Code with the given version number,\n  // error correction level, data codeword bytes, and mask number.\n  // This is a low-level API that most users should not use directly.\n  // A mid-level API is the encodeSegments() function.\n  public constructor(\n    // The version number of this QR Code, which is between 1 and 40 (inclusive).\n    // This determines the size of this barcode.\n    version: int,\n\n    // The error correction level used in this QR Code.\n    errorCorrectionLevel: QrCodeEcc,\n\n    dataCodewords: Readonly<Array<byte>>,\n\n    msk: int,\n  ) {\n    this.version = version;\n    this.errorCorrectionLevel = errorCorrectionLevel;\n\n    // Check scalar arguments\n    if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)\n      throw new RangeError(\"Version value out of range\");\n    if (msk < -1 || msk > 7) throw new RangeError(\"Mask value out of range\");\n    this.size = version * 4 + 17;\n\n    // Initialize both grids to be size*size arrays of Boolean false\n    let row: Array<boolean> = [];\n    for (let i = 0; i < this.size; i++) row.push(false);\n    for (let i = 0; i < this.size; i++) {\n      this.modules.push(row.slice()); // Initially all light\n      this.isFunction.push(row.slice());\n    }\n\n    // Compute ECC, draw modules\n    this.drawFunctionPatterns();\n    const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords);\n    this.drawCodewords(allCodewords);\n\n    // Do masking\n    if (msk == -1) {\n      // Automatically choose best mask\n      let minPenalty: int = 1000000000;\n      for (let i = 0; i < 8; i++) {\n        this.applyMask(i);\n        this.drawFormatBits(i);\n        const penalty: int = this.getPenaltyScore();\n        if (penalty < minPenalty) {\n          msk = i;\n          minPenalty = penalty;\n        }\n        this.applyMask(i); // Undoes the mask due to XOR\n      }\n    }\n    assert(0 <= msk && msk <= 7);\n    this.mask = msk;\n    this.applyMask(msk); // Apply the final choice of mask\n    this.drawFormatBits(msk); // Overwrite old format bits\n\n    this.isFunction = [];\n  }\n\n  /*-- Accessor methods --*/\n\n  // Returns the color of the module (pixel) at the given coordinates, which is false\n  // for light or true for dark. The top left corner has the coordinates (x=0, y=0).\n  // If the given coordinates are out of bounds, then false (light) is returned.\n  public getModule(x: int, y: int): boolean {\n    return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y]![x]!;\n  }\n\n  /*-- Private helper methods for constructor: Drawing function modules --*/\n\n  // Reads this object's version field, and draws and marks all function modules.\n  private drawFunctionPatterns(): void {\n    // Draw horizontal and vertical timing patterns\n    for (let i = 0; i < this.size; i++) {\n      this.setFunctionModule(6, i, i % 2 == 0);\n      this.setFunctionModule(i, 6, i % 2 == 0);\n    }\n\n    // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)\n    this.drawFinderPattern(3, 3);\n    this.drawFinderPattern(this.size - 4, 3);\n    this.drawFinderPattern(3, this.size - 4);\n\n    // Draw numerous alignment patterns\n    const alignPatPos: Array<int> = this.getAlignmentPatternPositions();\n    const numAlign: int = alignPatPos.length;\n    for (let i = 0; i < numAlign; i++) {\n      for (let j = 0; j < numAlign; j++) {\n        // Don't draw on the three finder corners\n        if (!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0)))\n          this.drawAlignmentPattern(alignPatPos[i]!, alignPatPos[j]!);\n      }\n    }\n\n    // Draw configuration data\n    this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor\n    this.drawVersion();\n  }\n\n  // Draws two copies of the format bits (with its own error correction code)\n  // based on the given mask and this object's error correction level field.\n  private drawFormatBits(mask: int): void {\n    // Calculate error correction code and pack bits\n    const data: int = (this.errorCorrectionLevel.formatBits << 3) | mask; // errCorrLvl is uint2, mask is uint3\n    let rem: int = data;\n    for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);\n    const bits = ((data << 10) | rem) ^ 0x5412; // uint15\n    assert(bits >>> 15 == 0);\n\n    // Draw first copy\n    for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i));\n    this.setFunctionModule(8, 7, getBit(bits, 6));\n    this.setFunctionModule(8, 8, getBit(bits, 7));\n    this.setFunctionModule(7, 8, getBit(bits, 8));\n    for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i));\n\n    // Draw second copy\n    for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));\n    for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));\n    this.setFunctionModule(8, this.size - 8, true); // Always dark\n  }\n\n  // Draws two copies of the version bits (with its own error correction code),\n  // based on this object's version field, iff 7 <= version <= 40.\n  private drawVersion(): void {\n    if (this.version < 7) return;\n\n    // Calculate error correction code and pack bits\n    let rem: int = this.version; // version is uint6, in the range [7, 40]\n    for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);\n    const bits: int = (this.version << 12) | rem; // uint18\n    assert(bits >>> 18 == 0);\n\n    // Draw two copies\n    for (let i = 0; i < 18; i++) {\n      const color: boolean = getBit(bits, i);\n      const a: int = this.size - 11 + (i % 3);\n      const b: int = Math.floor(i / 3);\n      this.setFunctionModule(a, b, color);\n      this.setFunctionModule(b, a, color);\n    }\n  }\n\n  // Draws a 9*9 finder pattern including the border separator,\n  // with the center module at (x, y). Modules can be out of bounds.\n  private drawFinderPattern(x: int, y: int): void {\n    for (let dy = -4; dy <= 4; dy++) {\n      for (let dx = -4; dx <= 4; dx++) {\n        const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm\n        const xx: int = x + dx;\n        const yy: int = y + dy;\n        if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)\n          this.setFunctionModule(xx, yy, dist != 2 && dist != 4);\n      }\n    }\n  }\n\n  // Draws a 5*5 alignment pattern, with the center module\n  // at (x, y). All modules must be in bounds.\n  private drawAlignmentPattern(x: int, y: int): void {\n    for (let dy = -2; dy <= 2; dy++) {\n      for (let dx = -2; dx <= 2; dx++)\n        this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);\n    }\n  }\n\n  // Sets the color of a module and marks it as a function module.\n  // Only used by the constructor. Coordinates must be in bounds.\n  private setFunctionModule(x: int, y: int, isDark: boolean): void {\n    this.modules[y]![x] = isDark;\n    this.isFunction[y]![x] = true;\n  }\n\n  /*-- Private helper methods for constructor: Codewords and masking --*/\n\n  // Returns a new byte string representing the given data with the appropriate error correction\n  // codewords appended to it, based on this object's version and error correction level.\n  private addEccAndInterleave(data: Readonly<Array<byte>>): Array<byte> {\n    const ver: int = this.version;\n    const ecl: QrCodeEcc = this.errorCorrectionLevel;\n    if (data.length != QrCode.getNumDataCodewords(ver, ecl))\n      throw new RangeError(\"Invalid argument\");\n\n    // Calculate parameter numbers\n    const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal]![ver]!;\n    const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal]![ver]!;\n    const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8);\n    const numShortBlocks: int = numBlocks - (rawCodewords % numBlocks);\n    const shortBlockLen: int = Math.floor(rawCodewords / numBlocks);\n\n    // Split data into blocks and append ECC to each block\n    let blocks: Array<Array<byte>> = [];\n    const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen);\n    for (let i = 0, k = 0; i < numBlocks; i++) {\n      let dat: Array<byte> = data.slice(\n        k,\n        k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1),\n      );\n      k += dat.length;\n      const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv);\n      if (i < numShortBlocks) dat.push(0);\n      blocks.push(dat.concat(ecc));\n    }\n\n    // Interleave (not concatenate) the bytes from every block into a single sequence\n    let result: Array<byte> = [];\n    for (let i = 0; i < blocks[0]!.length; i++) {\n      blocks.forEach((block, j) => {\n        // Skip the padding byte in short blocks\n        if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]!);\n      });\n    }\n    assert(result.length == rawCodewords);\n    return result;\n  }\n\n  // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire\n  // data area of this QR Code. Function modules need to be marked off before this is called.\n  private drawCodewords(data: Readonly<Array<byte>>): void {\n    if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))\n      throw new RangeError(\"Invalid argument\");\n    let i: int = 0; // Bit index into the data\n    // Do the funny zigzag scan\n    for (let right = this.size - 1; right >= 1; right -= 2) {\n      // Index of right column in each column pair\n      if (right == 6) right = 5;\n      for (let vert = 0; vert < this.size; vert++) {\n        // Vertical counter\n        for (let j = 0; j < 2; j++) {\n          const x: int = right - j; // Actual x coordinate\n          const upward: boolean = ((right + 1) & 2) == 0;\n          const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate\n          if (!this.isFunction[y]![x]! && i < data.length * 8) {\n            this.modules[y]![x] = getBit(data[i >>> 3]!, 7 - (i & 7));\n            i++;\n          }\n          // If this QR Code has any remainder bits (0 to 7), they were assigned as\n          // 0/false/light by the constructor and are left unchanged by this method\n        }\n      }\n    }\n    assert(i == data.length * 8);\n  }\n\n  // XORs the codeword modules in this QR Code with the given mask pattern.\n  // The function modules must be marked and the codeword bits must be drawn\n  // before masking. Due to the arithmetic of XOR, calling applyMask() with\n  // the same mask value a second time will undo the mask. A final well-formed\n  // QR Code needs exactly one (not zero, two, etc.) mask applied.\n  private applyMask(mask: int): void {\n    if (mask < 0 || mask > 7) throw new RangeError(\"Mask value out of range\");\n    for (let y = 0; y < this.size; y++) {\n      for (let x = 0; x < this.size; x++) {\n        let invert: boolean;\n        switch (mask) {\n          case 0:\n            invert = (x + y) % 2 == 0;\n            break;\n          case 1:\n            invert = y % 2 == 0;\n            break;\n          case 2:\n            invert = x % 3 == 0;\n            break;\n          case 3:\n            invert = (x + y) % 3 == 0;\n            break;\n          case 4:\n            invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;\n            break;\n          case 5:\n            invert = ((x * y) % 2) + ((x * y) % 3) == 0;\n            break;\n          case 6:\n            invert = (((x * y) % 2) + ((x * y) % 3)) % 2 == 0;\n            break;\n          case 7:\n            invert = (((x + y) % 2) + ((x * y) % 3)) % 2 == 0;\n            break;\n          default:\n            throw new Error(\"Unreachable\");\n        }\n        if (!this.isFunction[y]![x]! && invert) this.modules[y]![x] = !this.modules[y]![x]!;\n      }\n    }\n  }\n\n  // Calculates and returns the penalty score based on state of this QR Code's current modules.\n  // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.\n  private getPenaltyScore(): int {\n    let result: int = 0;\n\n    // Adjacent modules in row having same color, and finder-like patterns\n    for (let y = 0; y < this.size; y++) {\n      let runColor = false;\n      let runX = 0;\n      let runHistory = [0, 0, 0, 0, 0, 0, 0];\n      for (let x = 0; x < this.size; x++) {\n        if (this.modules[y]![x] === runColor) {\n          runX++;\n          if (runX == 5) result += QrCode.PENALTY_N1;\n          else if (runX > 5) result++;\n        } else {\n          this.finderPenaltyAddHistory(runX, runHistory);\n          if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;\n          runColor = this.modules[y]![x]!;\n          runX = 1;\n        }\n      }\n      result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;\n    }\n    // Adjacent modules in column having same color, and finder-like patterns\n    for (let x = 0; x < this.size; x++) {\n      let runColor = false;\n      let runY = 0;\n      let runHistory = [0, 0, 0, 0, 0, 0, 0];\n      for (let y = 0; y < this.size; y++) {\n        if (this.modules[y]![x] === runColor) {\n          runY++;\n          if (runY == 5) result += QrCode.PENALTY_N1;\n          else if (runY > 5) result++;\n        } else {\n          this.finderPenaltyAddHistory(runY, runHistory);\n          if (!runColor) result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;\n          runColor = this.modules[y]![x]!;\n          runY = 1;\n        }\n      }\n      result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;\n    }\n\n    // 2*2 blocks of modules having same color\n    for (let y = 0; y < this.size - 1; y++) {\n      for (let x = 0; x < this.size - 1; x++) {\n        const color: boolean = this.modules[y]![x]!;\n        if (\n          color == this.modules[y]![x + 1]! &&\n          color == this.modules[y + 1]![x]! &&\n          color == this.modules[y + 1]![x + 1]!\n        )\n          result += QrCode.PENALTY_N2;\n      }\n    }\n\n    // Balance of dark and light modules\n    let dark: int = 0;\n    for (const row of this.modules) dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);\n    const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2\n    // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%\n    const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;\n    assert(0 <= k && k <= 9);\n    result += k * QrCode.PENALTY_N4;\n    assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4\n    return result;\n  }\n\n  /*-- Private helper functions --*/\n\n  // Returns an ascending list of positions of alignment patterns for this version number.\n  // Each position is in the range [0,177), and are used on both the x and y axes.\n  // This could be implemented as lookup table of 40 variable-length lists of integers.\n  private getAlignmentPatternPositions(): Array<int> {\n    if (this.version == 1) return [];\n    else {\n      const numAlign: int = Math.floor(this.version / 7) + 2;\n      const step: int =\n        this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;\n      let result: Array<int> = [6];\n      for (let pos = this.size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos);\n      return result;\n    }\n  }\n\n  // Returns the number of data bits that can be stored in a QR Code of the given version number, after\n  // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.\n  // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.\n  private static getNumRawDataModules(ver: int): int {\n    if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)\n      throw new RangeError(\"Version number out of range\");\n    let result: int = (16 * ver + 128) * ver + 64;\n    if (ver >= 2) {\n      const numAlign: int = Math.floor(ver / 7) + 2;\n      result -= (25 * numAlign - 10) * numAlign - 55;\n      if (ver >= 7) result -= 36;\n    }\n    assert(208 <= result && result <= 29648);\n    return result;\n  }\n\n  // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any\n  // QR Code of the given version number and error correction level, with remainder bits discarded.\n  // This stateless pure function could be implemented as a (40*4)-cell lookup table.\n  private static getNumDataCodewords(ver: int, ecl: QrCodeEcc): int {\n    return (\n      Math.floor(QrCode.getNumRawDataModules(ver) / 8) -\n      QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal]![ver]! *\n        QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal]![ver]!\n    );\n  }\n\n  // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be\n  // implemented as a lookup table over all possible parameter values, instead of as an algorithm.\n  private static reedSolomonComputeDivisor(degree: int): Array<byte> {\n    if (degree < 1 || degree > 255) throw new RangeError(\"Degree out of range\");\n    // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.\n    // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].\n    let result: Array<byte> = [];\n    for (let i = 0; i < degree - 1; i++) result.push(0);\n    result.push(1); // Start off with the monomial x^0\n\n    // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),\n    // and drop the highest monomial term which is always 1x^degree.\n    // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).\n    let root = 1;\n    for (let i = 0; i < degree; i++) {\n      // Multiply the current product by (x - r^i)\n      for (let j = 0; j < result.length; j++) {\n        result[j] = QrCode.reedSolomonMultiply(result[j]!, root);\n        if (j + 1 < result.length) result[j]! ^= result[j + 1]!;\n      }\n      root = QrCode.reedSolomonMultiply(root, 0x02);\n    }\n    return result;\n  }\n\n  // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.\n  private static reedSolomonComputeRemainder(\n    data: Readonly<Array<byte>>,\n    divisor: Readonly<Array<byte>>,\n  ): Array<byte> {\n    let result: Array<byte> = divisor.map((_) => 0);\n    for (const b of data) {\n      // Polynomial division\n      const factor: byte = b ^ (result.shift() as byte);\n      result.push(0);\n      divisor.forEach((coef, i) => (result[i]! ^= QrCode.reedSolomonMultiply(coef, factor)));\n    }\n    return result;\n  }\n\n  // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result\n  // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.\n  private static reedSolomonMultiply(x: byte, y: byte): byte {\n    if (x >>> 8 != 0 || y >>> 8 != 0) throw new RangeError(\"Byte out of range\");\n    // Russian peasant multiplication\n    let z: int = 0;\n    for (let i = 7; i >= 0; i--) {\n      z = (z << 1) ^ ((z >>> 7) * 0x11d);\n      z ^= ((y >>> i) & 1) * x;\n    }\n    assert(z >>> 8 == 0);\n    return z as byte;\n  }\n\n  // Can only be called immediately after a light run is added, and\n  // returns either 0, 1, or 2. A helper function for getPenaltyScore().\n  private finderPenaltyCountPatterns(runHistory: Readonly<Array<int>>): int {\n    const n: int = runHistory[1]!;\n    assert(n <= this.size * 3);\n    const core: boolean =\n      n > 0 &&\n      runHistory[2] === n &&\n      runHistory[3] === n * 3 &&\n      runHistory[4] === n &&\n      runHistory[5] === n;\n    return (\n      (core && runHistory[0]! >= n * 4 && runHistory[6]! >= n ? 1 : 0) +\n      (core && runHistory[6]! >= n * 4 && runHistory[0]! >= n ? 1 : 0)\n    );\n  }\n\n  // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().\n  private finderPenaltyTerminateAndCount(\n    currentRunColor: boolean,\n    currentRunLength: int,\n    runHistory: Array<int>,\n  ): int {\n    if (currentRunColor) {\n      // Terminate dark run\n      this.finderPenaltyAddHistory(currentRunLength, runHistory);\n      currentRunLength = 0;\n    }\n    currentRunLength += this.size; // Add light border to final run\n    this.finderPenaltyAddHistory(currentRunLength, runHistory);\n    return this.finderPenaltyCountPatterns(runHistory);\n  }\n\n  // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().\n  private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void {\n    if (runHistory[0] === 0) currentRunLength += this.size; // Add light border to initial run\n    runHistory.pop();\n    runHistory.unshift(currentRunLength);\n  }\n\n  /*-- Constants and tables --*/\n\n  // The minimum version number supported in the QR Code Model 2 standard.\n  public static readonly MIN_VERSION: int = 1;\n  // The maximum version number supported in the QR Code Model 2 standard.\n  public static readonly MAX_VERSION: int = 40;\n\n  // For use in getPenaltyScore(), when evaluating which mask is best.\n  private static readonly PENALTY_N1: int = 3;\n  private static readonly PENALTY_N2: int = 3;\n  private static readonly PENALTY_N3: int = 40;\n  private static readonly PENALTY_N4: int = 10;\n\n  private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [\n    // Version: (note that index 0 is for padding, and is set to an illegal value)\n    //0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level\n    [\n      -1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30,\n      30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,\n    ], // Low\n    [\n      -1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28,\n      28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,\n    ], // Medium\n    [\n      -1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30,\n      30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,\n    ], // Quartile\n    [\n      -1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24,\n      30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,\n    ], // High\n  ];\n\n  private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [\n    // Version: (note that index 0 is for padding, and is set to an illegal value)\n    //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40    Error correction level\n    [\n      -1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13,\n      14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25,\n    ], // Low\n    [\n      -1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23,\n      25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49,\n    ], // Medium\n    [\n      -1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29,\n      34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68,\n    ], // Quartile\n    [\n      -1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35,\n      37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81,\n    ], // High\n  ];\n}\n\n// Appends the given number of low-order bits of the given value\n// to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.\nfunction appendBits(val: int, len: int, bb: Array<bit>): void {\n  if (len < 0 || len > 31 || val >>> len != 0) throw new RangeError(\"Value out of range\");\n  for (\n    let i = len - 1;\n    i >= 0;\n    i-- // Append bit by bit\n  )\n    bb.push((val >>> i) & 1);\n}\n\n// Returns true iff the i'th bit of x is set to 1.\nfunction getBit(x: int, i: int): boolean {\n  return ((x >>> i) & 1) != 0;\n}\n\n// Throws an exception if the given condition is false.\nfunction assert(cond: boolean): void {\n  if (!cond) throw new Error(\"Assertion error\");\n}\n\n/*---- Data segment class ----*/\n\n/*\n * A segment of character/binary/control data in a QR Code symbol.\n * Instances of this class are immutable.\n * The mid-level way to create a segment is to take the payload data\n * and call a static factory function such as QrSegment.makeNumeric().\n * The low-level way to create a segment is to custom-make the bit buffer\n * and call the QrSegment() constructor with appropriate values.\n * This segment class imposes no length restrictions, but QR Codes have restrictions.\n * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.\n * Any segment longer than this is meaningless for the purpose of generating QR Codes.\n */\nexport class QrSegment {\n  public static Mode: typeof QrSegmentMode;\n\n  /*-- Static factory functions (mid level) --*/\n\n  // Returns a segment representing the given binary data encoded in\n  // byte mode. All input byte arrays are acceptable. Any text string\n  // can be converted to UTF-8 bytes and encoded as a byte mode segment.\n  public static makeBytes(data: Readonly<Array<byte>>): QrSegment {\n    let bb: Array<bit> = [];\n    for (const b of data) appendBits(b, 8, bb);\n    return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);\n  }\n\n  // Returns a segment representing the given string of decimal digits encoded in numeric mode.\n  public static makeNumeric(digits: string): QrSegment {\n    if (!QrSegment.isNumeric(digits))\n      throw new RangeError(\"String contains non-numeric characters\");\n    let bb: Array<bit> = [];\n    for (let i = 0; i < digits.length; ) {\n      // Consume up to 3 digits per iteration\n      const n: int = Math.min(digits.length - i, 3);\n      appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);\n      i += n;\n    }\n    return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);\n  }\n\n  // Returns a segment representing the given text string encoded in alphanumeric mode.\n  // The characters allowed are: 0 to 9, A to Z (uppercase only), space,\n  // dollar, percent, asterisk, plus, hyphen, period, slash, colon.\n  public static makeAlphanumeric(text: string): QrSegment {\n    if (!QrSegment.isAlphanumeric(text))\n      throw new RangeError(\"String contains unencodable characters in alphanumeric mode\");\n    let bb: Array<bit> = [];\n    let i: int;\n    for (i = 0; i + 2 <= text.length; i += 2) {\n      // Process groups of 2\n      let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;\n      temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));\n      appendBits(temp, 11, bb);\n    }\n    if (i < text.length)\n      // 1 character remaining\n      appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);\n    return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);\n  }\n\n  // Returns a new mutable list of zero or more segments to represent the given Unicode text string.\n  // The result may use various segment modes and switch modes to optimize the length of the bit stream.\n  public static makeSegments(text: string): Array<QrSegment> {\n    // Select the most efficient segment encoding automatically\n    if (text == \"\") return [];\n    else if (QrSegment.isNumeric(text)) return [QrSegment.makeNumeric(text)];\n    else if (QrSegment.isAlphanumeric(text)) return [QrSegment.makeAlphanumeric(text)];\n    else return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];\n  }\n\n  // Returns a segment representing an Extended Channel Interpretation\n  // (ECI) designator with the given assignment value.\n  public static makeEci(assignVal: int): QrSegment {\n    let bb: Array<bit> = [];\n    if (assignVal < 0) throw new RangeError(\"ECI assignment value out of range\");\n    else if (assignVal < 1 << 7) appendBits(assignVal, 8, bb);\n    else if (assignVal < 1 << 14) {\n      appendBits(0b10, 2, bb);\n      appendBits(assignVal, 14, bb);\n    } else if (assignVal < 1000000) {\n      appendBits(0b110, 3, bb);\n      appendBits(assignVal, 21, bb);\n    } else throw new RangeError(\"ECI assignment value out of range\");\n    return new QrSegment(QrSegment.Mode.ECI, 0, bb);\n  }\n\n  // Tests whether the given string can be encoded as a segment in numeric mode.\n  // A string is encodable iff each character is in the range 0 to 9.\n  public static isNumeric(text: string): boolean {\n    return QrSegment.NUMERIC_REGEX.test(text);\n  }\n\n  // Tests whether the given string can be encoded as a segment in alphanumeric mode.\n  // A string is encodable iff each character is in the following set: 0 to 9, A to Z\n  // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.\n  public static isAlphanumeric(text: string): boolean {\n    return QrSegment.ALPHANUMERIC_REGEX.test(text);\n  }\n\n  /*-- Constructor (low level) and fields --*/\n\n  public readonly mode: QrSegmentMode;\n  public readonly numChars: int;\n  private readonly bitData: Array<bit>;\n\n  // Creates a new QR Code segment with the given attributes and data.\n  // The character count (numChars) must agree with the mode and the bit buffer length,\n  // but the constraint isn't checked. The given bit buffer is cloned and stored.\n  public constructor(\n    // The mode indicator of this segment.\n    mode: QrSegmentMode,\n\n    // The length of this segment's unencoded data. Measured in characters for\n    // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.\n    // Always zero or positive. Not the same as the data's bit length.\n    numChars: int,\n\n    // The data bits of this segment. Accessed through getData().\n    bitData: Array<bit>,\n  ) {\n    this.mode = mode;\n    this.numChars = numChars;\n    if (numChars < 0) throw new RangeError(\"Invalid argument\");\n    this.bitData = bitData.slice(); // Make defensive copy\n  }\n\n  /*-- Methods --*/\n\n  // Returns a new copy of the data bits of this segment.\n  public getData(): Array<bit> {\n    return this.bitData.slice(); // Make defensive copy\n  }\n\n  // (Package-private) Calculates and returns the number of bits needed to encode the given segments at\n  // the given version. The result is infinity if a segment has too many characters to fit its length field.\n  public static getTotalBits(segs: Readonly<Array<QrSegment>>, version: int): number {\n    let result: number = 0;\n    for (const seg of segs) {\n      const ccbits: int = seg.mode.numCharCountBits(version);\n      if (seg.numChars >= 1 << ccbits) return Infinity; // The segment's length doesn't fit the field's bit width\n      result += 4 + ccbits + seg.bitData.length;\n    }\n    return result;\n  }\n\n  // Returns a new array of bytes representing the given string encoded in UTF-8.\n  private static toUtf8ByteArray(str: string): Array<byte> {\n    str = encodeURI(str);\n    let result: Array<byte> = [];\n    for (let i = 0; i < str.length; i++) {\n      if (str.charAt(i) != \"%\") result.push(str.charCodeAt(i));\n      else {\n        result.push(parseInt(str.substring(i + 1, i + 3), 16));\n        i += 2;\n      }\n    }\n    return result;\n  }\n\n  /*-- Constants --*/\n\n  // Describes precisely all strings that are encodable in numeric mode.\n  private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/;\n\n  // Describes precisely all strings that are encodable in alphanumeric mode.\n  private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\\/:-]*$/;\n\n  // The set of all legal characters in alphanumeric mode,\n  // where each character value maps to the index in the string.\n  private static readonly ALPHANUMERIC_CHARSET: string =\n    \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:\";\n}\n\n/*---- Public helper enumeration ----*/\n\nclass QrCodeEcc {\n  /*-- Constants --*/\n\n  public static readonly LOW = new QrCodeEcc(0, 1); // The QR Code can tolerate about  7% erroneous codewords\n  public static readonly MEDIUM = new QrCodeEcc(1, 0); // The QR Code can tolerate about 15% erroneous codewords\n  public static readonly QUARTILE = new QrCodeEcc(2, 3); // The QR Code can tolerate about 25% erroneous codewords\n  public static readonly HIGH = new QrCodeEcc(3, 2); // The QR Code can tolerate about 30% erroneous codewords\n\n  public readonly ordinal: int;\n  public readonly formatBits: int;\n\n  /*-- Constructor and fields --*/\n\n  private constructor(\n    // In the range 0 to 3 (unsigned 2-bit integer).\n    ordinal: int,\n    // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).\n    formatBits: int,\n  ) {\n    this.ordinal = ordinal;\n    this.formatBits = formatBits;\n  }\n}\n\n/*---- Public helper enumeration ----*/\n\nclass QrSegmentMode {\n  /*-- Constants --*/\n\n  public static readonly NUMERIC = new QrSegmentMode(0x1, [10, 12, 14]);\n  public static readonly ALPHANUMERIC = new QrSegmentMode(0x2, [9, 11, 13]);\n  public static readonly BYTE = new QrSegmentMode(0x4, [8, 16, 16]);\n  public static readonly KANJI = new QrSegmentMode(0x8, [8, 10, 12]);\n  public static readonly ECI = new QrSegmentMode(0x7, [0, 0, 0]);\n\n  public readonly modeBits: int;\n  private readonly numBitsCharCount: [int, int, int];\n\n  /*-- Constructor and fields --*/\n\n  private constructor(\n    // The mode indicator bits, which is a uint4 value (range 0 to 15).\n    modeBits: int,\n    // Number of character count bits for three different version ranges.\n    numBitsCharCount: [int, int, int],\n  ) {\n    this.modeBits = modeBits;\n    this.numBitsCharCount = numBitsCharCount;\n  }\n\n  /*-- Method --*/\n\n  // (Package-private) Returns the bit width of the character count field for a segment in\n  // this mode in a QR Code at the given version number. The result is in the range [0, 16].\n  public numCharCountBits(ver: int): int {\n    return this.numBitsCharCount[Math.floor((ver + 7) / 17)]!;\n  }\n}\n\nQrCode.Ecc = QrCodeEcc;\nQrSegment.Mode = QrSegmentMode;\n","import * as NodeOS from \"node:os\";\n\nimport { QrCode } from \"@t3tools/shared/qrCode\";\nimport * as Effect from \"effect/Effect\";\nimport { HttpServer } from \"effect/unstable/http\";\n\nimport { ServerConfig } from \"./config.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\n\nexport interface HeadlessServeAccessInfo {\n  readonly connectionString: string;\n  readonly token: string;\n  readonly pairingUrl: string;\n}\n\ntype NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;\n\nexport const isLoopbackHost = (host: string | undefined): boolean => {\n  if (!host || host.length === 0) {\n    return true;\n  }\n\n  return (\n    host === \"localhost\" ||\n    host === \"127.0.0.1\" ||\n    host === \"::1\" ||\n    host === \"[::1]\" ||\n    host.startsWith(\"127.\")\n  );\n};\n\nexport const isWildcardHost = (host: string | undefined): boolean =>\n  host === \"0.0.0.0\" || host === \"::\" || host === \"[::]\";\n\nexport const formatHostForUrl = (host: string): string =>\n  host.includes(\":\") && !host.startsWith(\"[\") ? `[${host}]` : host;\n\nconst normalizeHost = (host: string): string =>\n  host.startsWith(\"[\") && host.endsWith(\"]\") ? host.slice(1, -1) : host;\n\nconst isIpv4Family = (family: string | number): boolean => family === \"IPv4\" || family === 4;\n\nconst isIpv6Family = (family: string | number): boolean => family === \"IPv6\" || family === 6;\n\nexport const resolveHeadlessConnectionHost = (\n  host: string | undefined,\n  interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),\n): string => {\n  if (!host) {\n    return \"localhost\";\n  }\n\n  if (!isWildcardHost(host)) {\n    return normalizeHost(host);\n  }\n\n  const interfaceEntries = Object.values(interfaces).flatMap((entries) => entries ?? []);\n  const externalIpv4 = interfaceEntries.find(\n    (entry) => !entry.internal && isIpv4Family(entry.family),\n  );\n  if (externalIpv4) {\n    return externalIpv4.address;\n  }\n\n  const externalIpv6 = interfaceEntries.find(\n    (entry) => !entry.internal && isIpv6Family(entry.family),\n  );\n  return externalIpv6 ? normalizeHost(externalIpv6.address) : \"localhost\";\n};\n\nexport const resolveHeadlessConnectionString = (\n  host: string | undefined,\n  port: number,\n  interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),\n): string => {\n  const connectionHost = resolveHeadlessConnectionHost(host, interfaces);\n  return `http://${formatHostForUrl(connectionHost)}:${port}`;\n};\n\nexport const resolveListeningPort = (address: unknown, fallbackPort: number): number => {\n  if (\n    typeof address === \"object\" &&\n    address !== null &&\n    \"port\" in address &&\n    typeof address.port === \"number\"\n  ) {\n    return address.port;\n  }\n  return fallbackPort;\n};\n\nexport const buildPairingUrl = (connectionString: string, token: string): string => {\n  const url = new URL(connectionString);\n  url.pathname = \"/pair\";\n  url.searchParams.delete(\"token\");\n  url.hash = new URLSearchParams([[\"token\", token]]).toString();\n  return url.toString();\n};\n\nexport const renderTerminalQrCode = (value: string, margin = 2): string => {\n  const qrCode = QrCode.encodeText(value, QrCode.Ecc.MEDIUM);\n  const rows: Array<string> = [];\n  const isDark = (x: number, y: number): boolean =>\n    x >= 0 && x < qrCode.size && y >= 0 && y < qrCode.size && qrCode.getModule(x, y);\n\n  for (let y = -margin; y < qrCode.size + margin; y += 2) {\n    let row = \"\";\n\n    for (let x = -margin; x < qrCode.size + margin; x += 1) {\n      const topDark = isDark(x, y);\n      const bottomDark = isDark(x, y + 1);\n\n      row += topDark ? (bottomDark ? \"█\" : \"▀\") : bottomDark ? \"▄\" : \" \";\n    }\n\n    rows.push(row);\n  }\n\n  return rows.join(\"\\n\");\n};\n\nexport const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo): string =>\n  [\n    \"Synaptic Code server is ready.\",\n    `Connection string: ${accessInfo.connectionString}`,\n    `Token: ${accessInfo.token}`,\n    `Pairing URL: ${accessInfo.pairingUrl}`,\n    \"\",\n    renderTerminalQrCode(accessInfo.pairingUrl),\n    \"\",\n  ].join(\"\\n\");\n\nexport const issueHeadlessServeAccessInfo = Effect.fn(\"issueHeadlessServeAccessInfo\")(function* () {\n  const serverConfig = yield* ServerConfig;\n  const httpServer = yield* HttpServer.HttpServer;\n  const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n  const connectionString = resolveHeadlessConnectionString(\n    serverConfig.host,\n    resolveListeningPort(httpServer.address, serverConfig.port),\n  );\n  const issued = yield* serverAuth.issueStartupPairingCredential();\n\n  return {\n    connectionString,\n    token: issued.credential,\n    pairingUrl: buildPairingUrl(connectionString, issued.credential),\n  } satisfies HeadlessServeAccessInfo;\n});\n","import * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport { writeFileStringAtomically } from \"./atomicWrite.ts\";\nimport type * as ServerConfig from \"./config.ts\";\nimport { formatHostForUrl, isWildcardHost } from \"./startupAccess.ts\";\n\nexport const PersistedServerRuntimeState = Schema.Struct({\n  version: Schema.Literal(1),\n  pid: Schema.Int,\n  host: Schema.optional(Schema.String),\n  port: Schema.Int,\n  origin: Schema.String,\n  // Present when the server fronts a dev web server (VITE_DEV_SERVER_URL).\n  // Dev is single-origin: browsers must pair through this URL, not `origin`.\n  devUrl: Schema.optional(Schema.String),\n  startedAt: Schema.String,\n});\nexport type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;\n\nexport class ServerRuntimeStateError extends Schema.TaggedErrorClass<ServerRuntimeStateError>()(\n  \"ServerRuntimeStateError\",\n  {\n    operation: Schema.Literals([\"persist\", \"read\", \"decode\", \"clear\"]),\n    statePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to ${this.operation} server runtime state at ${this.statePath}.`;\n  }\n}\n\nconst decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(\n  Schema.fromJsonString(PersistedServerRuntimeState),\n);\n\nconst runtimeOriginForConfig = (\n  config: Pick<ServerConfig.ServerConfig[\"Service\"], \"host\">,\n  port: number,\n): PersistedServerRuntimeState[\"origin\"] => {\n  const hostname =\n    config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : \"127.0.0.1\";\n  return `http://${hostname}:${port}`;\n};\n\nexport const makePersistedServerRuntimeState = (input: {\n  readonly config: Pick<ServerConfig.ServerConfig[\"Service\"], \"host\" | \"devUrl\">;\n  readonly port: number;\n}): Effect.Effect<PersistedServerRuntimeState> =>\n  Effect.map(DateTime.now, (now) => ({\n    version: 1,\n    pid: process.pid,\n    ...(input.config.host ? { host: input.config.host } : {}),\n    port: input.port,\n    origin: runtimeOriginForConfig(input.config, input.port),\n    ...(input.config.devUrl ? { devUrl: input.config.devUrl.toString() } : {}),\n    startedAt: DateTime.formatIso(now),\n  }));\n\nexport const persistServerRuntimeState = (input: {\n  readonly path: string;\n  readonly state: PersistedServerRuntimeState;\n}) =>\n  writeFileStringAtomically({\n    filePath: input.path,\n    contents: `${JSON.stringify(input.state)}\\n`,\n  }).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ServerRuntimeStateError({\n          operation: \"persist\",\n          statePath: input.path,\n          cause,\n        }),\n    ),\n  );\n\nexport const clearPersistedServerRuntimeState = (path: string) =>\n  Effect.gen(function* () {\n    const fs = yield* FileSystem.FileSystem;\n    yield* fs.remove(path, { force: true }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerRuntimeStateError({\n            operation: \"clear\",\n            statePath: path,\n            cause,\n          }),\n      ),\n      Effect.catchTags({\n        ServerRuntimeStateError: (error) =>\n          Effect.logWarning(error.message).pipe(\n            Effect.annotateLogs({\n              operation: error.operation,\n              statePath: error.statePath,\n              cause: error,\n            }),\n          ),\n      }),\n    );\n  });\n\nexport const readPersistedServerRuntimeState = (path: string) =>\n  Effect.gen(function* () {\n    const fs = yield* FileSystem.FileSystem;\n    const raw = yield* fs.readFileString(path).pipe(\n      Effect.matchEffect({\n        onFailure: (cause) =>\n          cause.reason._tag === \"NotFound\"\n            ? Effect.succeed(Option.none<string>())\n            : Effect.fail(\n                new ServerRuntimeStateError({\n                  operation: \"read\",\n                  statePath: path,\n                  cause,\n                }),\n              ),\n        onSuccess: (contents) => Effect.succeed(Option.some(contents)),\n      }),\n    );\n    if (Option.isNone(raw)) {\n      return Option.none<PersistedServerRuntimeState>();\n    }\n\n    const trimmed = raw.value.trim();\n    if (trimmed.length === 0) {\n      return Option.none<PersistedServerRuntimeState>();\n    }\n\n    return yield* decodePersistedServerRuntimeState(trimmed).pipe(\n      Effect.map(Option.some),\n      Effect.mapError(\n        (cause) =>\n          new ServerRuntimeStateError({\n            operation: \"decode\",\n            statePath: path,\n            cause,\n          }),\n      ),\n    );\n  }).pipe(\n    Effect.catchTags({\n      ServerRuntimeStateError: (error) =>\n        Effect.logWarning(error.message).pipe(\n          Effect.annotateLogs({\n            operation: error.operation,\n            statePath: error.statePath,\n            cause: error,\n          }),\n          Effect.as(Option.none<PersistedServerRuntimeState>()),\n        ),\n    }),\n  );\n","/**\n * `synaptic-code pair` - mint a pairing token for an already-running server and print it\n * as a QR code, without restarting anything.\n *\n * Discovery reads the `server-runtime.json` a live server persists next to its\n * database, then confirms the process is actually answering by fetching its\n * public environment descriptor. Inside a linked git worktree the worktree's\n * own `.synaptic` is checked first (matching dev-runner precedence); otherwise\n * the shared `~/.synaptic` home. `--tailscale` publishes the server over Tailscale Serve\n * HTTPS and pairs through the tailnet URL instead.\n */\nimport {\n  AuthStandardClientScopes,\n  ExecutionEnvironmentDescriptor,\n  PortSchema,\n} from \"@t3tools/contracts\";\nimport { resolveWorktreeT3Home } from \"@t3tools/shared/devHome\";\nimport {\n  buildTailscaleHttpsBaseUrl,\n  DEFAULT_TAILSCALE_SERVE_PORT,\n  ensureTailscaleServe,\n  readTailscaleStatus,\n} from \"@t3tools/tailscale\";\nimport * as Config from \"effect/Config\";\nimport * as Console from \"effect/Console\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as References from \"effect/References\";\nimport * as Schema from \"effect/Schema\";\nimport { Command, Flag, GlobalFlag } from \"effect/unstable/cli\";\nimport {\n  FetchHttpClient,\n  HttpClient,\n  HttpClientRequest,\n  HttpClientResponse,\n} from \"effect/unstable/http\";\n\nimport * as EnvironmentAuth from \"../auth/EnvironmentAuth.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport { resolveBaseDir } from \"../os-jank.ts\";\nimport {\n  type PersistedServerRuntimeState,\n  readPersistedServerRuntimeState,\n} from \"../serverRuntimeState.ts\";\nimport {\n  buildPairingUrl,\n  formatHostForUrl,\n  isLoopbackHost,\n  isWildcardHost,\n  renderTerminalQrCode,\n  resolveHeadlessConnectionString,\n} from \"../startupAccess.ts\";\nimport { baseDirFlag, DurationFromString } from \"./config.ts\";\n\nconst WELL_KNOWN_ENVIRONMENT_PATH = \"/.well-known/t3/environment\";\nconst PAIR_PROBE_TIMEOUT = Duration.millis(2_500);\n// Tailscale provisions an HTTPS certificate on the first request to a fresh\n// serve mapping, which can take a few seconds.\nconst TAILSCALE_PROBE_ATTEMPTS = 5;\nconst TAILSCALE_PROBE_RETRY_DELAY = Duration.seconds(1);\n\nexport type PairStateVariant = \"userdata\" | \"dev\";\n\n// deriveServerPaths only checks devUrl for undefined-ness when picking the\n// dev-vs-userdata state directory; the value itself is not used.\nconst DEV_VARIANT_PLACEHOLDER_URL = new URL(\"http://localhost\");\n\nexport class NoRunningServerError extends Schema.TaggedErrorClass<NoRunningServerError>()(\n  \"NoRunningServerError\",\n  {\n    checkedStatePaths: Schema.Array(Schema.String),\n  },\n) {\n  override get message(): string {\n    return [\n      \"No running Synaptic Code server found.\",\n      ...this.checkedStatePaths.map((statePath) => `  checked ${statePath}`),\n      \"Start one with `npx @dmccore/code serve`.\",\n    ].join(\"\\n\");\n  }\n}\n\n// Each tailscale failure gets its own class (same reasoning as\n// scripts/lib/dev-share.ts): distinct caller-visible message, distinct remedy.\nexport class TailscaleUnavailableError extends Schema.TaggedErrorClass<TailscaleUnavailableError>()(\n  \"TailscaleUnavailableError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Could not talk to Tailscale. Is tailscaled running? Try `tailscale status`.\";\n  }\n}\n\nexport class MagicDnsNameMissingError extends Schema.TaggedErrorClass<MagicDnsNameMissingError>()(\n  \"MagicDnsNameMissingError\",\n  {},\n) {\n  override get message(): string {\n    return \"This machine has no MagicDNS name. Run `tailscale up` and enable MagicDNS.\";\n  }\n}\n\nexport class ServesOtherEnvironmentError extends Schema.TaggedErrorClass<ServesOtherEnvironmentError>()(\n  \"ServesOtherEnvironmentError\",\n  { servePort: Schema.Number },\n) {\n  override get message(): string {\n    return `Tailscale Serve on HTTPS port ${String(this.servePort)} already fronts a different Synaptic Code server. Pass --tailscale-serve-port to publish this one on another port.`;\n  }\n}\n\nexport class TailscaleServeFailedError extends Schema.TaggedErrorClass<TailscaleServeFailedError>()(\n  \"TailscaleServeFailedError\",\n  { servePort: Schema.Number, cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return `tailscale serve failed for HTTPS port ${String(this.servePort)}. Run \\`tailscale serve --https=${String(this.servePort)} --bg <local-url>\\` by hand to see why.`;\n  }\n}\n\nexport class ServePortOccupiedError extends Schema.TaggedErrorClass<ServePortOccupiedError>()(\n  \"ServePortOccupiedError\",\n  { servePort: Schema.Number },\n) {\n  override get message(): string {\n    return `HTTPS port ${String(this.servePort)} on the tailnet already serves something that is not a Synaptic Code server. Pass --tailscale-serve-port to publish this one on another port.`;\n  }\n}\n\n/** The URL a browser or phone should pair through, absent Tailscale. */\nexport const resolveDirectPairingBaseUrl = (state: PersistedServerRuntimeState): string =>\n  state.devUrl ?? resolveHeadlessConnectionString(state.host, state.port);\n\nexport class DevServerNotProxiableError extends Schema.TaggedErrorClass<DevServerNotProxiableError>()(\n  \"DevServerNotProxiableError\",\n  { devUrl: Schema.String },\n) {\n  override get message(): string {\n    return `Tailscale Serve can only proxy plain-HTTP local targets, and this dev server runs at ${this.devUrl}. Pair without --tailscale instead.`;\n  }\n}\n\nconst isDevServerNotProxiableError = Schema.is(DevServerNotProxiableError);\n\n/**\n * The local endpoint Tailscale Serve should proxy to. Dev servers are\n * single-origin, so the web dev server's port is the one to publish; the\n * backend rides along behind Vite's proxy. Serve targets are always plain\n * HTTP, so an HTTPS dev URL cannot be proxied and is rejected.\n */\nexport const resolveTailscaleLocalTarget = (\n  state: PersistedServerRuntimeState,\n): { readonly localPort: number; readonly localHost?: string } | DevServerNotProxiableError => {\n  if (state.devUrl !== undefined) {\n    const devUrl = new URL(state.devUrl);\n    if (devUrl.protocol !== \"http:\") {\n      return new DevServerNotProxiableError({ devUrl: state.devUrl });\n    }\n    const localPort = devUrl.port.length > 0 ? Number.parseInt(devUrl.port, 10) : 80;\n    return isLoopbackHost(devUrl.hostname)\n      ? { localPort }\n      : { localPort, localHost: devUrl.hostname };\n  }\n  // A server bound to one specific interface does not answer on loopback, so\n  // the proxy has to target that interface directly.\n  if (state.host !== undefined && !isWildcardHost(state.host) && !isLoopbackHost(state.host)) {\n    return { localPort: state.port, localHost: formatHostForUrl(state.host) };\n  }\n  return { localPort: state.port };\n};\n\nexport const formatPairOutput = (input: {\n  readonly serverLabel: string;\n  readonly origin: string;\n  readonly pairingUrl: string;\n  readonly token: string;\n  readonly expiresAt: DateTime.Utc;\n  readonly notes: ReadonlyArray<string>;\n}): string =>\n  [\n    `Pairing with ${input.serverLabel} (${input.origin}).`,\n    \"\",\n    renderTerminalQrCode(input.pairingUrl),\n    \"\",\n    `Pairing URL: ${input.pairingUrl}`,\n    `Token: ${input.token}`,\n    `Expires: ${DateTime.formatIso(input.expiresAt)}`,\n    ...input.notes.flatMap((note) => [\"\", `Note: ${note}`]),\n    \"\",\n  ].join(\"\\n\");\n\n/**\n * Three outcomes, because they drive different decisions: a T3 descriptor\n * (pair with it), nothing answering (safe to configure Tailscale Serve), or\n * something answering that is not a T3 server (do NOT overwrite its mapping).\n */\ntype EnvironmentProbeResult =\n  | { readonly _tag: \"descriptor\"; readonly descriptor: ExecutionEnvironmentDescriptor }\n  | { readonly _tag: \"unreachable\" }\n  | { readonly _tag: \"not-a-t3-server\" };\n\nconst probeEnvironmentDescriptor = (\n  baseUrl: string,\n): Effect.Effect<EnvironmentProbeResult, never, HttpClient.HttpClient> =>\n  Effect.gen(function* () {\n    const client = yield* HttpClient.HttpClient;\n    const request = HttpClientRequest.get(new URL(WELL_KNOWN_ENVIRONMENT_PATH, baseUrl).toString());\n    const response = yield* client.execute(request).pipe(\n      Effect.timeout(PAIR_PROBE_TIMEOUT),\n      // Transport failure or timeout: nothing (reachable) is listening there.\n      Effect.mapError(() => ({ _tag: \"unreachable\" }) as const),\n    );\n    // Bad-gateway family means a proxy (Tailscale Serve) answered for a\n    // backend that is gone — a stale mapping, not a live occupant. Treating\n    // it as unreachable lets `synaptic-code pair --tailscale` repair its own mapping\n    // after the server's port changed.\n    if (response.status === 502 || response.status === 503 || response.status === 504) {\n      return { _tag: \"unreachable\" } as const;\n    }\n    // Anything else that answered HTTP but not with a valid descriptor is\n    // some other service.\n    const descriptor = yield* HttpClientResponse.filterStatusOk(response).pipe(\n      Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)),\n      Effect.mapError(() => ({ _tag: \"not-a-t3-server\" }) as const),\n    );\n    return { _tag: \"descriptor\", descriptor } as const;\n  }).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));\n\n// signal 0 delivers nothing; it only reports whether the pid exists. EPERM\n// means it exists but belongs to another user, which still counts as alive.\nconst isProcessAlive = (pid: number): boolean => {\n  try {\n    process.kill(pid, 0);\n    return true;\n  } catch (error) {\n    return error instanceof Error && \"code\" in error && error.code === \"EPERM\";\n  }\n};\n\ninterface DiscoveredPairTarget {\n  readonly baseDir: string;\n  readonly variant: PairStateVariant;\n  readonly state: PersistedServerRuntimeState;\n  readonly descriptor: ExecutionEnvironmentDescriptor;\n}\n\nconst discoverPairTarget = Effect.fn(\"pair.discoverPairTarget\")(function* (\n  explicitBaseDir: string | undefined,\n) {\n  const bases: Array<string> = [];\n  if (explicitBaseDir !== undefined && explicitBaseDir.trim().length > 0) {\n    bases.push(yield* resolveBaseDir(explicitBaseDir));\n  } else {\n    // Same precedence as dev-runner: inside a linked worktree its own `.synaptic`\n    // outranks the shared home, so `synaptic-code pair` in a worktree pairs with the dev\n    // server under test rather than the daily-driver install.\n    const worktreeHome = yield* resolveWorktreeT3Home(process.cwd());\n    if (worktreeHome !== undefined) {\n      bases.push(worktreeHome);\n    }\n    const envHome = yield* Config.string(\"SYNAPTIC_HOME\").pipe(Config.option);\n    bases.push(yield* resolveBaseDir(Option.getOrUndefined(envHome)));\n  }\n\n  const checkedStatePaths: Array<string> = [];\n  for (const baseDir of new Set(bases)) {\n    for (const variant of [\"userdata\", \"dev\"] as const) {\n      const derivedPaths = yield* ServerConfig.deriveServerPaths(\n        baseDir,\n        variant === \"dev\" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,\n        {},\n      );\n      const statePath = derivedPaths.serverRuntimeStatePath;\n      checkedStatePaths.push(statePath);\n      const state = yield* readPersistedServerRuntimeState(statePath);\n      if (Option.isNone(state)) {\n        continue;\n      }\n      // The pid check guards against a dead server's state file whose port\n      // was since reused by a different server: pairing would then mint a\n      // token in the old database while the QR code points at the new server.\n      if (!isProcessAlive(state.value.pid)) {\n        continue;\n      }\n      const probed = yield* probeEnvironmentDescriptor(state.value.origin);\n      if (probed._tag !== \"descriptor\") {\n        continue;\n      }\n      return {\n        baseDir,\n        variant,\n        state: state.value,\n        descriptor: probed.descriptor,\n      } satisfies DiscoveredPairTarget;\n    }\n  }\n  return yield* new NoRunningServerError({ checkedStatePaths });\n});\n\n/**\n * Server config pointed at the discovered server's state directory, so the\n * minted token lands in the database the running server reads from. Built by\n * hand rather than through `resolveServerConfig` to keep the dev-vs-userdata\n * choice pinned to where the runtime state was actually found, independent of\n * ambient environment variables.\n */\nconst makePairServerConfig = Effect.fn(function* (input: {\n  readonly target: DiscoveredPairTarget;\n  readonly logLevel: ServerConfig.ServerConfig[\"Service\"][\"logLevel\"];\n}) {\n  const { baseDir, variant, state } = input.target;\n  // The state-dir variant does not imply dev-ness: a worktree dev server uses\n  // an explicit home and therefore lands in `userdata`. The recorded devUrl is\n  // what actually marks a dev server.\n  const devUrl = state.devUrl !== undefined ? new URL(state.devUrl) : undefined;\n  const derivedPaths = yield* ServerConfig.deriveServerPaths(\n    baseDir,\n    variant === \"dev\" ? DEV_VARIANT_PLACEHOLDER_URL : undefined,\n    {},\n  );\n  return ServerConfig.make({\n    logLevel: input.logLevel,\n    traceMinLevel: \"Info\",\n    traceTimingEnabled: false,\n    traceBatchWindowMs: 1_000,\n    traceMaxBytes: 10 * 1024 * 1024,\n    traceMaxFiles: 10,\n    otlpTracesUrl: undefined,\n    otlpMetricsUrl: undefined,\n    otlpExportIntervalMs: 10_000,\n    otlpServiceName: \"t3-server\",\n    mode: \"web\",\n    port: state.port,\n    host: state.host,\n    cwd: process.cwd(),\n    baseDir,\n    ...derivedPaths,\n    staticDir: undefined,\n    devUrl,\n    devAllowedOrigins: [],\n    noBrowser: true,\n    startupPresentation: \"headless\",\n    desktopBootstrapToken: undefined,\n    desktopTelemetryFd: undefined,\n    desktopTelemetryControlFd: undefined,\n    resourceMonitorPath: undefined,\n    autoBootstrapProjectFromCwd: false,\n    logWebSocketEvents: false,\n    tailscaleServeEnabled: false,\n    tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,\n  });\n});\n\nconst awaitEnvironmentDescriptor = Effect.fn(function* (baseUrl: string) {\n  let last: EnvironmentProbeResult = { _tag: \"unreachable\" };\n  for (let attempt = 0; attempt < TAILSCALE_PROBE_ATTEMPTS; attempt += 1) {\n    last = yield* probeEnvironmentDescriptor(baseUrl);\n    if (last._tag === \"descriptor\") {\n      return last;\n    }\n    yield* Effect.sleep(TAILSCALE_PROBE_RETRY_DELAY);\n  }\n  return last;\n});\n\nconst resolveTailscalePairingBase = Effect.fn(\"pair.resolveTailscalePairingBase\")(\n  function* (input: { readonly target: DiscoveredPairTarget; readonly servePort: number }) {\n    const notes: Array<string> = [];\n    const status = yield* readTailscaleStatus.pipe(\n      Effect.mapError((cause) => new TailscaleUnavailableError({ cause })),\n    );\n    if (status.magicDnsName === null) {\n      return yield* new MagicDnsNameMissingError();\n    }\n    const baseUrl = buildTailscaleHttpsBaseUrl({\n      magicDnsName: status.magicDnsName,\n      servePort: input.servePort,\n    });\n\n    // Only an unreachable port, or a mapping already fronting this exact\n    // environment, is safe to (re)configure. Any other responder — T3 or not\n    // — must not have its mapping silently replaced.\n    const existing = yield* probeEnvironmentDescriptor(baseUrl);\n    if (existing._tag === \"descriptor\") {\n      if (existing.descriptor.environmentId !== input.target.descriptor.environmentId) {\n        return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });\n      }\n      // Matching environment id proves the mapping reaches this server, but\n      // not through which port: for a dev server it may front the backend\n      // (whose /.well-known also answers) while /pair only renders through\n      // the web origin. Reuse as-is for regular servers; fall through and\n      // repoint our own mapping at the web port for dev servers.\n      if (input.target.state.devUrl === undefined) {\n        return { baseUrl, notes };\n      }\n    }\n    if (existing._tag === \"not-a-t3-server\") {\n      return yield* new ServePortOccupiedError({ servePort: input.servePort });\n    }\n\n    const localTarget = resolveTailscaleLocalTarget(input.target.state);\n    if (isDevServerNotProxiableError(localTarget)) {\n      return yield* localTarget;\n    }\n    yield* ensureTailscaleServe({\n      localPort: localTarget.localPort,\n      servePort: input.servePort,\n      ...(localTarget.localHost !== undefined ? { localHost: localTarget.localHost } : {}),\n    }).pipe(\n      Effect.mapError(\n        (cause) => new TailscaleServeFailedError({ servePort: input.servePort, cause }),\n      ),\n    );\n    notes.push(\n      `Tailscale Serve now maps ${baseUrl} to this server and persists across restarts. Remove it with \\`tailscale serve --https=${String(input.servePort)} off\\`.`,\n    );\n\n    const probed = yield* awaitEnvironmentDescriptor(baseUrl);\n    if (probed._tag === \"descriptor\") {\n      if (probed.descriptor.environmentId !== input.target.descriptor.environmentId) {\n        return yield* new ServesOtherEnvironmentError({ servePort: input.servePort });\n      }\n    } else {\n      notes.push(\n        \"The HTTPS endpoint has not answered yet. First use can take a moment while Tailscale provisions certificates.\",\n      );\n    }\n    return { baseUrl, notes };\n  },\n);\n\nconst mintPairingLink = Effect.fn(\"pair.mintPairingLink\")(function* (input: {\n  readonly config: ServerConfig.ServerConfig[\"Service\"];\n  readonly ttl: Option.Option<Duration.Duration>;\n  readonly label: Option.Option<string>;\n}) {\n  return yield* Effect.gen(function* () {\n    const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    return yield* environmentAuth.createPairingLink({\n      scopes: AuthStandardClientScopes,\n      subject: \"one-time-token\",\n      label: Option.getOrElse(input.label, () => \"synaptic-code pair\"),\n      ...(Option.isSome(input.ttl) ? { ttl: input.ttl.value } : {}),\n    });\n  }).pipe(\n    Effect.provide(\n      EnvironmentAuth.runtimeLayer.pipe(\n        Layer.provide(ServerConfig.layer(input.config)),\n        Layer.provide(Layer.succeed(References.MinimumLogLevel, input.config.logLevel)),\n      ),\n    ),\n  );\n});\n\nconst ttlFlag = Flag.string(\"ttl\").pipe(\n  Flag.withSchema(DurationFromString),\n  Flag.withDescription(\n    \"Token TTL, for example `5m`, `1h`, or `15 minutes`. Defaults to 5 minutes.\",\n  ),\n  Flag.optional,\n);\n\nconst labelFlag = Flag.string(\"label\").pipe(\n  Flag.withDescription(\"Optional label shown in the server's connections list.\"),\n  Flag.optional,\n);\n\nconst tailscaleFlag = Flag.boolean(\"tailscale\").pipe(\n  Flag.withDescription(\n    \"Publish the server over Tailscale Serve HTTPS and pair through the tailnet URL.\",\n  ),\n  Flag.withDefault(false),\n);\n\nconst tailscaleServePortFlag = Flag.integer(\"tailscale-serve-port\").pipe(\n  Flag.withSchema(PortSchema),\n  Flag.withDescription(\"HTTPS port for Tailscale Serve when --tailscale is enabled.\"),\n  Flag.withDefault(DEFAULT_TAILSCALE_SERVE_PORT),\n);\n\nexport const pairCommand = Command.make(\"pair\", {\n  baseDir: baseDirFlag,\n  ttl: ttlFlag,\n  label: labelFlag,\n  tailscale: tailscaleFlag,\n  tailscaleServePort: tailscaleServePortFlag,\n}).pipe(\n  Command.withDescription(\n    \"Mint a pairing token for a running Synaptic Code server and print it as a QR code.\",\n  ),\n  Command.withHandler((flags) =>\n    Effect.gen(function* () {\n      const cliLogLevel = yield* GlobalFlag.LogLevel;\n      // Default to Warn so storage/migration chatter cannot bury the QR code;\n      // an explicit --log-level still wins.\n      const logLevel = Option.getOrElse(cliLogLevel, () => \"Warn\" as const);\n\n      const target = yield* discoverPairTarget(Option.getOrUndefined(flags.baseDir));\n\n      const notes: Array<string> = [];\n      let pairingBaseUrl: string;\n      if (flags.tailscale) {\n        const resolved = yield* resolveTailscalePairingBase({\n          target,\n          servePort: flags.tailscaleServePort,\n        });\n        pairingBaseUrl = resolved.baseUrl;\n        notes.push(...resolved.notes);\n      } else {\n        pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);\n        if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {\n          notes.push(\n            \"This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.\",\n          );\n        }\n        if (target.variant === \"dev\" && target.state.devUrl === undefined) {\n          notes.push(\n            \"This dev server did not record its web URL; restart it so pairing can go through the web origin.\",\n          );\n        }\n      }\n\n      const config = yield* makePairServerConfig({ target, logLevel });\n      const issued = yield* mintPairingLink({ config, ttl: flags.ttl, label: flags.label });\n      const pairingUrl = buildPairingUrl(pairingBaseUrl, issued.credential);\n\n      yield* Console.log(\n        formatPairOutput({\n          serverLabel: target.descriptor.label,\n          origin: target.state.origin,\n          pairingUrl,\n          token: issued.credential,\n          expiresAt: issued.expiresAt,\n          notes,\n        }),\n      );\n    }).pipe(Effect.provide(FetchHttpClient.layer)),\n  ),\n);\n","/**\n * OrchestrationEngineService - Service interface for orchestration command handling.\n *\n * Owns command validation/dispatch and in-memory read-model updates backed by\n * `OrchestrationEventStore` persistence. It does not own provider process\n * management or transport concerns (e.g. websocket request parsing).\n *\n * Uses Effect `Context.Service` for dependency injection. Command dispatch,\n * replay, and unknown-input decoding all return typed domain errors.\n *\n * @module OrchestrationEngineService\n */\nimport type { OrchestrationCommand, OrchestrationEvent } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { OrchestrationDispatchError } from \"../Errors.ts\";\nimport type { OrchestrationEventStoreError } from \"../../persistence/Errors.ts\";\n\n/**\n * OrchestrationEngineShape - Service API for orchestration command and event flow.\n */\nexport interface OrchestrationEngineShape {\n  /**\n   * Replay persisted orchestration events from an exclusive sequence cursor.\n   *\n   * @param fromSequenceExclusive - Sequence cursor (exclusive).\n   * @param limit - Maximum number of events to read. Defaults to the event\n   *   store's page-bounded default; pass a higher value when the caller must\n   *   read every event after the cursor (e.g. per-thread catch-up that filters\n   *   a small subset out of a potentially larger global range).\n   * @returns Stream containing ordered events.\n   */\n  readonly readEvents: (\n    fromSequenceExclusive: number,\n    limit?: number,\n  ) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;\n\n  /**\n   * Dispatch a validated orchestration command.\n   *\n   * @param command - Valid orchestration command.\n   * @returns Effect containing the sequence of the persisted event.\n   *\n   * Dispatch is serialized through an internal queue and deduplicated via\n   * command receipts.\n   */\n  readonly dispatch: (\n    command: OrchestrationCommand,\n  ) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>;\n\n  /**\n   * Stream persisted domain events in dispatch order.\n   *\n   * This is a hot runtime stream (new events only), not a historical replay.\n   */\n  readonly streamDomainEvents: Stream.Stream<OrchestrationEvent>;\n\n  /**\n   * The latest sequence reflected in the engine's authoritative command read\n   * model (0 if none). Used to gauge how far behind a resuming client is before\n   * choosing between an incremental replay and a fresh projected snapshot.\n   */\n  readonly latestSequence: Effect.Effect<number, never, never>;\n}\n\n/**\n * OrchestrationEngineService - Service tag for orchestration engine access.\n *\n * @example\n * ```ts\n * const program = Effect.gen(function* () {\n *   const engine = yield* OrchestrationEngineService\n *   return yield* engine.dispatch(command)\n * })\n * ```\n */\nexport class OrchestrationEngineService extends Context.Service<\n  OrchestrationEngineService,\n  OrchestrationEngineShape\n>()(\"t3/orchestration/Services/OrchestrationEngine/OrchestrationEngineService\") {}\n","/**\n * ProjectionSnapshotQuery - Read-model snapshot query service interface.\n *\n * Exposes the current orchestration projection snapshot for read-only API\n * access.\n *\n * @module ProjectionSnapshotQuery\n */\nimport type {\n  CheckpointRef,\n  OrchestrationCheckpointSummary,\n  OrchestrationProject,\n  OrchestrationProjectShell,\n  OrchestrationReadModel,\n  OrchestrationSearchThreadsInput,\n  OrchestrationSearchThreadsResult,\n  OrchestrationShellSnapshot,\n  OrchestrationThread,\n  OrchestrationThreadDetailSnapshot,\n  OrchestrationThreadDetailWindow,\n  OrchestrationThreadShell,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Option from \"effect/Option\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../../persistence/Errors.ts\";\n\nexport interface ProjectionSnapshotCounts {\n  readonly projectCount: number;\n  readonly threadCount: number;\n}\n\nexport interface ProjectionSnapshotSequence {\n  readonly snapshotSequence: number;\n}\n\nexport interface ProjectionThreadCheckpointContext {\n  readonly threadId: ThreadId;\n  readonly projectId: ProjectId;\n  readonly workspaceRoot: string;\n  readonly worktreePath: string | null;\n  readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;\n}\n\nexport interface ProjectionFullThreadDiffContext {\n  readonly threadId: ThreadId;\n  readonly projectId: ProjectId;\n  readonly workspaceRoot: string;\n  readonly worktreePath: string | null;\n  readonly latestCheckpointTurnCount: number;\n  readonly toCheckpointRef: CheckpointRef | null;\n}\n\n/**\n * ProjectionSnapshotQueryShape - Service API for read-model snapshots.\n */\nexport interface ProjectionSnapshotQueryShape {\n  /**\n   * Read the lightweight command snapshot used to bootstrap the in-memory\n   * orchestration engine without hydrating message/activity/checkpoint bodies.\n   */\n  readonly getCommandReadModel: () => Effect.Effect<\n    OrchestrationReadModel,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Read the latest orchestration projection snapshot.\n   *\n   * Rehydrates from projection tables and derives snapshot sequence from\n   * projector cursor state.\n   */\n  readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;\n\n  /**\n   * Read the latest orchestration shell snapshot.\n   *\n   * Returns only projects and thread shell summaries so clients can bootstrap\n   * lightweight navigation state without hydrating every thread body.\n   */\n  readonly getShellSnapshot: () => Effect.Effect<\n    OrchestrationShellSnapshot,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Read archived thread shell summaries for the archive page.\n   *\n   * This query is separate from the main shell snapshot so archived threads\n   * are never bootstrapped into normal navigation state.\n   */\n  readonly getArchivedShellSnapshot: () => Effect.Effect<\n    OrchestrationShellSnapshot,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Search active thread navigation metadata, user messages, and canonical\n   * assistant outputs without hydrating thread detail snapshots.\n   */\n  readonly searchThreads: (\n    input: OrchestrationSearchThreadsInput,\n  ) => Effect.Effect<OrchestrationSearchThreadsResult, ProjectionRepositoryError>;\n\n  /**\n   * Read the latest projection snapshot sequence without hydrating read-model\n   * entities.\n   */\n  readonly getSnapshotSequence: () => Effect.Effect<\n    ProjectionSnapshotSequence,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Read aggregate projection counts without hydrating the full read model.\n   */\n  readonly getCounts: () => Effect.Effect<ProjectionSnapshotCounts, ProjectionRepositoryError>;\n\n  /**\n   * Read the active project for an exact workspace root match.\n   */\n  readonly getActiveProjectByWorkspaceRoot: (\n    workspaceRoot: string,\n  ) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;\n\n  /**\n   * Read a single active project shell row by id.\n   */\n  readonly getProjectShellById: (\n    projectId: ProjectId,\n  ) => Effect.Effect<Option.Option<OrchestrationProjectShell>, ProjectionRepositoryError>;\n\n  /**\n   * Read the earliest active thread for a project.\n   */\n  readonly getFirstActiveThreadIdByProjectId: (\n    projectId: ProjectId,\n  ) => Effect.Effect<Option.Option<ThreadId>, ProjectionRepositoryError>;\n\n  /**\n   * Read the checkpoint context needed to resolve a single thread diff.\n   */\n  readonly getThreadCheckpointContext: (\n    threadId: ThreadId,\n  ) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;\n\n  /**\n   * Read only the narrow context needed to compute a full-thread diff from\n   * checkpoint 0 to a specific turn count.\n   */\n  readonly getFullThreadDiffContext: (\n    threadId: ThreadId,\n    toTurnCount: number,\n  ) => Effect.Effect<Option.Option<ProjectionFullThreadDiffContext>, ProjectionRepositoryError>;\n\n  /**\n   * Read a single active thread shell row by id.\n   */\n  readonly getThreadShellById: (\n    threadId: ThreadId,\n  ) => Effect.Effect<Option.Option<OrchestrationThreadShell>, ProjectionRepositoryError>;\n\n  /**\n   * Read a single active thread detail snapshot by id.\n   */\n  readonly getThreadDetailById: (\n    threadId: ThreadId,\n  ) => Effect.Effect<Option.Option<OrchestrationThread>, ProjectionRepositoryError>;\n\n  /**\n   * Read a single active thread detail together with the projection snapshot\n   * sequence in one consistent transaction, so the returned `snapshotSequence`\n   * exactly matches the state reflected in `thread` (no interleaving projector\n   * update between the two reads).\n   *\n   * When `window` is provided, the thread's messages, activities, proposed\n   * plans, and checkpoints are bounded to a page of recent turns and the\n   * response carries `page` metadata (see `OrchestrationThreadDetailWindow`).\n   * Without a window the full thread is returned with no `page` field —\n   * pagination is strictly opt-in.\n   */\n  readonly getThreadDetailSnapshot: (\n    threadId: ThreadId,\n    window?: OrchestrationThreadDetailWindow,\n  ) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionSnapshotQuery - Service tag for projection snapshot queries.\n */\nexport class ProjectionSnapshotQuery extends Context.Service<\n  ProjectionSnapshotQuery,\n  ProjectionSnapshotQueryShape\n>()(\"t3/orchestration/Services/ProjectionSnapshotQuery\") {}\n","/**\n * OrchestrationCommandReceiptRepository - Repository interface for command receipts.\n *\n * Owns persistence operations for deduplication and status tracking of\n * orchestration command handling.\n *\n * @module OrchestrationCommandReceiptRepository\n */\nimport {\n  CommandId,\n  IsoDateTime,\n  NonNegativeInt,\n  OrchestrationAggregateKind,\n  OrchestrationCommandReceiptStatus,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { OrchestrationCommandReceiptRepositoryError } from \"../Errors.ts\";\n\nexport const OrchestrationCommandReceipt = Schema.Struct({\n  commandId: CommandId,\n  aggregateKind: OrchestrationAggregateKind,\n  aggregateId: Schema.Union([ProjectId, ThreadId]),\n  acceptedAt: IsoDateTime,\n  resultSequence: NonNegativeInt,\n  status: OrchestrationCommandReceiptStatus,\n  error: Schema.NullOr(Schema.String),\n});\nexport type OrchestrationCommandReceipt = typeof OrchestrationCommandReceipt.Type;\n\nexport const GetByCommandIdInput = Schema.Struct({\n  commandId: CommandId,\n});\nexport type GetByCommandIdInput = typeof GetByCommandIdInput.Type;\n\n/**\n * OrchestrationCommandReceiptRepositoryShape - Service API for command receipts.\n */\nexport interface OrchestrationCommandReceiptRepositoryShape {\n  /**\n   * Insert or replace a command receipt row.\n   *\n   * Upserts by `commandId` for idempotent command-result tracking.\n   */\n  readonly upsert: (\n    receipt: OrchestrationCommandReceipt,\n  ) => Effect.Effect<void, OrchestrationCommandReceiptRepositoryError>;\n\n  /**\n   * Read a command receipt by command id.\n   */\n  readonly getByCommandId: (\n    input: GetByCommandIdInput,\n  ) => Effect.Effect<\n    Option.Option<OrchestrationCommandReceipt>,\n    OrchestrationCommandReceiptRepositoryError\n  >;\n}\n\n/**\n * OrchestrationCommandReceiptRepository - Service tag for command receipt persistence.\n */\nexport class OrchestrationCommandReceiptRepository extends Context.Service<\n  OrchestrationCommandReceiptRepository,\n  OrchestrationCommandReceiptRepositoryShape\n>()(\"t3/persistence/Services/OrchestrationCommandReceipts/OrchestrationCommandReceiptRepository\") {}\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\n\nimport {\n  GetByCommandIdInput,\n  OrchestrationCommandReceipt,\n  OrchestrationCommandReceiptRepository,\n  type OrchestrationCommandReceiptRepositoryShape,\n} from \"../Services/OrchestrationCommandReceipts.ts\";\n\nconst makeOrchestrationCommandReceiptRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertReceiptRow = SqlSchema.void({\n    Request: OrchestrationCommandReceipt,\n    execute: (receipt) =>\n      sql`\n        INSERT INTO orchestration_command_receipts (\n          command_id,\n          aggregate_kind,\n          aggregate_id,\n          accepted_at,\n          result_sequence,\n          status,\n          error\n        )\n        VALUES (\n          ${receipt.commandId},\n          ${receipt.aggregateKind},\n          ${receipt.aggregateId},\n          ${receipt.acceptedAt},\n          ${receipt.resultSequence},\n          ${receipt.status},\n          ${receipt.error}\n        )\n        ON CONFLICT (command_id)\n        DO UPDATE SET\n          aggregate_kind = excluded.aggregate_kind,\n          aggregate_id = excluded.aggregate_id,\n          accepted_at = excluded.accepted_at,\n          result_sequence = excluded.result_sequence,\n          status = excluded.status,\n          error = excluded.error\n      `,\n  });\n\n  const findReceiptByCommandId = SqlSchema.findOneOption({\n    Request: GetByCommandIdInput,\n    Result: OrchestrationCommandReceipt,\n    execute: ({ commandId }) =>\n      sql`\n        SELECT\n          command_id AS \"commandId\",\n          aggregate_kind AS \"aggregateKind\",\n          aggregate_id AS \"aggregateId\",\n          accepted_at AS \"acceptedAt\",\n          result_sequence AS \"resultSequence\",\n          status,\n          error\n        FROM orchestration_command_receipts\n        WHERE command_id = ${commandId}\n      `,\n  });\n\n  const upsert: OrchestrationCommandReceiptRepositoryShape[\"upsert\"] = (receipt) =>\n    upsertReceiptRow(receipt).pipe(\n      Effect.mapError(toPersistenceSqlError(\"OrchestrationCommandReceiptRepository.upsert:query\")),\n    );\n\n  const getByCommandId: OrchestrationCommandReceiptRepositoryShape[\"getByCommandId\"] = (input) =>\n    findReceiptByCommandId(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"OrchestrationCommandReceiptRepository.getByCommandId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    getByCommandId,\n  } satisfies OrchestrationCommandReceiptRepositoryShape;\n});\n\nexport const OrchestrationCommandReceiptRepositoryLive = Layer.effect(\n  OrchestrationCommandReceiptRepository,\n  makeOrchestrationCommandReceiptRepository,\n);\n","/**\n * OrchestrationEventStore - Event store interface for orchestration events.\n *\n * Owns durable append/replay access to the orchestration event stream. It does\n * not reduce events into read models or apply command validation rules.\n *\n * Uses Effect `Context.Service` for dependency injection and exposes typed\n * persistence/decode errors for event append and replay operations.\n *\n * @module OrchestrationEventStore\n */\nimport { OrchestrationEvent } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { OrchestrationEventStoreError } from \"../Errors.ts\";\n\n/**\n * OrchestrationEventStoreShape - Service API for orchestration event persistence.\n */\nexport interface OrchestrationEventStoreShape {\n  /**\n   * Persist a new orchestration event.\n   *\n   * @param event - Event payload without sequence (assigned by storage).\n   * @returns Effect containing the stored event with assigned sequence.\n   *\n   * Actor kind is inferred from command/metadata before persistence.\n   */\n  readonly append: (\n    event: Omit<OrchestrationEvent, \"sequence\">,\n  ) => Effect.Effect<OrchestrationEvent, OrchestrationEventStoreError>;\n\n  /**\n   * Replay events after the provided sequence.\n   *\n   * @param sequenceExclusive - Sequence cursor (exclusive).\n   * @param limit - Maximum number of events to emit.\n   * @returns Stream containing ordered events.\n   *\n   * Reads in fixed-size pages and normalizes non-integer/negative limits.\n   */\n  readonly readFromSequence: (\n    sequenceExclusive: number,\n    limit?: number,\n  ) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;\n\n  /**\n   * Read all events from the beginning of the stream.\n   *\n   * @returns Stream containing all stored events.\n   */\n  readonly readAll: () => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;\n}\n\n/**\n * OrchestrationEventStore - Service tag for orchestration event persistence.\n *\n * @example\n * ```ts\n * const program = Effect.gen(function* () {\n *   const events = yield* OrchestrationEventStore\n *   return yield* Stream.runCollect(events.readAll())\n * })\n * ```\n */\nexport class OrchestrationEventStore extends Context.Service<\n  OrchestrationEventStore,\n  OrchestrationEventStoreShape\n>()(\"t3/persistence/Services/OrchestrationEventStore\") {}\n","import {\n  CommandId,\n  EventId,\n  IsoDateTime,\n  NonNegativeInt,\n  OrchestrationActorKind,\n  OrchestrationAggregateKind,\n  OrchestrationEvent,\n  OrchestrationEventMetadata,\n  OrchestrationEventType,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n  toPersistenceDecodeError,\n  toPersistenceSqlError,\n  type OrchestrationEventStoreError,\n} from \"../Errors.ts\";\nimport {\n  OrchestrationEventStore,\n  type OrchestrationEventStoreShape,\n} from \"../Services/OrchestrationEventStore.ts\";\n\nconst decodeEvent = Schema.decodeUnknownEffect(OrchestrationEvent);\nconst UnknownFromJsonString = Schema.fromJsonString(Schema.Unknown);\nconst EventMetadataFromJsonString = Schema.fromJsonString(OrchestrationEventMetadata);\n\nconst AppendEventRequestSchema = Schema.Struct({\n  eventId: EventId,\n  aggregateKind: OrchestrationAggregateKind,\n  streamId: Schema.Union([ProjectId, ThreadId]),\n  type: OrchestrationEventType,\n  causationEventId: Schema.NullOr(EventId),\n  correlationId: Schema.NullOr(CommandId),\n  actorKind: OrchestrationActorKind,\n  occurredAt: IsoDateTime,\n  commandId: Schema.NullOr(CommandId),\n  payloadJson: UnknownFromJsonString,\n  metadataJson: EventMetadataFromJsonString,\n});\n\nconst OrchestrationEventPersistedRowSchema = Schema.Struct({\n  sequence: NonNegativeInt,\n  eventId: EventId,\n  type: OrchestrationEventType,\n  aggregateKind: OrchestrationAggregateKind,\n  aggregateId: Schema.Union([ProjectId, ThreadId]),\n  occurredAt: IsoDateTime,\n  commandId: Schema.NullOr(CommandId),\n  causationEventId: Schema.NullOr(EventId),\n  correlationId: Schema.NullOr(CommandId),\n  payload: UnknownFromJsonString,\n  metadata: EventMetadataFromJsonString,\n});\n\nconst ReadFromSequenceRequestSchema = Schema.Struct({\n  sequenceExclusive: NonNegativeInt,\n  limit: Schema.Number,\n});\nconst DEFAULT_READ_FROM_SEQUENCE_LIMIT = 1_000;\nconst READ_PAGE_SIZE = 500;\n\nfunction inferActorKind(\n  event: Omit<OrchestrationEvent, \"sequence\">,\n): Schema.Schema.Type<typeof OrchestrationActorKind> {\n  if (event.commandId !== null && event.commandId.startsWith(\"provider:\")) {\n    return \"provider\";\n  }\n  if (event.commandId !== null && event.commandId.startsWith(\"server:\")) {\n    return \"server\";\n  }\n  if (\n    event.metadata.providerTurnId !== undefined ||\n    event.metadata.providerItemId !== undefined ||\n    event.metadata.adapterKey !== undefined\n  ) {\n    return \"provider\";\n  }\n  if (event.commandId === null) {\n    return \"server\";\n  }\n  return \"client\";\n}\n\nfunction toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {\n  return (cause: unknown): OrchestrationEventStoreError =>\n    Schema.isSchemaError(cause)\n      ? toPersistenceDecodeError(decodeOperation)(cause)\n      : toPersistenceSqlError(sqlOperation)(cause);\n}\n\nconst makeEventStore = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const appendEventRow = SqlSchema.findOne({\n    Request: AppendEventRequestSchema,\n    Result: OrchestrationEventPersistedRowSchema,\n    execute: (request) =>\n      sql`\n        INSERT INTO orchestration_events (\n          event_id,\n          aggregate_kind,\n          stream_id,\n          stream_version,\n          event_type,\n          occurred_at,\n          command_id,\n          causation_event_id,\n          correlation_id,\n          actor_kind,\n          payload_json,\n          metadata_json\n        )\n        VALUES (\n          ${request.eventId},\n          ${request.aggregateKind},\n          ${request.streamId},\n          COALESCE(\n            (\n              SELECT stream_version + 1\n              FROM orchestration_events\n              WHERE aggregate_kind = ${request.aggregateKind}\n                AND stream_id = ${request.streamId}\n              ORDER BY stream_version DESC\n              LIMIT 1\n            ),\n            0\n          ),\n          ${request.type},\n          ${request.occurredAt},\n          ${request.commandId},\n          ${request.causationEventId},\n          ${request.correlationId},\n          ${request.actorKind},\n          ${request.payloadJson},\n          ${request.metadataJson}\n        )\n        RETURNING\n          sequence,\n          event_id AS \"eventId\",\n          event_type AS \"type\",\n          aggregate_kind AS \"aggregateKind\",\n          stream_id AS \"aggregateId\",\n          occurred_at AS \"occurredAt\",\n          command_id AS \"commandId\",\n          causation_event_id AS \"causationEventId\",\n          correlation_id AS \"correlationId\",\n          payload_json AS \"payload\",\n          metadata_json AS \"metadata\"\n      `,\n  });\n\n  const readEventRowsFromSequence = SqlSchema.findAll({\n    Request: ReadFromSequenceRequestSchema,\n    Result: OrchestrationEventPersistedRowSchema,\n    execute: (request) =>\n      sql`\n        SELECT\n          sequence,\n          event_id AS \"eventId\",\n          event_type AS \"type\",\n          aggregate_kind AS \"aggregateKind\",\n          stream_id AS \"aggregateId\",\n          occurred_at AS \"occurredAt\",\n          command_id AS \"commandId\",\n          causation_event_id AS \"causationEventId\",\n          correlation_id AS \"correlationId\",\n          payload_json AS \"payload\",\n          metadata_json AS \"metadata\"\n        FROM orchestration_events\n        WHERE sequence > ${request.sequenceExclusive}\n        ORDER BY sequence ASC\n        LIMIT ${request.limit}\n      `,\n  });\n\n  const append: OrchestrationEventStoreShape[\"append\"] = (event) =>\n    appendEventRow({\n      eventId: event.eventId,\n      aggregateKind: event.aggregateKind,\n      streamId: event.aggregateId,\n      type: event.type,\n      causationEventId: event.causationEventId,\n      correlationId: event.correlationId,\n      actorKind: inferActorKind(event),\n      occurredAt: event.occurredAt,\n      commandId: event.commandId,\n      payloadJson: event.payload,\n      metadataJson: event.metadata,\n    }).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"OrchestrationEventStore.append:insert\",\n          \"OrchestrationEventStore.append:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((row) =>\n        decodeEvent(row).pipe(\n          Effect.mapError(toPersistenceDecodeError(\"OrchestrationEventStore.append:rowToEvent\")),\n        ),\n      ),\n    );\n\n  const readFromSequence: OrchestrationEventStoreShape[\"readFromSequence\"] = (\n    sequenceExclusive,\n    limit = DEFAULT_READ_FROM_SEQUENCE_LIMIT,\n  ) => {\n    const normalizedLimit = Math.max(0, Math.floor(limit));\n    if (normalizedLimit === 0) {\n      return Stream.empty;\n    }\n    const readPage = (\n      cursor: number,\n      remaining: number,\n    ): Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError> =>\n      Stream.fromEffect(\n        readEventRowsFromSequence({\n          sequenceExclusive: cursor,\n          limit: Math.min(remaining, READ_PAGE_SIZE),\n        }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"OrchestrationEventStore.readFromSequence:query\",\n              \"OrchestrationEventStore.readFromSequence:decodeRows\",\n            ),\n          ),\n          Effect.flatMap((rows) =>\n            Effect.forEach(rows, (row) =>\n              decodeEvent(row).pipe(\n                Effect.mapError(\n                  toPersistenceDecodeError(\"OrchestrationEventStore.readFromSequence:rowToEvent\"),\n                ),\n              ),\n            ),\n          ),\n        ),\n      ).pipe(\n        Stream.flatMap((events) => {\n          if (events.length === 0) {\n            return Stream.empty;\n          }\n          const nextRemaining = remaining - events.length;\n          if (nextRemaining <= 0) {\n            return Stream.fromIterable(events);\n          }\n          return Stream.concat(\n            Stream.fromIterable(events),\n            readPage(events[events.length - 1]!.sequence, nextRemaining),\n          );\n        }),\n      );\n\n    return readPage(sequenceExclusive, normalizedLimit);\n  };\n\n  return {\n    append,\n    readFromSequence,\n    readAll: () => readFromSequence(0, Number.MAX_SAFE_INTEGER),\n  } satisfies OrchestrationEventStoreShape;\n});\n\nexport const OrchestrationEventStoreLive = Layer.effect(OrchestrationEventStore, makeEventStore);\n","import * as Cause from \"effect/Cause\";\nimport * as Exit from \"effect/Exit\";\n\nexport type MetricAttributeValue = string;\nexport type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;\nexport type ObservabilityOutcome = \"success\" | \"failure\" | \"interrupt\";\n\nexport function compactMetricAttributes(\n  attributes: Readonly<Record<string, unknown>>,\n): MetricAttributes {\n  return Object.fromEntries(\n    Object.entries(attributes).flatMap(([key, value]) => {\n      if (value === undefined || value === null) {\n        return [];\n      }\n      if (typeof value === \"string\") {\n        return [[key, value]];\n      }\n      if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n        return [[key, String(value)]];\n      }\n      return [];\n    }),\n  );\n}\n\nexport function outcomeFromExit(exit: Exit.Exit<unknown, unknown>): ObservabilityOutcome {\n  if (Exit.isSuccess(exit)) {\n    return \"success\";\n  }\n  return Cause.hasInterruptsOnly(exit.cause) ? \"interrupt\" : \"failure\";\n}\n\nexport function normalizeModelMetricLabel(model: string | null | undefined): string | undefined {\n  const normalized = model?.trim().toLowerCase();\n  if (!normalized) {\n    return undefined;\n  }\n  if (normalized.includes(\"gpt\")) {\n    return \"gpt\";\n  }\n  if (normalized.includes(\"claude\")) {\n    return \"claude\";\n  }\n  if (normalized.includes(\"gemini\")) {\n    return \"gemini\";\n  }\n  return \"other\";\n}\n","import * as Clock from \"effect/Clock\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Metric from \"effect/Metric\";\nimport { dual } from \"effect/Function\";\n\nimport {\n  compactMetricAttributes,\n  normalizeModelMetricLabel,\n  outcomeFromExit,\n} from \"./Attributes.ts\";\n\nexport const rpcRequestsTotal = Metric.counter(\"t3_rpc_requests_total\", {\n  description: \"Total RPC requests handled by the websocket RPC server.\",\n});\n\nexport const rpcRequestDuration = Metric.timer(\"t3_rpc_request_duration\", {\n  description: \"RPC request handling duration.\",\n});\n\nexport const orchestrationCommandsTotal = Metric.counter(\"t3_orchestration_commands_total\", {\n  description: \"Total orchestration commands dispatched.\",\n});\n\nexport const orchestrationCommandDuration = Metric.timer(\"t3_orchestration_command_duration\", {\n  description: \"Orchestration command dispatch duration.\",\n});\n\nexport const orchestrationCommandAckDuration = Metric.timer(\n  \"t3_orchestration_command_ack_duration\",\n  {\n    description:\n      \"Time from orchestration command dispatch to the first committed domain event emitted for that command.\",\n  },\n);\n\nexport const orchestrationEventsProcessedTotal = Metric.counter(\n  \"t3_orchestration_events_processed_total\",\n  {\n    description: \"Total orchestration intent events processed by runtime reactors.\",\n  },\n);\n\nexport const providerSessionsTotal = Metric.counter(\"t3_provider_sessions_total\", {\n  description: \"Total provider session lifecycle operations.\",\n});\n\nexport const providerTurnsTotal = Metric.counter(\"t3_provider_turns_total\", {\n  description: \"Total provider turn lifecycle operations.\",\n});\n\nexport const providerTurnDuration = Metric.timer(\"t3_provider_turn_duration\", {\n  description: \"Provider turn request duration.\",\n});\n\nexport const providerRuntimeEventsTotal = Metric.counter(\"t3_provider_runtime_events_total\", {\n  description: \"Total canonical provider runtime events processed.\",\n});\n\nexport const gitCommandsTotal = Metric.counter(\"t3_git_commands_total\", {\n  description: \"Total git commands executed by the server runtime.\",\n});\n\nexport const gitCommandDuration = Metric.timer(\"t3_git_command_duration\", {\n  description: \"Git command execution duration.\",\n});\n\nexport const terminalSessionsTotal = Metric.counter(\"t3_terminal_sessions_total\", {\n  description: \"Total terminal sessions started.\",\n});\n\nexport const terminalRestartsTotal = Metric.counter(\"t3_terminal_restarts_total\", {\n  description: \"Total terminal restart requests handled.\",\n});\n\nexport const metricAttributes = (\n  attributes: Readonly<Record<string, unknown>>,\n): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));\n\nexport const increment = (\n  metric: Metric.Metric<number, unknown>,\n  attributes: Readonly<Record<string, unknown>>,\n  amount = 1,\n) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);\n\nexport interface WithMetricsOptions {\n  readonly counter?: Metric.Metric<number, unknown>;\n  readonly timer?: Metric.Metric<Duration.Duration, unknown>;\n  readonly attributes?:\n    | Readonly<Record<string, unknown>>\n    | (() => Readonly<Record<string, unknown>>);\n  readonly outcomeAttributes?: (\n    outcome: ReturnType<typeof outcomeFromExit>,\n  ) => Readonly<Record<string, unknown>>;\n}\n\nconst withMetricsImpl = <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n  options: WithMetricsOptions,\n): Effect.Effect<A, E, R> =>\n  Effect.gen(function* () {\n    const startedAt = yield* Clock.currentTimeNanos;\n    const exit = yield* Effect.exit(effect);\n    const endedAt = yield* Clock.currentTimeNanos;\n    const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;\n    const duration = Duration.nanos(elapsedNanos);\n    const baseAttributes =\n      typeof options.attributes === \"function\" ? options.attributes() : (options.attributes ?? {});\n\n    if (options.timer) {\n      yield* Metric.update(\n        Metric.withAttributes(options.timer, metricAttributes(baseAttributes)),\n        duration,\n      );\n    }\n\n    if (options.counter) {\n      const outcome = outcomeFromExit(exit);\n      yield* Metric.update(\n        Metric.withAttributes(\n          options.counter,\n          metricAttributes({\n            ...baseAttributes,\n            outcome,\n            ...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}),\n          }),\n        ),\n        1,\n      );\n    }\n\n    if (Exit.isSuccess(exit)) {\n      return exit.value;\n    }\n    return yield* Effect.failCause(exit.cause);\n  });\n\nexport const withMetrics: {\n  <A, E, R>(\n    options: WithMetricsOptions,\n  ): (effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n  <A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;\n} = dual(2, withMetricsImpl);\n\nexport const providerMetricAttributes = (\n  provider: string,\n  extra?: Readonly<Record<string, unknown>>,\n) =>\n  compactMetricAttributes({\n    provider,\n    ...extra,\n  });\n\nexport const providerTurnMetricAttributes = (input: {\n  readonly provider: string;\n  readonly model: string | null | undefined;\n  readonly extra?: Readonly<Record<string, unknown>>;\n}) => {\n  const modelFamily = normalizeModelMetricLabel(input.model);\n  return compactMetricAttributes({\n    provider: input.provider,\n    ...(modelFamily ? { modelFamily } : {}),\n    ...input.extra,\n  });\n};\n","import * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { ProjectionRepositoryError } from \"../persistence/Errors.ts\";\n\nexport class OrchestrationCommandJsonParseError extends Schema.TaggedErrorClass<OrchestrationCommandJsonParseError>()(\n  \"OrchestrationCommandJsonParseError\",\n  {\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Invalid orchestration command JSON: ${this.detail}`;\n  }\n}\n\nexport class OrchestrationCommandDecodeError extends Schema.TaggedErrorClass<OrchestrationCommandDecodeError>()(\n  \"OrchestrationCommandDecodeError\",\n  {\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Invalid orchestration command payload: ${this.issue}`;\n  }\n}\n\nexport class OrchestrationCommandInvariantError extends Schema.TaggedErrorClass<OrchestrationCommandInvariantError>()(\n  \"OrchestrationCommandInvariantError\",\n  {\n    commandType: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Orchestration command invariant failed (${this.commandType}): ${this.detail}`;\n  }\n}\n\nexport class OrchestrationCommandPreviouslyRejectedError extends Schema.TaggedErrorClass<OrchestrationCommandPreviouslyRejectedError>()(\n  \"OrchestrationCommandPreviouslyRejectedError\",\n  {\n    commandId: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Command previously rejected (${this.commandId}): ${this.detail}`;\n  }\n}\n\nexport class OrchestrationProjectorDecodeError extends Schema.TaggedErrorClass<OrchestrationProjectorDecodeError>()(\n  \"OrchestrationProjectorDecodeError\",\n  {\n    eventType: Schema.String,\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Projector decode failed for ${this.eventType}: ${this.issue}`;\n  }\n}\n\nexport class OrchestrationListenerCallbackError extends Schema.TaggedErrorClass<OrchestrationListenerCallbackError>()(\n  \"OrchestrationListenerCallbackError\",\n  {\n    listener: Schema.Literals([\"read-model\", \"domain-event\"]),\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Orchestration ${this.listener} listener failed: ${this.detail}`;\n  }\n}\n\nexport type OrchestrationDispatchError =\n  | ProjectionRepositoryError\n  | OrchestrationCommandInvariantError\n  | OrchestrationCommandPreviouslyRejectedError\n  | OrchestrationProjectorDecodeError\n  | OrchestrationListenerCallbackError;\n\nexport type OrchestrationEngineError =\n  | OrchestrationDispatchError\n  | OrchestrationCommandJsonParseError\n  | OrchestrationCommandDecodeError;\n\nexport function toOrchestrationCommandDecodeError(error: Schema.SchemaError) {\n  return new OrchestrationCommandDecodeError({\n    issue: SchemaIssue.makeFormatterDefault()(error.issue),\n    cause: error,\n  });\n}\n\nexport function toProjectorDecodeError(eventType: string) {\n  return (error: Schema.SchemaError): OrchestrationProjectorDecodeError =>\n    new OrchestrationProjectorDecodeError({\n      eventType,\n      issue: SchemaIssue.makeFormatterDefault()(error.issue),\n      cause: error,\n    });\n}\n\nexport function toOrchestrationJsonParseError(cause: unknown) {\n  return new OrchestrationCommandJsonParseError({\n    detail: `Failed to parse orchestration command JSON`,\n    cause,\n  });\n}\n\nexport function toListenerCallbackError(listener: \"read-model\" | \"domain-event\") {\n  return (cause: unknown): OrchestrationListenerCallbackError =>\n    new OrchestrationListenerCallbackError({\n      listener,\n      detail: `Failed to invoke orchestration ${listener} listener`,\n      cause,\n    });\n}\n","export function isWindowsDrivePath(value: string): boolean {\n  return /^[a-zA-Z]:([/\\\\]|$)/.test(value);\n}\n\nexport function isUncPath(value: string): boolean {\n  return value.startsWith(\"\\\\\\\\\");\n}\n\nexport function isWindowsAbsolutePath(value: string): boolean {\n  return isUncPath(value) || isWindowsDrivePath(value);\n}\n\nexport function isExplicitRelativePath(value: string): boolean {\n  return (\n    value === \".\" ||\n    value === \"..\" ||\n    value.startsWith(\"./\") ||\n    value.startsWith(\"../\") ||\n    value.startsWith(\".\\\\\") ||\n    value.startsWith(\"..\\\\\")\n  );\n}\n\nfunction isRootPath(value: string): boolean {\n  return value === \"/\" || value === \"\\\\\" || /^[a-zA-Z]:[/\\\\]?$/.test(value);\n}\n\nfunction trimTrailingPathSeparators(value: string): string {\n  if (value.length === 0 || isRootPath(value)) {\n    return value;\n  }\n  const trimmed = value.startsWith(\"/\")\n    ? value.replace(/\\/+$/g, \"\")\n    : value.replace(/[\\\\/]+$/g, \"\");\n  if (trimmed.length === 0) {\n    return value;\n  }\n  return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\\\` : trimmed;\n}\n\nexport function normalizeProjectPathForDispatch(value: string): string {\n  return trimTrailingPathSeparators(value.trim());\n}\n\nexport function normalizeProjectPathForComparison(value: string): string {\n  const normalized = normalizeProjectPathForDispatch(value);\n  if (isWindowsDrivePath(normalized) || isUncPath(normalized)) {\n    return normalized.replaceAll(\"/\", \"\\\\\").toLowerCase();\n  }\n  return normalized;\n}\n","import type {\n  OrchestrationCommand,\n  OrchestrationProject,\n  OrchestrationReadModel,\n  OrchestrationThread,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport { normalizeProjectPathForComparison } from \"@t3tools/shared/path\";\nimport * as Effect from \"effect/Effect\";\n\nimport { OrchestrationCommandInvariantError } from \"./Errors.ts\";\n\nfunction invariantError(commandType: string, detail: string): OrchestrationCommandInvariantError {\n  return new OrchestrationCommandInvariantError({\n    commandType,\n    detail,\n  });\n}\n\nexport function findThreadById(\n  readModel: OrchestrationReadModel,\n  threadId: ThreadId,\n): OrchestrationThread | undefined {\n  return readModel.threads.find((thread) => thread.id === threadId);\n}\n\nexport function findProjectById(\n  readModel: OrchestrationReadModel,\n  projectId: ProjectId,\n): OrchestrationProject | undefined {\n  return readModel.projects.find((project) => project.id === projectId);\n}\n\nexport function listThreadsByProjectId(\n  readModel: OrchestrationReadModel,\n  projectId: ProjectId,\n): ReadonlyArray<OrchestrationThread> {\n  return readModel.threads.filter((thread) => thread.projectId === projectId);\n}\n\nexport function requireProject(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly projectId: ProjectId;\n}): Effect.Effect<OrchestrationProject, OrchestrationCommandInvariantError> {\n  const project = findProjectById(input.readModel, input.projectId);\n  if (project) {\n    return Effect.succeed(project);\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Project '${input.projectId}' does not exist for command '${input.command.type}'.`,\n    ),\n  );\n}\n\nexport function requireProjectAbsent(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly projectId: ProjectId;\n}): Effect.Effect<void, OrchestrationCommandInvariantError> {\n  if (!findProjectById(input.readModel, input.projectId)) {\n    return Effect.void;\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Project '${input.projectId}' already exists and cannot be created twice.`,\n    ),\n  );\n}\n\nexport function requireActiveProjectWorkspaceRootAbsent(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly workspaceRoot: string;\n  readonly exceptProjectId?: ProjectId;\n}): Effect.Effect<void, OrchestrationCommandInvariantError> {\n  const normalizedWorkspaceRoot = normalizeProjectPathForComparison(input.workspaceRoot);\n  const existingProject = input.readModel.projects.find(\n    (project) =>\n      project.deletedAt === null &&\n      normalizeProjectPathForComparison(project.workspaceRoot) === normalizedWorkspaceRoot &&\n      project.id !== input.exceptProjectId,\n  );\n  if (existingProject === undefined) {\n    return Effect.void;\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Active project '${existingProject.id}' already exists for workspace root '${normalizedWorkspaceRoot}'.`,\n    ),\n  );\n}\n\nexport function requireThread(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly threadId: ThreadId;\n}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {\n  const thread = findThreadById(input.readModel, input.threadId);\n  if (thread) {\n    return Effect.succeed(thread);\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Thread '${input.threadId}' does not exist for command '${input.command.type}'.`,\n    ),\n  );\n}\n\nexport function requireThreadArchived(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly threadId: ThreadId;\n}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {\n  return requireThread(input).pipe(\n    Effect.flatMap((thread) =>\n      thread.archivedAt !== null\n        ? Effect.succeed(thread)\n        : Effect.fail(\n            invariantError(\n              input.command.type,\n              `Thread '${input.threadId}' is not archived for command '${input.command.type}'.`,\n            ),\n          ),\n    ),\n  );\n}\n\nexport function requireThreadNotArchived(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly threadId: ThreadId;\n}): Effect.Effect<OrchestrationThread, OrchestrationCommandInvariantError> {\n  return requireThread(input).pipe(\n    Effect.flatMap((thread) =>\n      thread.archivedAt === null\n        ? Effect.succeed(thread)\n        : Effect.fail(\n            invariantError(\n              input.command.type,\n              `Thread '${input.threadId}' is already archived and cannot handle command '${input.command.type}'.`,\n            ),\n          ),\n    ),\n  );\n}\n\nexport function requireThreadAbsent(input: {\n  readonly readModel: OrchestrationReadModel;\n  readonly command: OrchestrationCommand;\n  readonly threadId: ThreadId;\n}): Effect.Effect<void, OrchestrationCommandInvariantError> {\n  if (!findThreadById(input.readModel, input.threadId)) {\n    return Effect.void;\n  }\n  return Effect.fail(\n    invariantError(\n      input.command.type,\n      `Thread '${input.threadId}' already exists and cannot be created twice.`,\n    ),\n  );\n}\n\nexport function requireNonNegativeInteger(input: {\n  readonly commandType: OrchestrationCommand[\"type\"];\n  readonly field: string;\n  readonly value: number;\n}): Effect.Effect<void, OrchestrationCommandInvariantError> {\n  if (Number.isInteger(input.value) && input.value >= 0) {\n    return Effect.void;\n  }\n  return Effect.fail(\n    invariantError(\n      input.commandType,\n      `${input.field} must be an integer greater than or equal to 0.`,\n    ),\n  );\n}\n","import {\n  ProjectCreatedPayload as ContractsProjectCreatedPayloadSchema,\n  ProjectMetaUpdatedPayload as ContractsProjectMetaUpdatedPayloadSchema,\n  ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,\n  ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,\n  ThreadArchivedPayload as ContractsThreadArchivedPayloadSchema,\n  ThreadSettledPayload as ContractsThreadSettledPayloadSchema,\n  ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,\n  ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,\n  ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,\n  ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,\n  ThreadUnarchivedPayload as ContractsThreadUnarchivedPayloadSchema,\n  ThreadUnsettledPayload as ContractsThreadUnsettledPayloadSchema,\n  ThreadSnoozedPayload as ContractsThreadSnoozedPayloadSchema,\n  ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,\n  ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,\n  ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,\n  ThreadPinReorderedPayload as ContractsThreadPinReorderedPayloadSchema,\n  ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,\n  ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,\n  ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,\n  ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,\n  ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,\n  ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,\n  ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,\n  ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,\n  ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,\n  ThreadCheckpointRevertRequestedPayload as ContractsThreadCheckpointRevertRequestedPayloadSchema,\n  ThreadSessionStopRequestedPayload as ContractsThreadSessionStopRequestedPayloadSchema,\n} from \"@t3tools/contracts\";\n\n// Server-internal alias surface, backed by contract schemas as the source of truth.\nexport const ProjectCreatedPayload = ContractsProjectCreatedPayloadSchema;\nexport const ProjectMetaUpdatedPayload = ContractsProjectMetaUpdatedPayloadSchema;\nexport const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;\n\nexport const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;\nexport const ThreadArchivedPayload = ContractsThreadArchivedPayloadSchema;\nexport const ThreadSettledPayload = ContractsThreadSettledPayloadSchema;\nexport const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;\nexport const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;\nexport const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;\nexport const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;\nexport const ThreadUnarchivedPayload = ContractsThreadUnarchivedPayloadSchema;\nexport const ThreadUnsettledPayload = ContractsThreadUnsettledPayloadSchema;\nexport const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;\nexport const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;\nexport const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;\nexport const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;\nexport const ThreadPinReorderedPayload = ContractsThreadPinReorderedPayloadSchema;\n\nexport const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;\nexport const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;\nexport const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;\nexport const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;\nexport const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;\nexport const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;\n\nexport const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;\nexport const ThreadTurnInterruptRequestedPayload =\n  ContractsThreadTurnInterruptRequestedPayloadSchema;\nexport const ThreadApprovalResponseRequestedPayload =\n  ContractsThreadApprovalResponseRequestedPayloadSchema;\nexport const ThreadCheckpointRevertRequestedPayload =\n  ContractsThreadCheckpointRevertRequestedPayloadSchema;\nexport const ThreadSessionStopRequestedPayload = ContractsThreadSessionStopRequestedPayloadSchema;\n","import type { OrchestrationEvent, OrchestrationReadModel, ThreadId } from \"@t3tools/contracts\";\nimport {\n  OrchestrationCheckpointSummary,\n  OrchestrationMessage,\n  OrchestrationSession,\n  OrchestrationThread,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport { toProjectorDecodeError, type OrchestrationProjectorDecodeError } from \"./Errors.ts\";\nimport {\n  MessageSentPayloadSchema,\n  ProjectCreatedPayload,\n  ProjectDeletedPayload,\n  ProjectMetaUpdatedPayload,\n  ThreadActivityAppendedPayload,\n  ThreadArchivedPayload,\n  ThreadCreatedPayload,\n  ThreadDeletedPayload,\n  ThreadInteractionModeSetPayload,\n  ThreadMetaUpdatedPayload,\n  ThreadProposedPlanUpsertedPayload,\n  ThreadRuntimeModeSetPayload,\n  ThreadSettledPayload,\n  ThreadPinnedPayload,\n  ThreadPinReorderedPayload,\n  ThreadSnoozedPayload,\n  ThreadUnpinnedPayload,\n  ThreadUnarchivedPayload,\n  ThreadUnsettledPayload,\n  ThreadUnsnoozedPayload,\n  ThreadRevertedPayload,\n  ThreadSessionSetPayload,\n  ThreadTurnDiffCompletedPayload,\n} from \"./Schemas.ts\";\n\ntype ThreadPatch = Partial<Omit<OrchestrationThread, \"id\" | \"projectId\">>;\nconst MAX_THREAD_MESSAGES = 2_000;\nconst MAX_THREAD_CHECKPOINTS = 500;\n\nfunction checkpointStatusToLatestTurnState(status: \"ready\" | \"missing\" | \"error\") {\n  if (status === \"error\") return \"error\" as const;\n  if (status === \"missing\") return \"interrupted\" as const;\n  return \"completed\" as const;\n}\n\n/**\n * Turn state to settle a still-running latest turn with when its session\n * leaves the \"running\" status, or null while the session is (re)starting or\n * running and the turn must stay unsettled.\n */\nfunction settledTurnStateForSessionStatus(\n  status: OrchestrationSession[\"status\"],\n): \"completed\" | \"interrupted\" | \"error\" | null {\n  switch (status) {\n    case \"idle\":\n    case \"ready\":\n      return \"completed\";\n    case \"error\":\n      return \"error\";\n    case \"interrupted\":\n    case \"stopped\":\n      return \"interrupted\";\n    case \"starting\":\n    case \"running\":\n      return null;\n  }\n}\n\nfunction updateThread(\n  threads: ReadonlyArray<OrchestrationThread>,\n  threadId: ThreadId,\n  patch: ThreadPatch,\n): OrchestrationThread[] {\n  return threads.map((thread) => (thread.id === threadId ? { ...thread, ...patch } : thread));\n}\n\nfunction decodeForEvent<A>(\n  schema: Schema.Decoder<A, never>,\n  value: unknown,\n  eventType: OrchestrationEvent[\"type\"],\n  field: string,\n): Effect.Effect<A, OrchestrationProjectorDecodeError> {\n  return Schema.decodeUnknownEffect(schema)(value).pipe(\n    Effect.mapError(toProjectorDecodeError(`${eventType}:${field}`)),\n  );\n}\n\nfunction retainThreadMessagesAfterRevert(\n  messages: ReadonlyArray<OrchestrationMessage>,\n  retainedTurnIds: ReadonlySet<string>,\n  turnCount: number,\n): ReadonlyArray<OrchestrationMessage> {\n  const retainedMessageIds = new Set<string>();\n  for (const message of messages) {\n    if (message.role === \"system\") {\n      retainedMessageIds.add(message.id);\n      continue;\n    }\n    if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {\n      retainedMessageIds.add(message.id);\n    }\n  }\n\n  const retainedUserCount = messages.filter(\n    (message) => message.role === \"user\" && retainedMessageIds.has(message.id),\n  ).length;\n  const missingUserCount = Math.max(0, turnCount - retainedUserCount);\n  if (missingUserCount > 0) {\n    const fallbackUserMessages = messages\n      .filter(\n        (message) =>\n          message.role === \"user\" &&\n          !retainedMessageIds.has(message.id) &&\n          (message.turnId === null || retainedTurnIds.has(message.turnId)),\n      )\n      .toSorted(\n        (left, right) =>\n          left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),\n      )\n      .slice(0, missingUserCount);\n    for (const message of fallbackUserMessages) {\n      retainedMessageIds.add(message.id);\n    }\n  }\n\n  const retainedAssistantCount = messages.filter(\n    (message) => message.role === \"assistant\" && retainedMessageIds.has(message.id),\n  ).length;\n  const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);\n  if (missingAssistantCount > 0) {\n    const fallbackAssistantMessages = messages\n      .filter(\n        (message) =>\n          message.role === \"assistant\" &&\n          !retainedMessageIds.has(message.id) &&\n          (message.turnId === null || retainedTurnIds.has(message.turnId)),\n      )\n      .toSorted(\n        (left, right) =>\n          left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),\n      )\n      .slice(0, missingAssistantCount);\n    for (const message of fallbackAssistantMessages) {\n      retainedMessageIds.add(message.id);\n    }\n  }\n\n  return messages.filter((message) => retainedMessageIds.has(message.id));\n}\n\nfunction retainThreadActivitiesAfterRevert(\n  activities: ReadonlyArray<OrchestrationThread[\"activities\"][number]>,\n  retainedTurnIds: ReadonlySet<string>,\n): ReadonlyArray<OrchestrationThread[\"activities\"][number]> {\n  return activities.filter(\n    (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),\n  );\n}\n\nfunction retainThreadProposedPlansAfterRevert(\n  proposedPlans: ReadonlyArray<OrchestrationThread[\"proposedPlans\"][number]>,\n  retainedTurnIds: ReadonlySet<string>,\n): ReadonlyArray<OrchestrationThread[\"proposedPlans\"][number]> {\n  return proposedPlans.filter(\n    (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),\n  );\n}\n\nfunction compareThreadActivities(\n  left: OrchestrationThread[\"activities\"][number],\n  right: OrchestrationThread[\"activities\"][number],\n): number {\n  if (left.sequence !== undefined && right.sequence !== undefined) {\n    if (left.sequence !== right.sequence) {\n      return left.sequence - right.sequence;\n    }\n  } else if (left.sequence !== undefined) {\n    return 1;\n  } else if (right.sequence !== undefined) {\n    return -1;\n  }\n\n  return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);\n}\n\nexport function createEmptyReadModel(nowIso: string): OrchestrationReadModel {\n  return {\n    snapshotSequence: 0,\n    projects: [],\n    threads: [],\n    updatedAt: nowIso,\n  };\n}\n\nexport function projectEvent(\n  model: OrchestrationReadModel,\n  event: OrchestrationEvent,\n): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError> {\n  const nextBase: OrchestrationReadModel = {\n    ...model,\n    snapshotSequence: event.sequence,\n    updatedAt: event.occurredAt,\n  };\n\n  switch (event.type) {\n    case \"project.created\":\n      return decodeForEvent(ProjectCreatedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => {\n          const existing = nextBase.projects.find((entry) => entry.id === payload.projectId);\n          const nextProject = {\n            id: payload.projectId,\n            title: payload.title,\n            workspaceRoot: payload.workspaceRoot,\n            defaultModelSelection: payload.defaultModelSelection,\n            scripts: payload.scripts,\n            createdAt: payload.createdAt,\n            updatedAt: payload.updatedAt,\n            deletedAt: null,\n          };\n\n          return {\n            ...nextBase,\n            projects: existing\n              ? nextBase.projects.map((entry) =>\n                  entry.id === payload.projectId ? nextProject : entry,\n                )\n              : [...nextBase.projects, nextProject],\n          };\n        }),\n      );\n\n    case \"project.meta-updated\":\n      return decodeForEvent(ProjectMetaUpdatedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          projects: nextBase.projects.map((project) =>\n            project.id === payload.projectId\n              ? {\n                  ...project,\n                  ...(payload.title !== undefined ? { title: payload.title } : {}),\n                  ...(payload.workspaceRoot !== undefined\n                    ? { workspaceRoot: payload.workspaceRoot }\n                    : {}),\n                  ...(payload.defaultModelSelection !== undefined\n                    ? { defaultModelSelection: payload.defaultModelSelection }\n                    : {}),\n                  ...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),\n                  updatedAt: payload.updatedAt,\n                }\n              : project,\n          ),\n        })),\n      );\n\n    case \"project.deleted\":\n      return decodeForEvent(ProjectDeletedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          projects: nextBase.projects.map((project) =>\n            project.id === payload.projectId\n              ? {\n                  ...project,\n                  deletedAt: payload.deletedAt,\n                  updatedAt: payload.deletedAt,\n                }\n              : project,\n          ),\n        })),\n      );\n\n    case \"thread.created\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          ThreadCreatedPayload,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread: OrchestrationThread = yield* decodeForEvent(\n          OrchestrationThread,\n          {\n            id: payload.threadId,\n            projectId: payload.projectId,\n            title: payload.title,\n            modelSelection: payload.modelSelection,\n            runtimeMode: payload.runtimeMode,\n            interactionMode: payload.interactionMode,\n            branch: payload.branch,\n            worktreePath: payload.worktreePath,\n            latestTurn: null,\n            createdAt: payload.createdAt,\n            updatedAt: payload.updatedAt,\n            archivedAt: null,\n            settledOverride: null,\n            settledAt: null,\n            snoozedUntil: null,\n            snoozedAt: null,\n            deletedAt: null,\n            messages: [],\n            activities: [],\n            checkpoints: [],\n            session: null,\n          },\n          event.type,\n          \"thread\",\n        );\n        const existing = nextBase.threads.find((entry) => entry.id === thread.id);\n        return {\n          ...nextBase,\n          threads: existing\n            ? nextBase.threads.map((entry) => (entry.id === thread.id ? thread : entry))\n            : [...nextBase.threads, thread],\n        };\n      });\n\n    case \"thread.deleted\":\n      return decodeForEvent(ThreadDeletedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            deletedAt: payload.deletedAt,\n            updatedAt: payload.deletedAt,\n          }),\n        })),\n      );\n\n    case \"thread.archived\":\n      return decodeForEvent(ThreadArchivedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            archivedAt: payload.archivedAt,\n            titleRegeneration: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.unarchived\":\n      return decodeForEvent(ThreadUnarchivedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            archivedAt: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.settled\":\n      return decodeForEvent(ThreadSettledPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            settledOverride: \"settled\",\n            settledAt: payload.settledAt,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.unsettled\":\n      return decodeForEvent(ThreadUnsettledPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            settledOverride: payload.reason === \"user\" ? \"active\" : null,\n            settledAt: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.snoozed\":\n      return decodeForEvent(ThreadSnoozedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            snoozedUntil: payload.snoozedUntil,\n            snoozedAt: payload.snoozedAt,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.unsnoozed\":\n      return decodeForEvent(ThreadUnsnoozedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            snoozedUntil: null,\n            snoozedAt: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.pinned\":\n      return decodeForEvent(ThreadPinnedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            pinnedAt: payload.pinnedAt,\n            ...(payload.pinOrderKey !== undefined ? { pinOrderKey: payload.pinOrderKey } : {}),\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.unpinned\":\n      return decodeForEvent(ThreadUnpinnedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            pinnedAt: null,\n            // Unpin clears the slot: re-pinning is \"pin again\", not \"restore\n            // an ancient position\".\n            pinOrderKey: null,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.pin-reordered\":\n      return decodeForEvent(ThreadPinReorderedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            pinOrderKey: payload.orderKey,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.meta-updated\":\n      return decodeForEvent(ThreadMetaUpdatedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            ...(payload.title !== undefined ? { title: payload.title } : {}),\n            ...(payload.titleRegeneration !== undefined\n              ? { titleRegeneration: payload.titleRegeneration }\n              : {}),\n            ...(payload.modelSelection !== undefined\n              ? { modelSelection: payload.modelSelection }\n              : {}),\n            ...(payload.branch !== undefined ? { branch: payload.branch } : {}),\n            ...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.runtime-mode-set\":\n      return decodeForEvent(ThreadRuntimeModeSetPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            runtimeMode: payload.runtimeMode,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.interaction-mode-set\":\n      return decodeForEvent(\n        ThreadInteractionModeSetPayload,\n        event.payload,\n        event.type,\n        \"payload\",\n      ).pipe(\n        Effect.map((payload) => ({\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            interactionMode: payload.interactionMode,\n            updatedAt: payload.updatedAt,\n          }),\n        })),\n      );\n\n    case \"thread.message-sent\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          MessageSentPayloadSchema,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n        if (!thread) {\n          return nextBase;\n        }\n\n        const message: OrchestrationMessage = yield* decodeForEvent(\n          OrchestrationMessage,\n          {\n            id: payload.messageId,\n            role: payload.role,\n            text: payload.text,\n            ...(payload.attachments !== undefined ? { attachments: payload.attachments } : {}),\n            turnId: payload.turnId,\n            streaming: payload.streaming,\n            createdAt: payload.createdAt,\n            updatedAt: payload.updatedAt,\n          },\n          event.type,\n          \"message\",\n        );\n\n        const existingMessage = thread.messages.find((entry) => entry.id === message.id);\n        const messages = existingMessage\n          ? thread.messages.map((entry) =>\n              entry.id === message.id\n                ? {\n                    ...entry,\n                    text: message.streaming\n                      ? `${entry.text}${message.text}`\n                      : message.text.length > 0\n                        ? message.text\n                        : entry.text,\n                    streaming: message.streaming,\n                    updatedAt: message.updatedAt,\n                    turnId: message.turnId,\n                    ...(message.attachments !== undefined\n                      ? { attachments: message.attachments }\n                      : {}),\n                  }\n                : entry,\n            )\n          : [...thread.messages, message];\n        const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES);\n\n        return {\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            messages: cappedMessages,\n            updatedAt: event.occurredAt,\n          }),\n        };\n      });\n\n    case \"thread.session-set\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          ThreadSessionSetPayload,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n        if (!thread) {\n          return nextBase;\n        }\n\n        const session: OrchestrationSession = yield* decodeForEvent(\n          OrchestrationSession,\n          payload.session,\n          event.type,\n          \"session\",\n        );\n\n        // Leaving the \"running\" session status is the turn-end signal: settle\n        // a still-running latest turn so its duration reflects the whole turn.\n        const settledTurnState = settledTurnStateForSessionStatus(session.status);\n        return {\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            session,\n            latestTurn:\n              session.status === \"running\" && session.activeTurnId !== null\n                ? {\n                    turnId: session.activeTurnId,\n                    state: \"running\",\n                    requestedAt:\n                      thread.latestTurn?.turnId === session.activeTurnId\n                        ? thread.latestTurn.requestedAt\n                        : session.updatedAt,\n                    startedAt:\n                      thread.latestTurn?.turnId === session.activeTurnId\n                        ? (thread.latestTurn.startedAt ?? session.updatedAt)\n                        : session.updatedAt,\n                    completedAt: null,\n                    assistantMessageId:\n                      thread.latestTurn?.turnId === session.activeTurnId\n                        ? thread.latestTurn.assistantMessageId\n                        : null,\n                  }\n                : thread.latestTurn !== null &&\n                    thread.latestTurn.state === \"running\" &&\n                    settledTurnState !== null\n                  ? {\n                      ...thread.latestTurn,\n                      state: settledTurnState,\n                      // A running turn's completedAt can only hold a mid-turn\n                      // placeholder checkpoint timestamp — the session leaving\n                      // \"running\" is the authoritative turn end.\n                      completedAt: session.updatedAt,\n                    }\n                  : thread.latestTurn,\n            updatedAt: event.occurredAt,\n          }),\n        };\n      });\n\n    case \"thread.proposed-plan-upserted\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          ThreadProposedPlanUpsertedPayload,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n        if (!thread) {\n          return nextBase;\n        }\n\n        const proposedPlans = [\n          ...thread.proposedPlans.filter((entry) => entry.id !== payload.proposedPlan.id),\n          payload.proposedPlan,\n        ]\n          .toSorted(\n            (left, right) =>\n              left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),\n          )\n          .slice(-200);\n\n        return {\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            proposedPlans,\n            updatedAt: event.occurredAt,\n          }),\n        };\n      });\n\n    case \"thread.turn-diff-completed\":\n      return Effect.gen(function* () {\n        const payload = yield* decodeForEvent(\n          ThreadTurnDiffCompletedPayload,\n          event.payload,\n          event.type,\n          \"payload\",\n        );\n        const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n        if (!thread) {\n          return nextBase;\n        }\n\n        const checkpoint = yield* decodeForEvent(\n          OrchestrationCheckpointSummary,\n          {\n            turnId: payload.turnId,\n            checkpointTurnCount: payload.checkpointTurnCount,\n            checkpointRef: payload.checkpointRef,\n            status: payload.status,\n            files: payload.files,\n            assistantMessageId: payload.assistantMessageId,\n            completedAt: payload.completedAt,\n          },\n          event.type,\n          \"checkpoint\",\n        );\n\n        // Do not let a placeholder (status \"missing\") overwrite a checkpoint\n        // that has already been captured with a real git ref (status \"ready\").\n        // ProviderRuntimeIngestion may fire multiple turn.diff.updated events\n        // per turn; without this guard later placeholders would clobber the\n        // real capture dispatched by CheckpointReactor.\n        const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId);\n        if (existing && existing.status !== \"missing\" && checkpoint.status === \"missing\") {\n          return nextBase;\n        }\n\n        const checkpoints = [\n          ...thread.checkpoints.filter((entry) => entry.turnId !== checkpoint.turnId),\n          checkpoint,\n        ]\n          .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)\n          .slice(-MAX_THREAD_CHECKPOINTS);\n\n        // Mid-turn diff updates produce placeholder checkpoints; record the\n        // checkpoint, but don't settle a turn its session is still running.\n        const turnStillRunning =\n          thread.session?.status === \"running\" && thread.session.activeTurnId === payload.turnId;\n\n        return {\n          ...nextBase,\n          threads: updateThread(nextBase.threads, payload.threadId, {\n            checkpoints,\n            latestTurn: turnStillRunning\n              ? thread.latestTurn\n              : {\n                  turnId: payload.turnId,\n                  state: checkpointStatusToLatestTurnState(payload.status),\n                  requestedAt:\n                    thread.latestTurn?.turnId === payload.turnId\n                      ? thread.latestTurn.requestedAt\n                      : payload.completedAt,\n                  startedAt:\n                    thread.latestTurn?.turnId === payload.turnId\n                      ? (thread.latestTurn.startedAt ?? payload.completedAt)\n                      : payload.completedAt,\n                  completedAt: payload.completedAt,\n                  assistantMessageId: payload.assistantMessageId,\n                },\n            updatedAt: event.occurredAt,\n          }),\n        };\n      });\n\n    case \"thread.reverted\":\n      return decodeForEvent(ThreadRevertedPayload, event.payload, event.type, \"payload\").pipe(\n        Effect.map((payload) => {\n          const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n          if (!thread) {\n            return nextBase;\n          }\n\n          const checkpoints = thread.checkpoints\n            .filter((entry) => entry.checkpointTurnCount <= payload.turnCount)\n            .toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)\n            .slice(-MAX_THREAD_CHECKPOINTS);\n          const retainedTurnIds = new Set(checkpoints.map((checkpoint) => checkpoint.turnId));\n          const messages = retainThreadMessagesAfterRevert(\n            thread.messages,\n            retainedTurnIds,\n            payload.turnCount,\n          ).slice(-MAX_THREAD_MESSAGES);\n          const proposedPlans = retainThreadProposedPlansAfterRevert(\n            thread.proposedPlans,\n            retainedTurnIds,\n          ).slice(-200);\n          const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);\n\n          const latestCheckpoint = checkpoints.at(-1) ?? null;\n          const latestTurn =\n            latestCheckpoint === null\n              ? null\n              : {\n                  turnId: latestCheckpoint.turnId,\n                  state: checkpointStatusToLatestTurnState(latestCheckpoint.status),\n                  requestedAt: latestCheckpoint.completedAt,\n                  startedAt: latestCheckpoint.completedAt,\n                  completedAt: latestCheckpoint.completedAt,\n                  assistantMessageId: latestCheckpoint.assistantMessageId,\n                };\n\n          return {\n            ...nextBase,\n            threads: updateThread(nextBase.threads, payload.threadId, {\n              checkpoints,\n              messages,\n              proposedPlans,\n              activities,\n              latestTurn,\n              updatedAt: event.occurredAt,\n            }),\n          };\n        }),\n      );\n\n    case \"thread.activity-appended\":\n      return decodeForEvent(\n        ThreadActivityAppendedPayload,\n        event.payload,\n        event.type,\n        \"payload\",\n      ).pipe(\n        Effect.map((payload) => {\n          const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);\n          if (!thread) {\n            return nextBase;\n          }\n\n          const activities = [\n            ...thread.activities.filter((entry) => entry.id !== payload.activity.id),\n            payload.activity,\n          ]\n            .toSorted(compareThreadActivities)\n            .slice(-500);\n\n          return {\n            ...nextBase,\n            threads: updateThread(nextBase.threads, payload.threadId, {\n              activities,\n              updatedAt: event.occurredAt,\n            }),\n          };\n        }),\n      );\n\n    default:\n      return Effect.succeed(nextBase);\n  }\n}\n","import {\n  EventId,\n  type OrchestrationCommand,\n  type OrchestrationEvent,\n  type OrchestrationReadModel,\n} from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport type * as PlatformError from \"effect/PlatformError\";\n\nimport { OrchestrationCommandInvariantError } from \"./Errors.ts\";\nimport {\n  listThreadsByProjectId,\n  requireActiveProjectWorkspaceRootAbsent,\n  requireProject,\n  requireProjectAbsent,\n  requireThread,\n  requireThreadArchived,\n  requireThreadAbsent,\n  requireThreadNotArchived,\n} from \"./commandInvariants.ts\";\nimport { projectEvent } from \"./projector.ts\";\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\n// Session adoption takes seconds; a user message still unadopted after this\n// window is a failed/stale start, not pending work. Mirrors the client's\n// QUEUED_TURN_START_GRACE_MS in client-runtime threadSettled.ts.\nconst QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;\n\n/**\n * Blocked-on-you work derived from the thread's retained activities: an\n * approval or user-input request with no later resolution for the same\n * requestId. The server-side twin of the shell's hasPendingApprovals /\n * hasPendingUserInput flags, which the decider read model does not carry.\n * The clearing rules MUST match ProjectionPipeline's pending accounting —\n * resolved activities always clear, respond.failed clears only when the\n * failure detail marks the request stale/unknown — or settle would be\n * rejected on threads whose shell flags read as clear.\n */\nfunction isStaleRequestFailureDetail(payload: Record<string, unknown> | null): boolean {\n  const detail = typeof payload?.detail === \"string\" ? payload.detail.toLowerCase() : null;\n  if (detail === null) return false;\n  return (\n    detail.includes(\"stale pending approval request\") ||\n    detail.includes(\"unknown pending approval request\") ||\n    detail.includes(\"unknown pending permission request\") ||\n    detail.includes(\"stale pending user-input request\") ||\n    detail.includes(\"unknown pending user-input request\") ||\n    detail.includes(\"unknown pending user input request\") ||\n    detail.includes(\"unknown pending codex user input request\")\n  );\n}\n\n// Scans the read model's activities, which the projector caps at the most\n// recent 500. That bound is safe here: an OPEN approval/user-input request\n// blocks its turn, so the thread cannot accumulate hundreds of later\n// activities while one is outstanding — a request that has scrolled out of\n// the window is one whose turn kept running, i.e. it was resolved or went\n// stale. (The projection pipeline's pendingApprovalCount reads the same\n// capped stream and stays consistent with this view.)\nfunction hasOpenBlockingRequest(thread: {\n  readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;\n}): boolean {\n  const openRequestIds = new Set<string>();\n  for (const activity of thread.activities) {\n    const payload =\n      typeof activity.payload === \"object\" && activity.payload !== null\n        ? (activity.payload as Record<string, unknown>)\n        : null;\n    const requestId = typeof payload?.requestId === \"string\" ? payload.requestId : null;\n    if (requestId === null) continue;\n    if (activity.kind === \"approval.requested\" || activity.kind === \"user-input.requested\") {\n      openRequestIds.add(requestId);\n    } else if (activity.kind === \"approval.resolved\" || activity.kind === \"user-input.resolved\") {\n      openRequestIds.delete(requestId);\n    } else if (\n      (activity.kind === \"provider.approval.respond.failed\" ||\n        activity.kind === \"provider.user-input.respond.failed\") &&\n      isStaleRequestFailureDetail(payload)\n    ) {\n      openRequestIds.delete(requestId);\n    }\n  }\n  return openRequestIds.size > 0;\n}\n\n/**\n * A queued turn start — a user message no turn has picked up yet — is work\n * in flight even though session is still null (turn.start emits\n * message-sent + turn-start-requested; the session arrives later). Detection\n * mirrors the client's hasQueuedTurnStart: the newest user message is\n * strictly newer than every latestTurn timestamp (adoption stamps the new\n * turn's requestedAt with the message time, clearing this), and only within\n * the adoption grace window — historical threads whose last user message\n * postdates their turn timestamps (older-server data, mid-turn messages)\n * must not be blocked forever. A failed session start (status \"error\")\n * clears the block immediately.\n *\n * The age check is bounded on BOTH sides: message timestamps are\n * client-supplied, so a client clock ahead of the server yields a negative\n * age. Without the lower bound that negative age satisfies `<= grace` for\n * as long as the skew lasts, extending the block far past the intended two\n * minutes.\n */\nfunction threadHasQueuedTurnStart(\n  thread: {\n    readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;\n    readonly latestTurn: {\n      readonly requestedAt: string;\n      readonly startedAt: string | null;\n      readonly completedAt: string | null;\n    } | null;\n    readonly session: { readonly status: string } | null;\n  },\n  occurredAt: string,\n): boolean {\n  const latestUserMessageAtMs = thread.messages.reduce(\n    (latest, message) =>\n      message.role === \"user\" ? Math.max(latest, Date.parse(message.createdAt)) : latest,\n    Number.NEGATIVE_INFINITY,\n  );\n  const latestTurnAtMs =\n    thread.latestTurn === null\n      ? Number.NEGATIVE_INFINITY\n      : Math.max(\n          ...[\n            thread.latestTurn.requestedAt,\n            thread.latestTurn.startedAt,\n            thread.latestTurn.completedAt,\n          ].map((candidate) =>\n            candidate == null ? Number.NEGATIVE_INFINITY : Date.parse(candidate),\n          ),\n        );\n  const queuedAgeMs = Date.parse(occurredAt) - latestUserMessageAtMs;\n  return (\n    thread.session?.status !== \"error\" &&\n    Number.isFinite(latestUserMessageAtMs) &&\n    latestUserMessageAtMs > latestTurnAtMs &&\n    Math.abs(queuedAgeMs) <= QUEUED_TURN_START_GRACE_MS\n  );\n}\n\nfunction withEventBase(\n  input: Pick<OrchestrationCommand, \"commandId\"> & {\n    readonly aggregateKind: OrchestrationEvent[\"aggregateKind\"];\n    readonly aggregateId: OrchestrationEvent[\"aggregateId\"];\n    readonly occurredAt: string;\n    readonly metadata?: OrchestrationEvent[\"metadata\"];\n  },\n): Effect.Effect<\n  Omit<OrchestrationEvent, \"sequence\" | \"type\" | \"payload\">,\n  PlatformError.PlatformError,\n  Crypto.Crypto\n> {\n  return Crypto.Crypto.pipe(\n    Effect.flatMap((crypto) =>\n      crypto.randomUUIDv4.pipe(\n        Effect.map((eventId) => ({\n          eventId: EventId.make(eventId),\n          aggregateKind: input.aggregateKind,\n          aggregateId: input.aggregateId,\n          occurredAt: input.occurredAt,\n          commandId: input.commandId,\n          causationEventId: null,\n          correlationId: input.commandId,\n          metadata: input.metadata ?? {},\n        })),\n      ),\n    ),\n  );\n}\n\ntype PlannedOrchestrationEvent = Omit<OrchestrationEvent, \"sequence\">;\n\ntype DecideOrchestrationCommandResult =\n  | PlannedOrchestrationEvent\n  | ReadonlyArray<PlannedOrchestrationEvent>;\n\nconst decideCommandSequence = Effect.fn(\"decideCommandSequence\")(function* ({\n  commands,\n  readModel,\n}: {\n  readonly commands: ReadonlyArray<OrchestrationCommand>;\n  readonly readModel: OrchestrationReadModel;\n}): Effect.fn.Return<\n  ReadonlyArray<PlannedOrchestrationEvent>,\n  OrchestrationCommandInvariantError | PlatformError.PlatformError,\n  Crypto.Crypto\n> {\n  let nextReadModel = readModel;\n  let nextSequence = readModel.snapshotSequence;\n  const plannedEvents: PlannedOrchestrationEvent[] = [];\n\n  for (const nextCommand of commands) {\n    const decided = yield* decideOrchestrationCommand({\n      command: nextCommand,\n      readModel: nextReadModel,\n    });\n    const nextEvents = Array.isArray(decided) ? decided : [decided];\n    for (const nextEvent of nextEvents) {\n      plannedEvents.push(nextEvent);\n      nextSequence += 1;\n      nextReadModel = yield* projectEvent(nextReadModel, {\n        ...nextEvent,\n        sequence: nextSequence,\n      }).pipe(Effect.orDie);\n    }\n  }\n\n  return plannedEvents;\n});\n\nexport const decideOrchestrationCommand = Effect.fn(\"decideOrchestrationCommand\")(function* ({\n  command,\n  readModel,\n}: {\n  readonly command: OrchestrationCommand;\n  readonly readModel: OrchestrationReadModel;\n}): Effect.fn.Return<\n  DecideOrchestrationCommandResult,\n  OrchestrationCommandInvariantError | PlatformError.PlatformError,\n  Crypto.Crypto\n> {\n  switch (command.type) {\n    case \"project.create\": {\n      yield* requireProjectAbsent({\n        readModel,\n        command,\n        projectId: command.projectId,\n      });\n      yield* requireActiveProjectWorkspaceRootAbsent({\n        readModel,\n        command,\n        workspaceRoot: command.workspaceRoot,\n        exceptProjectId: command.projectId,\n      });\n\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"project\",\n          aggregateId: command.projectId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"project.created\",\n        payload: {\n          projectId: command.projectId,\n          title: command.title,\n          workspaceRoot: command.workspaceRoot,\n          defaultModelSelection: command.defaultModelSelection ?? null,\n          scripts: [],\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"project.meta.update\": {\n      yield* requireProject({\n        readModel,\n        command,\n        projectId: command.projectId,\n      });\n      if (command.workspaceRoot !== undefined) {\n        yield* requireActiveProjectWorkspaceRootAbsent({\n          readModel,\n          command,\n          workspaceRoot: command.workspaceRoot,\n          exceptProjectId: command.projectId,\n        });\n      }\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"project\",\n          aggregateId: command.projectId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"project.meta-updated\",\n        payload: {\n          projectId: command.projectId,\n          ...(command.title !== undefined ? { title: command.title } : {}),\n          ...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),\n          ...(command.defaultModelSelection !== undefined\n            ? { defaultModelSelection: command.defaultModelSelection }\n            : {}),\n          ...(command.scripts !== undefined ? { scripts: command.scripts } : {}),\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"project.delete\": {\n      yield* requireProject({\n        readModel,\n        command,\n        projectId: command.projectId,\n      });\n      const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(\n        (thread) => thread.deletedAt === null,\n      );\n      if (activeThreads.length > 0 && command.force !== true) {\n        return yield* new OrchestrationCommandInvariantError({\n          commandType: command.type,\n          detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,\n        });\n      }\n      if (activeThreads.length > 0) {\n        return yield* decideCommandSequence({\n          readModel,\n          commands: [\n            ...activeThreads.map(\n              (thread): Extract<OrchestrationCommand, { type: \"thread.delete\" }> => ({\n                type: \"thread.delete\",\n                commandId: command.commandId,\n                threadId: thread.id,\n              }),\n            ),\n            {\n              type: \"project.delete\",\n              commandId: command.commandId,\n              projectId: command.projectId,\n            },\n          ],\n        });\n      }\n\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"project\",\n          aggregateId: command.projectId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"project.deleted\" as const,\n        payload: {\n          projectId: command.projectId,\n          deletedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.create\": {\n      yield* requireProject({\n        readModel,\n        command,\n        projectId: command.projectId,\n      });\n      yield* requireThreadAbsent({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.created\",\n        payload: {\n          threadId: command.threadId,\n          projectId: command.projectId,\n          title: command.title,\n          modelSelection: command.modelSelection,\n          runtimeMode: command.runtimeMode,\n          interactionMode: command.interactionMode,\n          branch: command.branch,\n          worktreePath: command.worktreePath,\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.delete\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.deleted\",\n        payload: {\n          threadId: command.threadId,\n          deletedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.archive\": {\n      yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.archived\",\n        payload: {\n          threadId: command.threadId,\n          archivedAt: occurredAt,\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.unarchive\": {\n      yield* requireThreadArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unarchived\",\n        payload: {\n          threadId: command.threadId,\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.settle\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      // Server-side twin of the client's canSettle session check: a stale\n      // or raced client must not settle a thread whose session is coming\n      // alive or working.\n      if (thread.session?.status === \"starting\" || thread.session?.status === \"running\") {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has an active session and cannot be settled`,\n          }),\n        );\n      }\n      // Pending approval / user-input requests are blocked-on-you work: a\n      // raced or stale client must not park them behind a settled override\n      // that would surface only after the request resolves.\n      if (hasOpenBlockingRequest(thread)) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be settled`,\n          }),\n        );\n      }\n      const occurredAt = yield* nowIso;\n      // Settling inside the adoption window would hide just-requested work.\n      if (threadHasQueuedTurnStart(thread, occurredAt)) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has a queued turn start and cannot be settled`,\n          }),\n        );\n      }\n      // Settling an already-settled thread re-emits with the original\n      // settledAt: the engine rejects zero-event commands, and bulk-settle /\n      // double-click must stay silent no-ops rather than surface errors.\n      const alreadySettled = thread.settledOverride === \"settled\" && thread.settledAt !== null;\n      const settledEvent = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.settled\" as const,\n        payload: {\n          threadId: command.threadId,\n          settledAt: alreadySettled ? thread.settledAt : occurredAt,\n          // A re-emission is a projected no-op: keep the existing updatedAt\n          // so duplicate settles neither rewind nor churn ordering. A fresh\n          // settle stamps the command time.\n          updatedAt: alreadySettled ? thread.updatedAt : occurredAt,\n        },\n      };\n      // Settling is \"I'm done with this\": it clears a pin the same way it\n      // parks the thread. Without this, settling a pinned thread would only\n      // stamp invisible state — the pin would hold the card in place until\n      // a separate unpin.\n      if (thread.pinnedAt == null) {\n        return settledEvent;\n      }\n      return [\n        settledEvent,\n        {\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unpinned\" as const,\n          payload: {\n            threadId: command.threadId,\n            updatedAt: occurredAt,\n          },\n        },\n      ];\n    }\n\n    case \"thread.unsettle\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      // Idempotent by re-emission (see thread.settle): reducing the event a\n      // second time lands on the same override state. A re-emission keeps\n      // the existing updatedAt so duplicates do not churn ordering.\n      const alreadyPinnedActive = thread.settledOverride === \"active\";\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unsettled\",\n        payload: {\n          threadId: command.threadId,\n          reason: command.reason,\n          updatedAt: alreadyPinnedActive ? thread.updatedAt : occurredAt,\n        },\n      };\n    }\n\n    case \"thread.snooze\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      // A wake time in the past would create a thread that is snoozed and\n      // woken at once — the row would never leave the inbox but still carry\n      // snooze state. Reject instead of silently normalizing. The negated\n      // comparison also catches unparseable wake times (IsoDateTime is\n      // structurally just a string): NaN fails every comparison, and an\n      // unparseable snoozedUntil must never persist.\n      if (!(Date.parse(command.snoozedUntil) > Date.parse(occurredAt))) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future`,\n          }),\n        );\n      }\n      // Blocked-on-you work must not be snoozed away: a pending approval or\n      // user-input request is the agent waiting on the user, and hiding it\n      // defeats the request. (A running session IS snoozable — snooze only\n      // affects visibility, never the agent.)\n      if (hasOpenBlockingRequest(thread)) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed`,\n          }),\n        );\n      }\n      // A queued turn start — a user message no turn has adopted yet — is\n      // invisible pending work: no session, no pending flags. Snoozing in\n      // that window would hide a just-requested turn exactly the way settle\n      // would.\n      if (threadHasQueuedTurnStart(thread, occurredAt)) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} has a queued turn start and cannot be snoozed`,\n          }),\n        );\n      }\n      // Re-snoozing an already-snoozed thread to the SAME wake time is a\n      // duplicate (double-click, raced clients): re-emit with the original\n      // timestamps so the projection is a no-op. A different wake time is a\n      // real change and stamps fresh.\n      const existingSnoozedAt =\n        thread.snoozedUntil === command.snoozedUntil && thread.snoozedAt != null\n          ? thread.snoozedAt\n          : null;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.snoozed\",\n        payload: {\n          threadId: command.threadId,\n          snoozedUntil: command.snoozedUntil,\n          snoozedAt: existingSnoozedAt ?? occurredAt,\n          updatedAt: existingSnoozedAt !== null ? thread.updatedAt : occurredAt,\n        },\n      };\n    }\n\n    case \"thread.unsnooze\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      // Idempotent by re-emission (see thread.settle): waking a thread that\n      // is not snoozed lands on the same null state without churning\n      // updatedAt.\n      const alreadyAwake = thread.snoozedUntil == null;\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unsnoozed\",\n        payload: {\n          threadId: command.threadId,\n          reason: command.reason,\n          updatedAt: alreadyAwake ? thread.updatedAt : occurredAt,\n        },\n      };\n    }\n\n    case \"thread.pin\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      // Re-pinning an already-pinned thread is a duplicate (double-click,\n      // raced clients): re-emit with the original timestamps so the\n      // projection is a no-op. Pinning has no lifecycle invariants — a pin\n      // only ever promotes visibility, so it can never hide pending work.\n      const existingPinnedAt = thread.pinnedAt ?? null;\n      const pinnedEvent = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.pinned\" as const,\n        payload: {\n          threadId: command.threadId,\n          pinnedAt: existingPinnedAt ?? occurredAt,\n          // A fresh pin takes the client's slot in the arranged order; on a\n          // re-pin the existing key wins so raced duplicates cannot move a\n          // thread the user already placed.\n          ...(existingPinnedAt === null && command.orderKey !== undefined\n            ? { pinOrderKey: command.orderKey }\n            : {}),\n          updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,\n        },\n      };\n      // Pinning is a promotion: it clears the parked states rather than\n      // silently outranking them. An explicit settle un-settles (reason\n      // \"user\", same override the un-settle button stamps), and a snooze's\n      // return ticket is spent — the thread is on top NOW, not on Tuesday.\n      const promotionEvents: Array<Omit<OrchestrationEvent, \"sequence\">> = [];\n      if (thread.settledOverride === \"settled\") {\n        promotionEvents.push({\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unsettled\",\n          payload: {\n            threadId: command.threadId,\n            reason: \"user\",\n            updatedAt: occurredAt,\n          },\n        });\n      }\n      if (thread.snoozedUntil != null) {\n        promotionEvents.push({\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unsnoozed\",\n          payload: {\n            threadId: command.threadId,\n            reason: \"user\",\n            updatedAt: occurredAt,\n          },\n        });\n      }\n      return promotionEvents.length > 0 ? [pinnedEvent, ...promotionEvents] : pinnedEvent;\n    }\n\n    case \"thread.unpin\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      // Idempotent by re-emission (see thread.settle): unpinning a thread\n      // that is not pinned lands on the same null state without churning\n      // updatedAt.\n      const alreadyUnpinned = thread.pinnedAt == null;\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unpinned\",\n        payload: {\n          threadId: command.threadId,\n          updatedAt: alreadyUnpinned ? thread.updatedAt : occurredAt,\n        },\n      };\n    }\n\n    case \"thread.pin.reorder\": {\n      const thread = yield* requireThreadNotArchived({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      // Only pinned threads have a slot in the arranged order. Rejecting\n      // (rather than silently pinning) keeps a raced reorder-after-unpin\n      // from resurrecting a pin the user just cleared.\n      if (thread.pinnedAt == null) {\n        return yield* Effect.fail(\n          new OrchestrationCommandInvariantError({\n            commandType: command.type,\n            detail: `thread ${command.threadId} is not pinned and cannot be reordered`,\n          }),\n        );\n      }\n      // Idempotent by re-emission (see thread.settle): a duplicate drop on\n      // the same slot keeps the existing updatedAt so it projects as a no-op.\n      const keyUnchanged = thread.pinOrderKey === command.orderKey;\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.pin-reordered\",\n        payload: {\n          threadId: command.threadId,\n          orderKey: command.orderKey,\n          updatedAt: keyUnchanged ? thread.updatedAt : occurredAt,\n        },\n      };\n    }\n\n    case \"thread.meta.update\": {\n      const thread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const branch =\n        command.branch !== undefined &&\n        command.expectedBranch !== undefined &&\n        thread.branch !== command.expectedBranch\n          ? thread.branch\n          : command.branch;\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.meta-updated\",\n        payload: {\n          threadId: command.threadId,\n          ...(command.title !== undefined ? { title: command.title } : {}),\n          ...(command.regenerateTitle === true\n            ? {\n                regenerateTitle: true as const,\n                previousTitle: thread.title,\n                titleRegeneration: {\n                  requestId: command.commandId,\n                  startedAt: occurredAt,\n                },\n              }\n            : {}),\n          ...(command.title !== undefined && thread.titleRegeneration != null\n            ? { titleRegeneration: null }\n            : {}),\n          ...(command.modelSelection !== undefined\n            ? { modelSelection: command.modelSelection }\n            : {}),\n          ...(branch !== undefined ? { branch } : {}),\n          ...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.title.regeneration.complete\": {\n      const thread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const requestIsCurrent = thread.titleRegeneration?.requestId === command.requestId;\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.meta-updated\",\n        payload: {\n          threadId: command.threadId,\n          ...(requestIsCurrent && command.title !== undefined ? { title: command.title } : {}),\n          ...(requestIsCurrent ? { titleRegeneration: null } : {}),\n          updatedAt: requestIsCurrent ? occurredAt : thread.updatedAt,\n        },\n      };\n    }\n\n    case \"thread.runtime-mode.set\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.runtime-mode-set\",\n        payload: {\n          threadId: command.threadId,\n          runtimeMode: command.runtimeMode,\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.interaction-mode.set\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const occurredAt = yield* nowIso;\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.interaction-mode-set\",\n        payload: {\n          threadId: command.threadId,\n          interactionMode: command.interactionMode,\n          updatedAt: occurredAt,\n        },\n      };\n    }\n\n    case \"thread.turn.start\": {\n      const targetThread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const sourceProposedPlan = command.sourceProposedPlan;\n      const sourceThread = sourceProposedPlan\n        ? yield* requireThread({\n            readModel,\n            command,\n            threadId: sourceProposedPlan.threadId,\n          })\n        : null;\n      const sourcePlan =\n        sourceProposedPlan && sourceThread\n          ? sourceThread.proposedPlans.find((entry) => entry.id === sourceProposedPlan.planId)\n          : null;\n      if (sourceProposedPlan && !sourcePlan) {\n        return yield* new OrchestrationCommandInvariantError({\n          commandType: command.type,\n          detail: `Proposed plan '${sourceProposedPlan.planId}' does not exist on thread '${sourceProposedPlan.threadId}'.`,\n        });\n      }\n      if (sourceThread && sourceThread.projectId !== targetThread.projectId) {\n        return yield* new OrchestrationCommandInvariantError({\n          commandType: command.type,\n          detail: `Proposed plan '${sourceProposedPlan?.planId}' belongs to thread '${sourceThread.id}' in a different project.`,\n        });\n      }\n      const userMessageEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.message-sent\",\n        payload: {\n          threadId: command.threadId,\n          messageId: command.message.messageId,\n          role: \"user\",\n          text: command.message.text,\n          attachments: command.message.attachments,\n          turnId: null,\n          streaming: false,\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n      const turnStartRequestedEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        causationEventId: userMessageEvent.eventId,\n        type: \"thread.turn-start-requested\",\n        payload: {\n          threadId: command.threadId,\n          messageId: command.message.messageId,\n          ...(command.modelSelection !== undefined\n            ? { modelSelection: command.modelSelection }\n            : {}),\n          ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}),\n          runtimeMode: targetThread.runtimeMode,\n          interactionMode: targetThread.interactionMode,\n          ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),\n          createdAt: command.createdAt,\n        },\n      };\n      // Real activity resets ANY override: it wakes an explicitly settled\n      // thread, and it clears a keep-active pin back to neutral so the\n      // thread can auto-settle again after this burst of work goes stale.\n      // A snooze clears the same way — sending a message to a snoozed\n      // thread is the user re-engaging, so the return ticket is spent.\n      const lifecycleResetEvents: Array<Omit<OrchestrationEvent, \"sequence\">> = [];\n      if (targetThread.settledOverride !== null) {\n        lifecycleResetEvents.push({\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt: command.createdAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unsettled\",\n          payload: {\n            threadId: command.threadId,\n            reason: \"activity\",\n            updatedAt: command.createdAt,\n          },\n        });\n      }\n      if (targetThread.snoozedUntil != null) {\n        lifecycleResetEvents.push({\n          ...(yield* withEventBase({\n            aggregateKind: \"thread\",\n            aggregateId: command.threadId,\n            occurredAt: command.createdAt,\n            commandId: command.commandId,\n          })),\n          type: \"thread.unsnoozed\",\n          payload: {\n            threadId: command.threadId,\n            reason: \"activity\",\n            updatedAt: command.createdAt,\n          },\n        });\n      }\n      return [...lifecycleResetEvents, userMessageEvent, turnStartRequestedEvent];\n    }\n\n    case \"thread.turn.interrupt\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.turn-interrupt-requested\",\n        payload: {\n          threadId: command.threadId,\n          ...(command.turnId !== undefined ? { turnId: command.turnId } : {}),\n          createdAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.approval.respond\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n          metadata: {\n            requestId: command.requestId,\n          },\n        })),\n        type: \"thread.approval-response-requested\",\n        payload: {\n          threadId: command.threadId,\n          requestId: command.requestId,\n          decision: command.decision,\n          createdAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.user-input.respond\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n          metadata: {\n            requestId: command.requestId,\n          },\n        })),\n        type: \"thread.user-input-response-requested\",\n        payload: {\n          threadId: command.threadId,\n          requestId: command.requestId,\n          answers: command.answers,\n          createdAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.checkpoint.revert\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.checkpoint-revert-requested\",\n        payload: {\n          threadId: command.threadId,\n          turnCount: command.turnCount,\n          createdAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.session.stop\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.session-stop-requested\",\n        payload: {\n          threadId: command.threadId,\n          createdAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.session.set\": {\n      const thread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const sessionSetEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n          metadata: {},\n        })),\n        type: \"thread.session-set\",\n        payload: {\n          threadId: command.threadId,\n          session: command.session,\n        },\n      };\n      // Only a session coming alive is activity worth waking a settled thread\n      // for — status writes like ready/stopped/error arrive after the fact and\n      // must not fight a user's explicit settle. Snooze is deliberately NOT\n      // cleared here: snooze never pauses the agent, so its session starting\n      // or erroring is not the user re-engaging. Blocked/failed work still\n      // surfaces immediately — effectiveSnoozed refuses to classify a thread\n      // with a raised hand (approval / input / failure / fresh completion)\n      // as snoozed, without spending the return ticket.\n      const isSessionActivity =\n        command.session.status === \"starting\" || command.session.status === \"running\";\n      // Real activity resets ANY override (settled wakes, active unpins).\n      if (thread.settledOverride === null || !isSessionActivity) {\n        return sessionSetEvent;\n      }\n      const unsettledEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unsettled\",\n        payload: {\n          threadId: command.threadId,\n          reason: \"activity\",\n          updatedAt: command.createdAt,\n        },\n      };\n      return [unsettledEvent, sessionSetEvent];\n    }\n\n    case \"thread.message.assistant.delta\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.message-sent\",\n        payload: {\n          threadId: command.threadId,\n          messageId: command.messageId,\n          role: \"assistant\",\n          text: command.delta,\n          turnId: command.turnId ?? null,\n          streaming: true,\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.message.assistant.complete\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.message-sent\",\n        payload: {\n          threadId: command.threadId,\n          messageId: command.messageId,\n          role: \"assistant\",\n          text: \"\",\n          turnId: command.turnId ?? null,\n          streaming: false,\n          createdAt: command.createdAt,\n          updatedAt: command.createdAt,\n        },\n      };\n    }\n\n    case \"thread.proposed-plan.upsert\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.proposed-plan-upserted\",\n        payload: {\n          threadId: command.threadId,\n          proposedPlan: command.proposedPlan,\n        },\n      };\n    }\n\n    case \"thread.turn.diff.complete\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.turn-diff-completed\",\n        payload: {\n          threadId: command.threadId,\n          turnId: command.turnId,\n          checkpointTurnCount: command.checkpointTurnCount,\n          checkpointRef: command.checkpointRef,\n          status: command.status,\n          files: command.files,\n          assistantMessageId: command.assistantMessageId ?? null,\n          completedAt: command.completedAt,\n        },\n      };\n    }\n\n    case \"thread.revert.complete\": {\n      yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      return {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.reverted\",\n        payload: {\n          threadId: command.threadId,\n          turnCount: command.turnCount,\n        },\n      };\n    }\n\n    case \"thread.activity.append\": {\n      const thread = yield* requireThread({\n        readModel,\n        command,\n        threadId: command.threadId,\n      });\n      const requestId =\n        typeof command.activity.payload === \"object\" &&\n        command.activity.payload !== null &&\n        \"requestId\" in command.activity.payload &&\n        typeof (command.activity.payload as { requestId?: unknown }).requestId === \"string\"\n          ? ((command.activity.payload as { requestId: string })\n              .requestId as OrchestrationEvent[\"metadata\"][\"requestId\"])\n          : undefined;\n      const activityAppendedEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n          ...(requestId !== undefined ? { metadata: { requestId } } : {}),\n        })),\n        type: \"thread.activity-appended\",\n        payload: {\n          threadId: command.threadId,\n          activity: command.activity,\n        },\n      };\n      // An approval or user-input request is blocked-on-you work — it must\n      // never stay hidden inside a settled slim row.\n      const wakesSettledThread =\n        command.activity.kind === \"approval.requested\" ||\n        command.activity.kind === \"user-input.requested\";\n      // Real activity resets ANY override (settled wakes, active unpins).\n      if (thread.settledOverride === null || !wakesSettledThread) {\n        return activityAppendedEvent;\n      }\n      const unsettledEvent: Omit<OrchestrationEvent, \"sequence\"> = {\n        ...(yield* withEventBase({\n          aggregateKind: \"thread\",\n          aggregateId: command.threadId,\n          occurredAt: command.createdAt,\n          commandId: command.commandId,\n        })),\n        type: \"thread.unsettled\",\n        payload: {\n          threadId: command.threadId,\n          reason: \"activity\",\n          updatedAt: command.createdAt,\n        },\n      };\n      return [unsettledEvent, activityAppendedEvent];\n    }\n\n    default: {\n      command satisfies never;\n      const fallback = command as never as { type: string };\n      return yield* new OrchestrationCommandInvariantError({\n        commandType: fallback.type,\n        detail: `Unknown command type: ${fallback.type}`,\n      });\n    }\n  }\n});\n","/**\n * OrchestrationProjectionPipeline - Event projection pipeline service interface.\n *\n * Coordinates projection bootstrap/replay and per-event projection updates for\n * orchestration read models.\n *\n * @module OrchestrationProjectionPipeline\n */\nimport type { OrchestrationEvent } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../../persistence/Errors.ts\";\n\n/**\n * OrchestrationProjectionPipelineShape - Service API for projection execution.\n */\nexport interface OrchestrationProjectionPipelineShape {\n  /**\n   * Bootstrap projections by replaying persisted events.\n   *\n   * Resumes each projector from its stored projection-state cursor.\n   */\n  readonly bootstrap: Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Project a single orchestration event into projection repositories.\n   *\n   * Projectors are executed sequentially to preserve deterministic ordering.\n   */\n  readonly projectEvent: (\n    event: OrchestrationEvent,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * OrchestrationProjectionPipeline - Service tag for orchestration projections.\n */\nexport class OrchestrationProjectionPipeline extends Context.Service<\n  OrchestrationProjectionPipeline,\n  OrchestrationProjectionPipelineShape\n>()(\"t3/orchestration/Services/ProjectionPipeline/OrchestrationProjectionPipeline\") {}\n","import type {\n  OrchestrationEvent,\n  OrchestrationReadModel,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport { OrchestrationCommand } from \"@t3tools/contracts\";\nimport * as Cause from \"effect/Cause\";\nimport * as Clock from \"effect/Clock\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as Metric from \"effect/Metric\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nimport {\n  metricAttributes,\n  orchestrationCommandAckDuration,\n  orchestrationCommandsTotal,\n  orchestrationCommandDuration,\n} from \"../../observability/Metrics.ts\";\nimport { toPersistenceSqlError } from \"../../persistence/Errors.ts\";\nimport { OrchestrationEventStore } from \"../../persistence/Services/OrchestrationEventStore.ts\";\nimport { OrchestrationCommandReceiptRepository } from \"../../persistence/Services/OrchestrationCommandReceipts.ts\";\nimport {\n  OrchestrationCommandInvariantError,\n  OrchestrationCommandPreviouslyRejectedError,\n  type OrchestrationDispatchError,\n  type OrchestrationProjectorDecodeError,\n} from \"../Errors.ts\";\nimport { decideOrchestrationCommand } from \"../decider.ts\";\nimport { createEmptyReadModel, projectEvent } from \"../projector.ts\";\nimport { OrchestrationProjectionPipeline } from \"../Services/ProjectionPipeline.ts\";\nimport { ProjectionSnapshotQuery } from \"../Services/ProjectionSnapshotQuery.ts\";\nimport {\n  OrchestrationEngineService,\n  type OrchestrationEngineShape,\n} from \"../Services/OrchestrationEngine.ts\";\nconst isOrchestrationCommandPreviouslyRejectedError = Schema.is(\n  OrchestrationCommandPreviouslyRejectedError,\n);\nconst isOrchestrationCommandInvariantError = Schema.is(OrchestrationCommandInvariantError);\n\ninterface CommandEnvelope {\n  command: OrchestrationCommand;\n  result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;\n  startedAtMs: number;\n}\n\nfunction commandToAggregateRef(command: OrchestrationCommand): {\n  readonly aggregateKind: \"project\" | \"thread\";\n  readonly aggregateId: ProjectId | ThreadId;\n} {\n  switch (command.type) {\n    case \"project.create\":\n    case \"project.meta.update\":\n    case \"project.delete\":\n      return {\n        aggregateKind: \"project\",\n        aggregateId: command.projectId,\n      };\n    default:\n      return {\n        aggregateKind: \"thread\",\n        aggregateId: command.threadId,\n      };\n  }\n}\n\nconst makeOrchestrationEngine = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const eventStore = yield* OrchestrationEventStore;\n  const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;\n  const projectionPipeline = yield* OrchestrationProjectionPipeline;\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n  const crypto = yield* Crypto.Crypto;\n\n  const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n  let commandReadModel = createEmptyReadModel(yield* nowIso);\n\n  const commandQueue = yield* Queue.unbounded<CommandEnvelope>();\n  const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();\n\n  const projectEventsOntoReadModel = (\n    baseReadModel: OrchestrationReadModel,\n    events: ReadonlyArray<OrchestrationEvent>,\n  ): Effect.Effect<OrchestrationReadModel, OrchestrationProjectorDecodeError, never> =>\n    Effect.gen(function* () {\n      let nextReadModel = baseReadModel;\n      for (const event of events) {\n        nextReadModel = yield* projectEvent(nextReadModel, event);\n      }\n      return nextReadModel;\n    });\n\n  const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {\n    const dispatchStartSequence = commandReadModel.snapshotSequence;\n    let processingStartedAtMs = 0;\n    const aggregateRef = commandToAggregateRef(envelope.command);\n    const baseMetricAttributes = {\n      commandType: envelope.command.type,\n      aggregateKind: aggregateRef.aggregateKind,\n    } as const;\n    const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {\n      const persistedEvents = yield* Stream.runCollect(\n        eventStore.readFromSequence(dispatchStartSequence),\n      ).pipe(Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)));\n      if (persistedEvents.length === 0) {\n        return;\n      }\n\n      commandReadModel = yield* projectEventsOntoReadModel(commandReadModel, persistedEvents);\n\n      for (const persistedEvent of persistedEvents) {\n        yield* PubSub.publish(eventPubSub, persistedEvent);\n      }\n    });\n\n    return Effect.exit(\n      Effect.gen(function* () {\n        processingStartedAtMs = yield* Clock.currentTimeMillis;\n        yield* Effect.annotateCurrentSpan({\n          \"orchestration.command_id\": envelope.command.commandId,\n          \"orchestration.command_type\": envelope.command.type,\n          \"orchestration.aggregate_kind\": aggregateRef.aggregateKind,\n          \"orchestration.aggregate_id\": aggregateRef.aggregateId,\n        });\n\n        const existingReceipt = yield* commandReceiptRepository.getByCommandId({\n          commandId: envelope.command.commandId,\n        });\n        if (Option.isSome(existingReceipt)) {\n          if (existingReceipt.value.status === \"accepted\") {\n            return {\n              sequence: existingReceipt.value.resultSequence,\n            };\n          }\n          return yield* new OrchestrationCommandPreviouslyRejectedError({\n            commandId: envelope.command.commandId,\n            detail: existingReceipt.value.error ?? \"Previously rejected.\",\n          });\n        }\n\n        const eventBase = yield* decideOrchestrationCommand({\n          command: envelope.command,\n          readModel: commandReadModel,\n        }).pipe(\n          Effect.provideService(Crypto.Crypto, crypto),\n          Effect.mapError((cause) =>\n            isOrchestrationCommandInvariantError(cause)\n              ? cause\n              : new OrchestrationCommandInvariantError({\n                  commandType: envelope.command.type,\n                  detail: \"Failed to generate an event identifier.\",\n                  cause,\n                }),\n          ),\n        );\n        const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];\n        const committedCommand = yield* sql\n          .withTransaction(\n            Effect.gen(function* () {\n              const committedEvents: OrchestrationEvent[] = [];\n              let nextCommandReadModel = commandReadModel;\n\n              for (const nextEvent of eventBases) {\n                const savedEvent = yield* eventStore.append(nextEvent);\n                nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);\n                yield* projectionPipeline.projectEvent(savedEvent);\n                committedEvents.push(savedEvent);\n              }\n\n              const lastSavedEvent = committedEvents.at(-1) ?? null;\n              if (lastSavedEvent === null) {\n                return yield* new OrchestrationCommandInvariantError({\n                  commandType: envelope.command.type,\n                  detail: \"Command produced no events.\",\n                });\n              }\n\n              yield* commandReceiptRepository.upsert({\n                commandId: envelope.command.commandId,\n                aggregateKind: lastSavedEvent.aggregateKind,\n                aggregateId: lastSavedEvent.aggregateId,\n                acceptedAt: lastSavedEvent.occurredAt,\n                resultSequence: lastSavedEvent.sequence,\n                status: \"accepted\",\n                error: null,\n              });\n\n              return {\n                committedEvents,\n                lastSequence: lastSavedEvent.sequence,\n                nextCommandReadModel,\n              } as const;\n            }),\n          )\n          .pipe(\n            Effect.catchTag(\"SqlError\", (sqlError) =>\n              Effect.fail(\n                toPersistenceSqlError(\"OrchestrationEngine.processEnvelope:transaction\")(sqlError),\n              ),\n            ),\n          );\n\n        commandReadModel = committedCommand.nextCommandReadModel;\n        for (const [index, event] of committedCommand.committedEvents.entries()) {\n          yield* PubSub.publish(eventPubSub, event);\n          if (index === 0) {\n            yield* Metric.update(\n              Metric.withAttributes(\n                orchestrationCommandAckDuration,\n                metricAttributes({\n                  ...baseMetricAttributes,\n                  ackEventType: event.type,\n                }),\n              ),\n              Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - envelope.startedAtMs)),\n            );\n          }\n        }\n        return { sequence: committedCommand.lastSequence };\n      }).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),\n    ).pipe(\n      Effect.flatMap((exit) =>\n        Effect.gen(function* () {\n          const outcome = Exit.isSuccess(exit)\n            ? \"success\"\n            : Cause.hasInterruptsOnly(exit.cause)\n              ? \"interrupt\"\n              : \"failure\";\n          yield* Metric.update(\n            Metric.withAttributes(\n              orchestrationCommandDuration,\n              metricAttributes(baseMetricAttributes),\n            ),\n            Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - processingStartedAtMs)),\n          );\n          yield* Metric.update(\n            Metric.withAttributes(\n              orchestrationCommandsTotal,\n              metricAttributes({\n                ...baseMetricAttributes,\n                outcome,\n              }),\n            ),\n            1,\n          );\n\n          if (Exit.isSuccess(exit)) {\n            yield* Deferred.succeed(envelope.result, exit.value);\n            return;\n          }\n\n          const error = Cause.squash(exit.cause) as OrchestrationDispatchError;\n          if (!isOrchestrationCommandPreviouslyRejectedError(error)) {\n            yield* reconcileReadModelAfterDispatchFailure.pipe(\n              Effect.catch(() =>\n                Effect.logWarning(\n                  \"failed to reconcile orchestration read model after dispatch failure\",\n                ).pipe(\n                  Effect.annotateLogs({\n                    commandId: envelope.command.commandId,\n                    snapshotSequence: commandReadModel.snapshotSequence,\n                  }),\n                ),\n              ),\n            );\n\n            if (isOrchestrationCommandInvariantError(error)) {\n              yield* commandReceiptRepository\n                .upsert({\n                  commandId: envelope.command.commandId,\n                  aggregateKind: aggregateRef.aggregateKind,\n                  aggregateId: aggregateRef.aggregateId,\n                  acceptedAt: yield* nowIso,\n                  resultSequence: commandReadModel.snapshotSequence,\n                  status: \"rejected\",\n                  error: error.message,\n                })\n                .pipe(Effect.catch(() => Effect.void));\n            }\n          }\n\n          yield* Deferred.fail(envelope.result, error);\n        }),\n      ),\n    );\n  };\n\n  yield* projectionPipeline.bootstrap;\n  commandReadModel = yield* projectionSnapshotQuery.getCommandReadModel();\n\n  const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));\n  yield* Effect.forkScoped(worker);\n  yield* Effect.logDebug(\"orchestration engine started\").pipe(\n    Effect.annotateLogs({ sequence: commandReadModel.snapshotSequence }),\n  );\n\n  const readEvents: OrchestrationEngineShape[\"readEvents\"] = (fromSequenceExclusive, limit) =>\n    eventStore.readFromSequence(fromSequenceExclusive, limit);\n\n  const dispatch: OrchestrationEngineShape[\"dispatch\"] = (command) =>\n    Effect.gen(function* () {\n      const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();\n      yield* Queue.offer(commandQueue, {\n        command,\n        result,\n        startedAtMs: yield* Clock.currentTimeMillis,\n      });\n      return yield* Deferred.await(result);\n    });\n\n  return {\n    readEvents,\n    dispatch,\n    // Each access creates a fresh PubSub subscription so that multiple\n    // consumers (wsServer, ProviderRuntimeIngestion, CheckpointReactor, etc.)\n    // each independently receive all domain events.\n    get streamDomainEvents(): OrchestrationEngineShape[\"streamDomainEvents\"] {\n      return Stream.fromPubSub(eventPubSub);\n    },\n    // The command read model's snapshotSequence tracks the latest committed\n    // event sequence (updated on the worker fiber). A plain property read is a\n    // consistent, committed value — reassignment of `commandReadModel` is\n    // atomic on the single-threaded event loop.\n    latestSequence: Effect.sync(() => commandReadModel.snapshotSequence),\n  } satisfies OrchestrationEngineShape;\n});\n\nexport const OrchestrationEngineLive = Layer.effect(\n  OrchestrationEngineService,\n  makeOrchestrationEngine,\n);\n","/**\n * ProjectionPendingApprovalRepository - Repository interface for pending approvals.\n *\n * Owns persistence operations for projected approval requests awaiting user\n * decisions.\n *\n * @module ProjectionPendingApprovalRepository\n */\nimport {\n  ApprovalRequestId,\n  IsoDateTime,\n  ProjectionPendingApprovalDecision,\n  ProjectionPendingApprovalStatus,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionPendingApproval = Schema.Struct({\n  requestId: ApprovalRequestId,\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  status: ProjectionPendingApprovalStatus,\n  decision: ProjectionPendingApprovalDecision,\n  createdAt: IsoDateTime,\n  resolvedAt: Schema.NullOr(IsoDateTime),\n});\nexport type ProjectionPendingApproval = typeof ProjectionPendingApproval.Type;\n\nexport const ListProjectionPendingApprovalsInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionPendingApprovalsInput = typeof ListProjectionPendingApprovalsInput.Type;\n\nexport const GetProjectionPendingApprovalInput = Schema.Struct({\n  requestId: ApprovalRequestId,\n});\nexport type GetProjectionPendingApprovalInput = typeof GetProjectionPendingApprovalInput.Type;\n\nexport const DeleteProjectionPendingApprovalInput = Schema.Struct({\n  requestId: ApprovalRequestId,\n});\nexport type DeleteProjectionPendingApprovalInput = typeof DeleteProjectionPendingApprovalInput.Type;\n\n/**\n * ProjectionPendingApprovalRepositoryShape - Service API for pending approvals.\n */\nexport interface ProjectionPendingApprovalRepositoryShape {\n  /**\n   * Insert or replace a projected pending approval row.\n   *\n   * Upserts by `requestId`.\n   */\n  readonly upsert: (\n    row: ProjectionPendingApproval,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * List pending approvals for a thread.\n   *\n   * Returned in ascending creation order.\n   */\n  readonly listByThreadId: (\n    input: ListProjectionPendingApprovalsInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionPendingApproval>, ProjectionRepositoryError>;\n\n  /**\n   * Read a pending approval row by request id.\n   */\n  readonly getByRequestId: (\n    input: GetProjectionPendingApprovalInput,\n  ) => Effect.Effect<Option.Option<ProjectionPendingApproval>, ProjectionRepositoryError>;\n\n  /**\n   * Delete a pending approval row by request id.\n   */\n  readonly deleteByRequestId: (\n    input: DeleteProjectionPendingApprovalInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionPendingApprovalRepository - Service tag for pending approval persistence.\n */\nexport class ProjectionPendingApprovalRepository extends Context.Service<\n  ProjectionPendingApprovalRepository,\n  ProjectionPendingApprovalRepositoryShape\n>()(\"t3/persistence/Services/ProjectionPendingApprovals/ProjectionPendingApprovalRepository\") {}\n","/**\n * ProjectionProjectRepository - Projection repository interface for projects.\n *\n * Owns persistence operations for project rows in the orchestration projection\n * read model.\n *\n * @module ProjectionProjectRepository\n */\nimport { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionProject = Schema.Struct({\n  projectId: ProjectId,\n  title: Schema.String,\n  workspaceRoot: Schema.String,\n  defaultModelSelection: Schema.NullOr(ModelSelection),\n  scripts: Schema.Array(ProjectScript),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  deletedAt: Schema.NullOr(IsoDateTime),\n});\nexport type ProjectionProject = typeof ProjectionProject.Type;\n\nexport const GetProjectionProjectInput = Schema.Struct({\n  projectId: ProjectId,\n});\nexport type GetProjectionProjectInput = typeof GetProjectionProjectInput.Type;\n\nexport const DeleteProjectionProjectInput = Schema.Struct({\n  projectId: ProjectId,\n});\nexport type DeleteProjectionProjectInput = typeof DeleteProjectionProjectInput.Type;\n\n/**\n * ProjectionProjectRepositoryShape - Service API for projected project records.\n */\nexport interface ProjectionProjectRepositoryShape {\n  /**\n   * Insert or replace a projected project row.\n   *\n   * Upserts by `projectId` and persists scripts through JSON encoding.\n   */\n  readonly upsert: (row: ProjectionProject) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read a projected project row by id.\n   */\n  readonly getById: (\n    input: GetProjectionProjectInput,\n  ) => Effect.Effect<Option.Option<ProjectionProject>, ProjectionRepositoryError>;\n\n  /**\n   * List all projected project rows.\n   *\n   * Returned in deterministic creation order.\n   */\n  readonly listAll: () => Effect.Effect<\n    ReadonlyArray<ProjectionProject>,\n    ProjectionRepositoryError\n  >;\n\n  /**\n   * Soft-delete a projected project row by id.\n   */\n  readonly deleteById: (\n    input: DeleteProjectionProjectInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionProjectRepository - Service tag for project projection persistence.\n */\nexport class ProjectionProjectRepository extends Context.Service<\n  ProjectionProjectRepository,\n  ProjectionProjectRepositoryShape\n>()(\"t3/persistence/Services/ProjectionProjects/ProjectionProjectRepository\") {}\n","/**\n * ProjectionStateRepository - Projection repository interface for projector cursors.\n *\n * Owns persistence operations for projection cursor state used to resume\n * incremental event projection.\n *\n * @module ProjectionStateRepository\n */\nimport { IsoDateTime, NonNegativeInt } from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionState = Schema.Struct({\n  projector: Schema.String,\n  lastAppliedSequence: NonNegativeInt,\n  updatedAt: IsoDateTime,\n});\nexport type ProjectionState = typeof ProjectionState.Type;\n\nexport const GetProjectionStateInput = Schema.Struct({\n  projector: Schema.String,\n});\nexport type GetProjectionStateInput = typeof GetProjectionStateInput.Type;\n\n/**\n * ProjectionStateRepositoryShape - Service API for projector state records.\n */\nexport interface ProjectionStateRepositoryShape {\n  /**\n   * Insert or replace a projection cursor row.\n   *\n   * Upserts by projector name.\n   */\n  readonly upsert: (row: ProjectionState) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read projection cursor state for a projector key.\n   */\n  readonly getByProjector: (\n    input: GetProjectionStateInput,\n  ) => Effect.Effect<Option.Option<ProjectionState>, ProjectionRepositoryError>;\n\n  /**\n   * List all projector cursor rows.\n   */\n  readonly listAll: () => Effect.Effect<ReadonlyArray<ProjectionState>, ProjectionRepositoryError>;\n\n  /**\n   * Read the minimum applied sequence across all projectors.\n   *\n   * Returns `null` when no projector state rows exist.\n   */\n  readonly minLastAppliedSequence: () => Effect.Effect<number | null, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionStateRepository - Service tag for projection cursor persistence.\n */\nexport class ProjectionStateRepository extends Context.Service<\n  ProjectionStateRepository,\n  ProjectionStateRepositoryShape\n>()(\"t3/persistence/Services/ProjectionState/ProjectionStateRepository\") {}\n","/**\n * ProjectionThreadActivityRepository - Projection repository interface for thread activity.\n *\n * Owns persistence operations for activity timeline entries projected from\n * orchestration events.\n *\n * @module ProjectionThreadActivityRepository\n */\nimport {\n  EventId,\n  IsoDateTime,\n  NonNegativeInt,\n  OrchestrationThreadActivityTone,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThreadActivity = Schema.Struct({\n  activityId: EventId,\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  tone: OrchestrationThreadActivityTone,\n  kind: Schema.String,\n  summary: Schema.String,\n  payload: Schema.Unknown,\n  sequence: Schema.optional(NonNegativeInt),\n  createdAt: IsoDateTime,\n});\nexport type ProjectionThreadActivity = typeof ProjectionThreadActivity.Type;\n\nexport const ListProjectionThreadActivitiesInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionThreadActivitiesInput = typeof ListProjectionThreadActivitiesInput.Type;\n\nexport const DeleteProjectionThreadActivitiesInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadActivitiesInput =\n  typeof DeleteProjectionThreadActivitiesInput.Type;\n\n/**\n * ProjectionThreadActivityRepositoryShape - Service API for projected thread activity.\n */\nexport interface ProjectionThreadActivityRepositoryShape {\n  /**\n   * Insert or replace a projected thread activity row.\n   *\n   * Upserts by `activityId` and JSON-encodes payload.\n   */\n  readonly upsert: (\n    row: ProjectionThreadActivity,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * List projected thread activity rows for a thread.\n   *\n   * Returned in ascending runtime sequence order (or creation order when\n   * sequence is unavailable).\n   */\n  readonly listByThreadId: (\n    input: ListProjectionThreadActivitiesInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionThreadActivity>, ProjectionRepositoryError>;\n\n  /**\n   * Delete projected thread activity rows by thread.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteProjectionThreadActivitiesInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionThreadActivityRepository - Service tag for thread activity persistence.\n */\nexport class ProjectionThreadActivityRepository extends Context.Service<\n  ProjectionThreadActivityRepository,\n  ProjectionThreadActivityRepositoryShape\n>()(\"t3/persistence/Services/ProjectionThreadActivities/ProjectionThreadActivityRepository\") {}\n","/**\n * ProjectionThreadMessageRepository - Projection repository interface for messages.\n *\n * Owns persistence operations for projected thread messages rendered in the\n * orchestration read model.\n *\n * @module ProjectionThreadMessageRepository\n */\nimport {\n  ChatAttachment,\n  MessageId,\n  OrchestrationMessageRole,\n  ThreadId,\n  TurnId,\n  IsoDateTime,\n} from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Option from \"effect/Option\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThreadMessage = Schema.Struct({\n  messageId: MessageId,\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  role: OrchestrationMessageRole,\n  text: Schema.String,\n  attachments: Schema.optional(Schema.Array(ChatAttachment)),\n  isStreaming: Schema.Boolean,\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type ProjectionThreadMessage = typeof ProjectionThreadMessage.Type;\n\nexport const ListProjectionThreadMessagesInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type;\n\nexport const GetProjectionThreadMessageInput = Schema.Struct({\n  messageId: MessageId,\n});\nexport type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type;\n\nexport const DeleteProjectionThreadMessagesInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadMessagesInput = typeof DeleteProjectionThreadMessagesInput.Type;\n\n/**\n * ProjectionThreadMessageRepositoryShape - Service API for projected thread messages.\n */\nexport interface ProjectionThreadMessageRepositoryShape {\n  /**\n   * Insert or replace a projected thread message row.\n   *\n   * Upserts by `messageId`.\n   */\n  readonly upsert: (\n    message: ProjectionThreadMessage,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read a projected thread message by id.\n   */\n  readonly getByMessageId: (\n    input: GetProjectionThreadMessageInput,\n  ) => Effect.Effect<Option.Option<ProjectionThreadMessage>, ProjectionRepositoryError>;\n\n  /**\n   * List projected thread messages for a thread.\n   *\n   * Returned in ascending creation order.\n   */\n  readonly listByThreadId: (\n    input: ListProjectionThreadMessagesInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionThreadMessage>, ProjectionRepositoryError>;\n\n  /**\n   * Delete projected thread messages by thread.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteProjectionThreadMessagesInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionThreadMessageRepository - Service tag for message projection persistence.\n */\nexport class ProjectionThreadMessageRepository extends Context.Service<\n  ProjectionThreadMessageRepository,\n  ProjectionThreadMessageRepositoryShape\n>()(\"t3/persistence/Services/ProjectionThreadMessages/ProjectionThreadMessageRepository\") {}\n","import {\n  IsoDateTime,\n  OrchestrationProposedPlanId,\n  ThreadId,\n  TrimmedNonEmptyString,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThreadProposedPlan = Schema.Struct({\n  planId: OrchestrationProposedPlanId,\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  planMarkdown: TrimmedNonEmptyString,\n  implementedAt: Schema.NullOr(IsoDateTime),\n  implementationThreadId: Schema.NullOr(ThreadId),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n});\nexport type ProjectionThreadProposedPlan = typeof ProjectionThreadProposedPlan.Type;\n\nexport const ListProjectionThreadProposedPlansInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionThreadProposedPlansInput =\n  typeof ListProjectionThreadProposedPlansInput.Type;\n\nexport const DeleteProjectionThreadProposedPlansInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadProposedPlansInput =\n  typeof DeleteProjectionThreadProposedPlansInput.Type;\n\nexport interface ProjectionThreadProposedPlanRepositoryShape {\n  readonly upsert: (\n    proposedPlan: ProjectionThreadProposedPlan,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n  readonly listByThreadId: (\n    input: ListProjectionThreadProposedPlansInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionThreadProposedPlan>, ProjectionRepositoryError>;\n  readonly deleteByThreadId: (\n    input: DeleteProjectionThreadProposedPlansInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\nexport class ProjectionThreadProposedPlanRepository extends Context.Service<\n  ProjectionThreadProposedPlanRepository,\n  ProjectionThreadProposedPlanRepositoryShape\n>()(\n  \"t3/persistence/Services/ProjectionThreadProposedPlans/ProjectionThreadProposedPlanRepository\",\n) {}\n","/**\n * ProjectionThreadSessionRepository - Repository interface for thread sessions.\n *\n * Owns persistence operations for projected provider-session linkage and\n * runtime status for each thread.\n *\n * @module ProjectionThreadSessionRepository\n */\nimport {\n  RuntimeMode,\n  IsoDateTime,\n  OrchestrationSessionStatus,\n  ProviderInstanceId,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThreadSession = Schema.Struct({\n  threadId: ThreadId,\n  status: OrchestrationSessionStatus,\n  providerName: Schema.NullOr(Schema.String),\n  providerInstanceId: Schema.NullOr(ProviderInstanceId),\n  runtimeMode: RuntimeMode,\n  activeTurnId: Schema.NullOr(TurnId),\n  lastError: Schema.NullOr(Schema.String),\n  updatedAt: IsoDateTime,\n});\nexport type ProjectionThreadSession = typeof ProjectionThreadSession.Type;\n\nexport const GetProjectionThreadSessionInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type GetProjectionThreadSessionInput = typeof GetProjectionThreadSessionInput.Type;\n\nexport const DeleteProjectionThreadSessionInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadSessionInput = typeof DeleteProjectionThreadSessionInput.Type;\n\n/**\n * ProjectionThreadSessionRepositoryShape - Service API for projected thread sessions.\n */\nexport interface ProjectionThreadSessionRepositoryShape {\n  /**\n   * Insert or replace a projected thread-session row.\n   *\n   * Upserts by `threadId`.\n   */\n  readonly upsert: (row: ProjectionThreadSession) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read projected thread-session state by thread id.\n   */\n  readonly getByThreadId: (\n    input: GetProjectionThreadSessionInput,\n  ) => Effect.Effect<Option.Option<ProjectionThreadSession>, ProjectionRepositoryError>;\n\n  /**\n   * Delete projected thread-session state by thread id.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteProjectionThreadSessionInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionThreadSessionRepository - Service tag for thread-session persistence.\n */\nexport class ProjectionThreadSessionRepository extends Context.Service<\n  ProjectionThreadSessionRepository,\n  ProjectionThreadSessionRepositoryShape\n>()(\"t3/persistence/Services/ProjectionThreadSessions/ProjectionThreadSessionRepository\") {}\n","/**\n * ProjectionTurnRepository - Projection repository interface for unified turn state.\n *\n * Owns persistence operations for pending starts, running/completed turn lifecycle,\n * and checkpoint metadata in a single projection table.\n *\n * @module ProjectionTurnRepository\n */\nimport {\n  CheckpointRef,\n  IsoDateTime,\n  MessageId,\n  NonNegativeInt,\n  OrchestrationProposedPlanId,\n  OrchestrationCheckpointFile,\n  OrchestrationCheckpointStatus,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionTurnState = Schema.Literals([\n  \"pending\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"error\",\n]);\nexport type ProjectionTurnState = typeof ProjectionTurnState.Type;\n\nexport const ProjectionTurn = Schema.Struct({\n  threadId: ThreadId,\n  turnId: Schema.NullOr(TurnId),\n  pendingMessageId: Schema.NullOr(MessageId),\n  sourceProposedPlanThreadId: Schema.NullOr(ThreadId),\n  sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),\n  assistantMessageId: Schema.NullOr(MessageId),\n  state: ProjectionTurnState,\n  requestedAt: IsoDateTime,\n  startedAt: Schema.NullOr(IsoDateTime),\n  completedAt: Schema.NullOr(IsoDateTime),\n  checkpointTurnCount: Schema.NullOr(NonNegativeInt),\n  checkpointRef: Schema.NullOr(CheckpointRef),\n  checkpointStatus: Schema.NullOr(OrchestrationCheckpointStatus),\n  checkpointFiles: Schema.Array(OrchestrationCheckpointFile),\n});\nexport type ProjectionTurn = typeof ProjectionTurn.Type;\n\nexport const ProjectionTurnById = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  pendingMessageId: Schema.NullOr(MessageId),\n  sourceProposedPlanThreadId: Schema.NullOr(ThreadId),\n  sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),\n  assistantMessageId: Schema.NullOr(MessageId),\n  state: ProjectionTurnState,\n  requestedAt: IsoDateTime,\n  startedAt: Schema.NullOr(IsoDateTime),\n  completedAt: Schema.NullOr(IsoDateTime),\n  checkpointTurnCount: Schema.NullOr(NonNegativeInt),\n  checkpointRef: Schema.NullOr(CheckpointRef),\n  checkpointStatus: Schema.NullOr(OrchestrationCheckpointStatus),\n  checkpointFiles: Schema.Array(OrchestrationCheckpointFile),\n});\nexport type ProjectionTurnById = typeof ProjectionTurnById.Type;\n\nexport const ProjectionPendingTurnStart = Schema.Struct({\n  threadId: ThreadId,\n  messageId: MessageId,\n  sourceProposedPlanThreadId: Schema.NullOr(ThreadId),\n  sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),\n  requestedAt: IsoDateTime,\n});\nexport type ProjectionPendingTurnStart = typeof ProjectionPendingTurnStart.Type;\n\nexport const ListProjectionTurnsByThreadInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListProjectionTurnsByThreadInput = typeof ListProjectionTurnsByThreadInput.Type;\n\nexport const GetProjectionTurnByTurnIdInput = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n});\nexport type GetProjectionTurnByTurnIdInput = typeof GetProjectionTurnByTurnIdInput.Type;\n\nexport const GetProjectionPendingTurnStartInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type GetProjectionPendingTurnStartInput = typeof GetProjectionPendingTurnStartInput.Type;\n\nexport const DeleteProjectionTurnsByThreadInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionTurnsByThreadInput = typeof DeleteProjectionTurnsByThreadInput.Type;\n\nexport const ClearCheckpointTurnConflictInput = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n});\nexport type ClearCheckpointTurnConflictInput = typeof ClearCheckpointTurnConflictInput.Type;\n\nexport interface ProjectionTurnRepositoryShape {\n  /**\n   * Inserts or updates the canonical row for a concrete `{threadId, turnId}` turn lifecycle state.\n   */\n  readonly upsertByTurnId: (\n    row: ProjectionTurnById,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Replaces any existing pending-start placeholder rows for a thread with exactly one latest pending-start row.\n   */\n  readonly replacePendingTurnStart: (\n    row: ProjectionPendingTurnStart,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Returns the newest pending-start placeholder for a thread; this is expected to be at most one row after replacement writes.\n   */\n  readonly getPendingTurnStartByThreadId: (\n    input: GetProjectionPendingTurnStartInput,\n  ) => Effect.Effect<Option.Option<ProjectionPendingTurnStart>, ProjectionRepositoryError>;\n\n  /**\n   * Deletes only pending-start placeholder rows (`turnId = null`) for a thread and leaves concrete turn rows untouched.\n   */\n  readonly deletePendingTurnStartByThreadId: (\n    input: GetProjectionPendingTurnStartInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Lists all projection rows for a thread, including pending placeholders, with checkpoint rows ordered before non-checkpoint rows.\n   */\n  readonly listByThreadId: (\n    input: ListProjectionTurnsByThreadInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionTurn>, ProjectionRepositoryError>;\n\n  /**\n   * Looks up a concrete turn row by `{threadId, turnId}` and never returns pending placeholder rows.\n   */\n  readonly getByTurnId: (\n    input: GetProjectionTurnByTurnIdInput,\n  ) => Effect.Effect<Option.Option<ProjectionTurnById>, ProjectionRepositoryError>;\n\n  /**\n   * Clears checkpoint fields on conflicting rows that reuse the same checkpoint turn count in a thread, excluding the provided turn.\n   */\n  readonly clearCheckpointTurnConflict: (\n    input: ClearCheckpointTurnConflictInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Hard-deletes all projection rows for a thread, including pending-start placeholders and checkpoint metadata rows.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteProjectionTurnsByThreadInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\nexport class ProjectionTurnRepository extends Context.Service<\n  ProjectionTurnRepository,\n  ProjectionTurnRepositoryShape\n>()(\"t3/persistence/Services/ProjectionTurns/ProjectionTurnRepository\") {}\n","/**\n * ProjectionThreadRepository - Projection repository interface for threads.\n *\n * Owns persistence operations for projected thread records in the\n * orchestration read model.\n *\n * @module ProjectionThreadRepository\n */\nimport {\n  CommandId,\n  IsoDateTime,\n  ModelSelection,\n  NonNegativeInt,\n  ProjectId,\n  ProviderInteractionMode,\n  RuntimeMode,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionThread = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  title: Schema.String,\n  modelSelection: ModelSelection,\n  runtimeMode: RuntimeMode,\n  interactionMode: ProviderInteractionMode,\n  branch: Schema.NullOr(Schema.String),\n  worktreePath: Schema.NullOr(Schema.String),\n  latestTurnId: Schema.NullOr(TurnId),\n  createdAt: IsoDateTime,\n  updatedAt: IsoDateTime,\n  archivedAt: Schema.NullOr(IsoDateTime),\n  settledOverride: Schema.NullOr(Schema.Literals([\"settled\", \"active\"])),\n  settledAt: Schema.NullOr(IsoDateTime),\n  snoozedUntil: Schema.NullOr(IsoDateTime),\n  snoozedAt: Schema.NullOr(IsoDateTime),\n  pinnedAt: Schema.NullOr(IsoDateTime),\n  pinOrderKey: Schema.optional(Schema.NullOr(Schema.String)),\n  titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),\n  titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),\n  latestUserMessageAt: Schema.NullOr(IsoDateTime),\n  pendingApprovalCount: NonNegativeInt,\n  pendingUserInputCount: NonNegativeInt,\n  hasActionableProposedPlan: NonNegativeInt,\n  deletedAt: Schema.NullOr(IsoDateTime),\n});\nexport type ProjectionThread = typeof ProjectionThread.Type;\n\nexport const GetProjectionThreadInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type GetProjectionThreadInput = typeof GetProjectionThreadInput.Type;\n\nexport const DeleteProjectionThreadInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteProjectionThreadInput = typeof DeleteProjectionThreadInput.Type;\n\nexport const ListProjectionThreadsByProjectInput = Schema.Struct({\n  projectId: ProjectId,\n});\nexport type ListProjectionThreadsByProjectInput = typeof ListProjectionThreadsByProjectInput.Type;\n\n/**\n * ProjectionThreadRepositoryShape - Service API for projected thread records.\n */\nexport interface ProjectionThreadRepositoryShape {\n  /**\n   * Insert or replace a projected thread row.\n   *\n   * Upserts by `threadId`.\n   */\n  readonly upsert: (thread: ProjectionThread) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * Read a projected thread row by id.\n   */\n  readonly getById: (\n    input: GetProjectionThreadInput,\n  ) => Effect.Effect<Option.Option<ProjectionThread>, ProjectionRepositoryError>;\n\n  /**\n   * List projected threads for a project.\n   *\n   * Returned in deterministic creation order.\n   */\n  readonly listByProjectId: (\n    input: ListProjectionThreadsByProjectInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionThread>, ProjectionRepositoryError>;\n\n  /**\n   * Soft-delete a projected thread row by id.\n   */\n  readonly deleteById: (\n    input: DeleteProjectionThreadInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionThreadRepository - Service tag for thread projection persistence.\n */\nexport class ProjectionThreadRepository extends Context.Service<\n  ProjectionThreadRepository,\n  ProjectionThreadRepositoryShape\n>()(\"t3/persistence/Services/ProjectionThreads/ProjectionThreadRepository\") {}\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  GetProjectionPendingApprovalInput,\n  DeleteProjectionPendingApprovalInput,\n  ListProjectionPendingApprovalsInput,\n  ProjectionPendingApproval,\n  ProjectionPendingApprovalRepository,\n  type ProjectionPendingApprovalRepositoryShape,\n} from \"../Services/ProjectionPendingApprovals.ts\";\n\nconst makeProjectionPendingApprovalRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionPendingApprovalRow = SqlSchema.void({\n    Request: ProjectionPendingApproval,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_pending_approvals (\n          request_id,\n          thread_id,\n          turn_id,\n          status,\n          decision,\n          created_at,\n          resolved_at\n        )\n        VALUES (\n          ${row.requestId},\n          ${row.threadId},\n          ${row.turnId},\n          ${row.status},\n          ${row.decision},\n          ${row.createdAt},\n          ${row.resolvedAt}\n        )\n        ON CONFLICT (request_id)\n        DO UPDATE SET\n          thread_id = excluded.thread_id,\n          turn_id = excluded.turn_id,\n          status = excluded.status,\n          decision = excluded.decision,\n          created_at = excluded.created_at,\n          resolved_at = excluded.resolved_at\n      `,\n  });\n\n  const listProjectionPendingApprovalRows = SqlSchema.findAll({\n    Request: ListProjectionPendingApprovalsInput,\n    Result: ProjectionPendingApproval,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          request_id AS \"requestId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          status,\n          decision,\n          created_at AS \"createdAt\",\n          resolved_at AS \"resolvedAt\"\n        FROM projection_pending_approvals\n        WHERE thread_id = ${threadId}\n        ORDER BY created_at ASC, request_id ASC\n      `,\n  });\n\n  const getProjectionPendingApprovalRow = SqlSchema.findOneOption({\n    Request: GetProjectionPendingApprovalInput,\n    Result: ProjectionPendingApproval,\n    execute: ({ requestId }) =>\n      sql`\n        SELECT\n          request_id AS \"requestId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          status,\n          decision,\n          created_at AS \"createdAt\",\n          resolved_at AS \"resolvedAt\"\n        FROM projection_pending_approvals\n        WHERE request_id = ${requestId}\n      `,\n  });\n\n  const deleteProjectionPendingApprovalRow = SqlSchema.void({\n    Request: DeleteProjectionPendingApprovalInput,\n    execute: ({ requestId }) =>\n      sql`\n        DELETE FROM projection_pending_approvals\n        WHERE request_id = ${requestId}\n      `,\n  });\n\n  const upsert: ProjectionPendingApprovalRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionPendingApprovalRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionPendingApprovalRepository.upsert:query\")),\n    );\n\n  const listByThreadId: ProjectionPendingApprovalRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionPendingApprovalRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionPendingApprovalRepository.listByThreadId:query\"),\n      ),\n    );\n\n  const getByRequestId: ProjectionPendingApprovalRepositoryShape[\"getByRequestId\"] = (input) =>\n    getProjectionPendingApprovalRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionPendingApprovalRepository.getByRequestId:query\"),\n      ),\n    );\n\n  const deleteByRequestId: ProjectionPendingApprovalRepositoryShape[\"deleteByRequestId\"] = (\n    input,\n  ) =>\n    deleteProjectionPendingApprovalRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionPendingApprovalRepository.deleteByRequestId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    listByThreadId,\n    getByRequestId,\n    deleteByRequestId,\n  } satisfies ProjectionPendingApprovalRepositoryShape;\n});\n\nexport const ProjectionPendingApprovalRepositoryLive = Layer.effect(\n  ProjectionPendingApprovalRepository,\n  makeProjectionPendingApprovalRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\n\nimport { ModelSelection, ProjectScript } from \"@t3tools/contracts\";\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  DeleteProjectionProjectInput,\n  GetProjectionProjectInput,\n  ProjectionProject,\n  ProjectionProjectRepository,\n  type ProjectionProjectRepositoryShape,\n} from \"../Services/ProjectionProjects.ts\";\n\nconst ProjectionProjectDbRow = ProjectionProject.mapFields(\n  Struct.assign({\n    defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),\n    scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),\n  }),\n);\ntype ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;\n\nconst makeProjectionProjectRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionProjectRow = SqlSchema.void({\n    Request: ProjectionProject,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_projects (\n          project_id,\n          title,\n          workspace_root,\n          default_model_selection_json,\n          scripts_json,\n          created_at,\n          updated_at,\n          deleted_at\n        )\n        VALUES (\n          ${row.projectId},\n          ${row.title},\n          ${row.workspaceRoot},\n          ${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},\n          ${JSON.stringify(row.scripts)},\n          ${row.createdAt},\n          ${row.updatedAt},\n          ${row.deletedAt}\n        )\n        ON CONFLICT (project_id)\n        DO UPDATE SET\n          title = excluded.title,\n          workspace_root = excluded.workspace_root,\n          default_model_selection_json = excluded.default_model_selection_json,\n          scripts_json = excluded.scripts_json,\n          created_at = excluded.created_at,\n          updated_at = excluded.updated_at,\n          deleted_at = excluded.deleted_at\n      `,\n  });\n\n  const getProjectionProjectRow = SqlSchema.findOneOption({\n    Request: GetProjectionProjectInput,\n    Result: ProjectionProjectDbRow,\n    execute: ({ projectId }) =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        WHERE project_id = ${projectId}\n      `,\n  });\n\n  const listProjectionProjectRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionProjectDbRow,\n    execute: () =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        ORDER BY created_at ASC, project_id ASC\n      `,\n  });\n\n  const deleteProjectionProjectRow = SqlSchema.void({\n    Request: DeleteProjectionProjectInput,\n    execute: ({ projectId }) =>\n      sql`\n        DELETE FROM projection_projects\n        WHERE project_id = ${projectId}\n      `,\n  });\n\n  const upsert: ProjectionProjectRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionProjectRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionProjectRepository.upsert:query\")),\n    );\n\n  const getById: ProjectionProjectRepositoryShape[\"getById\"] = (input) =>\n    getProjectionProjectRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionProjectRepository.getById:query\")),\n    );\n\n  const listAll: ProjectionProjectRepositoryShape[\"listAll\"] = () =>\n    listProjectionProjectRows().pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionProjectRepository.listAll:query\")),\n    );\n\n  const deleteById: ProjectionProjectRepositoryShape[\"deleteById\"] = (input) =>\n    deleteProjectionProjectRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionProjectRepository.deleteById:query\")),\n    );\n\n  return {\n    upsert,\n    getById,\n    listAll,\n    deleteById,\n  } satisfies ProjectionProjectRepositoryShape;\n});\n\nexport const ProjectionProjectRepositoryLive = Layer.effect(\n  ProjectionProjectRepository,\n  makeProjectionProjectRepository,\n);\n","import { NonNegativeInt } from \"@t3tools/contracts\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\n\nimport {\n  ProjectionStateRepository,\n  type ProjectionStateRepositoryShape,\n  GetProjectionStateInput,\n  ProjectionState,\n} from \"../Services/ProjectionState.ts\";\n\nconst MinLastAppliedSequenceRowSchema = Schema.Struct({\n  minLastAppliedSequence: Schema.NullOr(NonNegativeInt),\n});\n\nconst makeProjectionStateRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionStateRow = SqlSchema.void({\n    Request: ProjectionState,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_state (\n          projector,\n          last_applied_sequence,\n          updated_at\n        )\n        VALUES (\n          ${row.projector},\n          ${row.lastAppliedSequence},\n          ${row.updatedAt}\n        )\n        ON CONFLICT (projector)\n        DO UPDATE SET\n          last_applied_sequence = excluded.last_applied_sequence,\n          updated_at = excluded.updated_at\n      `,\n  });\n\n  const getProjectionStateRow = SqlSchema.findOneOption({\n    Request: GetProjectionStateInput,\n    Result: ProjectionState,\n    execute: ({ projector }) =>\n      sql`\n        SELECT\n          projector,\n          last_applied_sequence AS \"lastAppliedSequence\",\n          updated_at AS \"updatedAt\"\n        FROM projection_state\n        WHERE projector = ${projector}\n      `,\n  });\n\n  const listProjectionStateRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionState,\n    execute: () =>\n      sql`\n        SELECT\n          projector,\n          last_applied_sequence AS \"lastAppliedSequence\",\n          updated_at AS \"updatedAt\"\n        FROM projection_state\n        ORDER BY projector ASC\n      `,\n  });\n\n  const readMinLastAppliedSequence = SqlSchema.findOne({\n    Request: Schema.Void,\n    Result: MinLastAppliedSequenceRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          MIN(last_applied_sequence) AS \"minLastAppliedSequence\"\n        FROM projection_state\n      `,\n  });\n\n  const upsert: ProjectionStateRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionStateRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionStateRepository.upsert:query\")),\n    );\n\n  const getByProjector: ProjectionStateRepositoryShape[\"getByProjector\"] = (input) =>\n    getProjectionStateRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionStateRepository.getByProjector:query\")),\n    );\n\n  const listAll: ProjectionStateRepositoryShape[\"listAll\"] = () =>\n    listProjectionStateRows(undefined).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionStateRepository.listAll:query\")),\n    );\n\n  const minLastAppliedSequence: ProjectionStateRepositoryShape[\"minLastAppliedSequence\"] = () =>\n    readMinLastAppliedSequence(undefined).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionStateRepository.minLastAppliedSequence:query\"),\n      ),\n      Effect.map((row) => row.minLastAppliedSequence),\n    );\n\n  return {\n    upsert,\n    getByProjector,\n    listAll,\n    minLastAppliedSequence,\n  } satisfies ProjectionStateRepositoryShape;\n});\n\nexport const ProjectionStateRepositoryLive = Layer.effect(\n  ProjectionStateRepository,\n  makeProjectionStateRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport { NonNegativeInt } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\n\nimport { toPersistenceDecodeError, toPersistenceSqlError } from \"../Errors.ts\";\n\nimport {\n  DeleteProjectionThreadActivitiesInput,\n  ListProjectionThreadActivitiesInput,\n  ProjectionThreadActivity,\n  ProjectionThreadActivityRepository,\n  type ProjectionThreadActivityRepositoryShape,\n} from \"../Services/ProjectionThreadActivities.ts\";\n\nconst ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(\n  Struct.assign({\n    payload: Schema.fromJsonString(Schema.Unknown),\n    sequence: Schema.NullOr(NonNegativeInt),\n  }),\n);\n\nfunction toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {\n  return (cause: unknown) =>\n    Schema.isSchemaError(cause)\n      ? toPersistenceDecodeError(decodeOperation)(cause)\n      : toPersistenceSqlError(sqlOperation)(cause);\n}\n\nconst makeProjectionThreadActivityRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadActivityRow = SqlSchema.void({\n    Request: ProjectionThreadActivity,\n    execute: (row) =>\n      sql`\n            INSERT INTO projection_thread_activities (\n              activity_id,\n              thread_id,\n              turn_id,\n              tone,\n              kind,\n              summary,\n              payload_json,\n              sequence,\n              created_at\n            )\n            VALUES (\n              ${row.activityId},\n              ${row.threadId},\n              ${row.turnId},\n              ${row.tone},\n              ${row.kind},\n              ${row.summary},\n              ${JSON.stringify(row.payload)},\n              ${row.sequence ?? null},\n              ${row.createdAt}\n            )\n            ON CONFLICT (activity_id)\n            DO UPDATE SET\n              thread_id = excluded.thread_id,\n              turn_id = excluded.turn_id,\n              tone = excluded.tone,\n              kind = excluded.kind,\n              summary = excluded.summary,\n              payload_json = excluded.payload_json,\n              sequence = excluded.sequence,\n              created_at = excluded.created_at\n          `,\n  });\n\n  const listProjectionThreadActivityRows = SqlSchema.findAll({\n    Request: ListProjectionThreadActivitiesInput,\n    Result: ProjectionThreadActivityDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          activity_id AS \"activityId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          tone,\n          kind,\n          summary,\n          payload_json AS \"payload\",\n          sequence,\n          created_at AS \"createdAt\"\n        FROM projection_thread_activities\n        WHERE thread_id = ${threadId}\n        ORDER BY\n          CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,\n          sequence ASC,\n          created_at ASC,\n          activity_id ASC\n      `,\n  });\n\n  const deleteProjectionThreadActivityRows = SqlSchema.void({\n    Request: DeleteProjectionThreadActivitiesInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_thread_activities\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProjectionThreadActivityRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadActivityRow(row).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionThreadActivityRepository.upsert:query\",\n          \"ProjectionThreadActivityRepository.upsert:encodeRequest\",\n        ),\n      ),\n    );\n\n  const listByThreadId: ProjectionThreadActivityRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionThreadActivityRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionThreadActivityRepository.listByThreadId:query\",\n          \"ProjectionThreadActivityRepository.listByThreadId:decodeRows\",\n        ),\n      ),\n      Effect.map((rows) =>\n        rows.map((row) => ({\n          activityId: row.activityId,\n          threadId: row.threadId,\n          turnId: row.turnId,\n          tone: row.tone,\n          kind: row.kind,\n          summary: row.summary,\n          payload: row.payload,\n          ...(row.sequence !== null ? { sequence: row.sequence } : {}),\n          createdAt: row.createdAt,\n        })),\n      ),\n    );\n\n  const deleteByThreadId: ProjectionThreadActivityRepositoryShape[\"deleteByThreadId\"] = (input) =>\n    deleteProjectionThreadActivityRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadActivityRepository.deleteByThreadId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    listByThreadId,\n    deleteByThreadId,\n  } satisfies ProjectionThreadActivityRepositoryShape;\n});\n\nexport const ProjectionThreadActivityRepositoryLive = Layer.effect(\n  ProjectionThreadActivityRepository,\n  makeProjectionThreadActivityRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\nimport { ChatAttachment } from \"@t3tools/contracts\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  GetProjectionThreadMessageInput,\n  ProjectionThreadMessageRepository,\n  type ProjectionThreadMessageRepositoryShape,\n  DeleteProjectionThreadMessagesInput,\n  ListProjectionThreadMessagesInput,\n  ProjectionThreadMessage,\n} from \"../Services/ProjectionThreadMessages.ts\";\n\nconst ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(\n  Struct.assign({\n    isStreaming: Schema.Number,\n    attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),\n  }),\n);\n\nfunction toProjectionThreadMessage(\n  row: Schema.Schema.Type<typeof ProjectionThreadMessageDbRowSchema>,\n): ProjectionThreadMessage {\n  return {\n    messageId: row.messageId,\n    threadId: row.threadId,\n    turnId: row.turnId,\n    role: row.role,\n    text: row.text,\n    isStreaming: row.isStreaming === 1,\n    createdAt: row.createdAt,\n    updatedAt: row.updatedAt,\n    ...(row.attachments !== null ? { attachments: row.attachments } : {}),\n  };\n}\n\nconst makeProjectionThreadMessageRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadMessageRow = SqlSchema.void({\n    Request: ProjectionThreadMessage,\n    execute: (row) => {\n      const nextAttachmentsJson =\n        row.attachments !== undefined ? JSON.stringify(row.attachments) : null;\n      return sql`\n        INSERT INTO projection_thread_messages (\n          message_id,\n          thread_id,\n          turn_id,\n          role,\n          text,\n          attachments_json,\n          is_streaming,\n          created_at,\n          updated_at\n        )\n        VALUES (\n          ${row.messageId},\n          ${row.threadId},\n          ${row.turnId},\n          ${row.role},\n          ${row.text},\n          COALESCE(\n            ${nextAttachmentsJson},\n            (\n              SELECT attachments_json\n              FROM projection_thread_messages\n              WHERE message_id = ${row.messageId}\n            )\n          ),\n          ${row.isStreaming ? 1 : 0},\n          ${row.createdAt},\n          ${row.updatedAt}\n        )\n        ON CONFLICT (message_id)\n        DO UPDATE SET\n          thread_id = excluded.thread_id,\n          turn_id = excluded.turn_id,\n          role = excluded.role,\n          text = excluded.text,\n          attachments_json = COALESCE(\n            excluded.attachments_json,\n            projection_thread_messages.attachments_json\n          ),\n          is_streaming = excluded.is_streaming,\n          created_at = excluded.created_at,\n          updated_at = excluded.updated_at\n      `;\n    },\n  });\n\n  const getProjectionThreadMessageRow = SqlSchema.findOneOption({\n    Request: GetProjectionThreadMessageInput,\n    Result: ProjectionThreadMessageDbRowSchema,\n    execute: ({ messageId }) =>\n      sql`\n        SELECT\n          message_id AS \"messageId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          role,\n          text,\n          attachments_json AS \"attachments\",\n          is_streaming AS \"isStreaming\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_messages\n        WHERE message_id = ${messageId}\n        LIMIT 1\n      `,\n  });\n\n  const listProjectionThreadMessageRows = SqlSchema.findAll({\n    Request: ListProjectionThreadMessagesInput,\n    Result: ProjectionThreadMessageDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          message_id AS \"messageId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          role,\n          text,\n          attachments_json AS \"attachments\",\n          is_streaming AS \"isStreaming\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_messages\n        WHERE thread_id = ${threadId}\n        ORDER BY created_at ASC, message_id ASC\n      `,\n  });\n\n  const deleteProjectionThreadMessageRows = SqlSchema.void({\n    Request: DeleteProjectionThreadMessagesInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_thread_messages\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProjectionThreadMessageRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadMessageRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadMessageRepository.upsert:query\")),\n    );\n\n  const getByMessageId: ProjectionThreadMessageRepositoryShape[\"getByMessageId\"] = (input) =>\n    getProjectionThreadMessageRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadMessageRepository.getByMessageId:query\"),\n      ),\n      Effect.map(Option.map(toProjectionThreadMessage)),\n    );\n\n  const listByThreadId: ProjectionThreadMessageRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionThreadMessageRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadMessageRepository.listByThreadId:query\"),\n      ),\n      Effect.map((rows) => rows.map(toProjectionThreadMessage)),\n    );\n\n  const deleteByThreadId: ProjectionThreadMessageRepositoryShape[\"deleteByThreadId\"] = (input) =>\n    deleteProjectionThreadMessageRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadMessageRepository.deleteByThreadId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    getByMessageId,\n    listByThreadId,\n    deleteByThreadId,\n  } satisfies ProjectionThreadMessageRepositoryShape;\n});\n\nexport const ProjectionThreadMessageRepositoryLive = Layer.effect(\n  ProjectionThreadMessageRepository,\n  makeProjectionThreadMessageRepository,\n);\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  DeleteProjectionThreadProposedPlansInput,\n  ListProjectionThreadProposedPlansInput,\n  ProjectionThreadProposedPlan,\n  ProjectionThreadProposedPlanRepository,\n  type ProjectionThreadProposedPlanRepositoryShape,\n} from \"../Services/ProjectionThreadProposedPlans.ts\";\n\nconst makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadProposedPlanRow = SqlSchema.void({\n    Request: ProjectionThreadProposedPlan,\n    execute: (row) => sql`\n      INSERT INTO projection_thread_proposed_plans (\n        plan_id,\n        thread_id,\n        turn_id,\n        plan_markdown,\n        implemented_at,\n        implementation_thread_id,\n        created_at,\n        updated_at\n      )\n      VALUES (\n        ${row.planId},\n        ${row.threadId},\n        ${row.turnId},\n        ${row.planMarkdown},\n        ${row.implementedAt},\n        ${row.implementationThreadId},\n        ${row.createdAt},\n        ${row.updatedAt}\n      )\n      ON CONFLICT (plan_id)\n      DO UPDATE SET\n        thread_id = excluded.thread_id,\n        turn_id = excluded.turn_id,\n        plan_markdown = excluded.plan_markdown,\n        implemented_at = excluded.implemented_at,\n        implementation_thread_id = excluded.implementation_thread_id,\n        created_at = excluded.created_at,\n        updated_at = excluded.updated_at\n    `,\n  });\n\n  const listProjectionThreadProposedPlanRows = SqlSchema.findAll({\n    Request: ListProjectionThreadProposedPlansInput,\n    Result: ProjectionThreadProposedPlan,\n    execute: ({ threadId }) => sql`\n      SELECT\n        plan_id AS \"planId\",\n        thread_id AS \"threadId\",\n        turn_id AS \"turnId\",\n        plan_markdown AS \"planMarkdown\",\n        implemented_at AS \"implementedAt\",\n        implementation_thread_id AS \"implementationThreadId\",\n        created_at AS \"createdAt\",\n        updated_at AS \"updatedAt\"\n      FROM projection_thread_proposed_plans\n      WHERE thread_id = ${threadId}\n      ORDER BY created_at ASC, plan_id ASC\n    `,\n  });\n\n  const deleteProjectionThreadProposedPlanRows = SqlSchema.void({\n    Request: DeleteProjectionThreadProposedPlansInput,\n    execute: ({ threadId }) => sql`\n      DELETE FROM projection_thread_proposed_plans\n      WHERE thread_id = ${threadId}\n    `,\n  });\n\n  const upsert: ProjectionThreadProposedPlanRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadProposedPlanRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadProposedPlanRepository.upsert:query\")),\n    );\n\n  const listByThreadId: ProjectionThreadProposedPlanRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionThreadProposedPlanRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadProposedPlanRepository.listByThreadId:query\"),\n      ),\n    );\n\n  const deleteByThreadId: ProjectionThreadProposedPlanRepositoryShape[\"deleteByThreadId\"] = (\n    input,\n  ) =>\n    deleteProjectionThreadProposedPlanRows(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadProposedPlanRepository.deleteByThreadId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    listByThreadId,\n    deleteByThreadId,\n  } satisfies ProjectionThreadProposedPlanRepositoryShape;\n});\n\nexport const ProjectionThreadProposedPlanRepositoryLive = Layer.effect(\n  ProjectionThreadProposedPlanRepository,\n  makeProjectionThreadProposedPlanRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\n\nimport {\n  ProjectionThreadSession,\n  ProjectionThreadSessionRepository,\n  type ProjectionThreadSessionRepositoryShape,\n  DeleteProjectionThreadSessionInput,\n  GetProjectionThreadSessionInput,\n} from \"../Services/ProjectionThreadSessions.ts\";\n\nconst makeProjectionThreadSessionRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadSessionRow = SqlSchema.void({\n    Request: ProjectionThreadSession,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_thread_sessions (\n          thread_id,\n          status,\n          provider_name,\n          provider_instance_id,\n          runtime_mode,\n          active_turn_id,\n          last_error,\n          updated_at\n        )\n        VALUES (\n          ${row.threadId},\n          ${row.status},\n          ${row.providerName},\n          ${row.providerInstanceId},\n          ${row.runtimeMode},\n          ${row.activeTurnId},\n          ${row.lastError},\n          ${row.updatedAt}\n        )\n        ON CONFLICT (thread_id)\n        DO UPDATE SET\n          status = excluded.status,\n          provider_name = excluded.provider_name,\n          provider_instance_id = excluded.provider_instance_id,\n          runtime_mode = excluded.runtime_mode,\n          active_turn_id = excluded.active_turn_id,\n          last_error = excluded.last_error,\n          updated_at = excluded.updated_at\n      `,\n  });\n\n  const getProjectionThreadSessionRow = SqlSchema.findOneOption({\n    Request: GetProjectionThreadSessionInput,\n    Result: ProjectionThreadSession,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          status,\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          runtime_mode AS \"runtimeMode\",\n          active_turn_id AS \"activeTurnId\",\n          last_error AS \"lastError\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const deleteProjectionThreadSessionRow = SqlSchema.void({\n    Request: DeleteProjectionThreadSessionInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_thread_sessions\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProjectionThreadSessionRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadSessionRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadSessionRepository.upsert:query\")),\n    );\n\n  const getByThreadId: ProjectionThreadSessionRepositoryShape[\"getByThreadId\"] = (input) =>\n    getProjectionThreadSessionRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadSessionRepository.getByThreadId:query\"),\n      ),\n    );\n\n  const deleteByThreadId: ProjectionThreadSessionRepositoryShape[\"deleteByThreadId\"] = (input) =>\n    deleteProjectionThreadSessionRow(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlError(\"ProjectionThreadSessionRepository.deleteByThreadId:query\"),\n      ),\n    );\n\n  return {\n    upsert,\n    getByThreadId,\n    deleteByThreadId,\n  } satisfies ProjectionThreadSessionRepositoryShape;\n});\n\nexport const ProjectionThreadSessionRepositoryLive = Layer.effect(\n  ProjectionThreadSessionRepository,\n  makeProjectionThreadSessionRepository,\n);\n","import { OrchestrationCheckpointFile } from \"@t3tools/contracts\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\n\nimport { toPersistenceDecodeError, toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  ClearCheckpointTurnConflictInput,\n  DeleteProjectionTurnsByThreadInput,\n  GetProjectionPendingTurnStartInput,\n  GetProjectionTurnByTurnIdInput,\n  ListProjectionTurnsByThreadInput,\n  ProjectionPendingTurnStart,\n  ProjectionTurn,\n  ProjectionTurnById,\n  ProjectionTurnRepository,\n  type ProjectionTurnRepositoryShape,\n} from \"../Services/ProjectionTurns.ts\";\n\nconst ProjectionTurnDbRowSchema = ProjectionTurn.mapFields(\n  Struct.assign({\n    checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),\n  }),\n);\n\nconst ProjectionTurnByIdDbRowSchema = ProjectionTurnById.mapFields(\n  Struct.assign({\n    checkpointFiles: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),\n  }),\n);\n\nfunction toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {\n  return (cause: unknown) =>\n    Schema.isSchemaError(cause)\n      ? toPersistenceDecodeError(decodeOperation)(cause)\n      : toPersistenceSqlError(sqlOperation)(cause);\n}\n\nconst makeProjectionTurnRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionTurnById = SqlSchema.void({\n    Request: ProjectionTurnByIdDbRowSchema,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_turns (\n          thread_id,\n          turn_id,\n          pending_message_id,\n          source_proposed_plan_thread_id,\n          source_proposed_plan_id,\n          assistant_message_id,\n          state,\n          requested_at,\n          started_at,\n          completed_at,\n          checkpoint_turn_count,\n          checkpoint_ref,\n          checkpoint_status,\n          checkpoint_files_json\n        )\n        VALUES (\n          ${row.threadId},\n          ${row.turnId},\n          ${row.pendingMessageId},\n          ${row.sourceProposedPlanThreadId},\n          ${row.sourceProposedPlanId},\n          ${row.assistantMessageId},\n          ${row.state},\n          ${row.requestedAt},\n          ${row.startedAt},\n          ${row.completedAt},\n          ${row.checkpointTurnCount},\n          ${row.checkpointRef},\n          ${row.checkpointStatus},\n          ${row.checkpointFiles}\n        )\n        ON CONFLICT (thread_id, turn_id)\n        DO UPDATE SET\n          pending_message_id = excluded.pending_message_id,\n          source_proposed_plan_thread_id = excluded.source_proposed_plan_thread_id,\n          source_proposed_plan_id = excluded.source_proposed_plan_id,\n          assistant_message_id = excluded.assistant_message_id,\n          state = excluded.state,\n          requested_at = excluded.requested_at,\n          started_at = excluded.started_at,\n          completed_at = excluded.completed_at,\n          checkpoint_turn_count = excluded.checkpoint_turn_count,\n          checkpoint_ref = excluded.checkpoint_ref,\n          checkpoint_status = excluded.checkpoint_status,\n          checkpoint_files_json = excluded.checkpoint_files_json\n      `,\n  });\n\n  const clearPendingProjectionTurnsByThread = SqlSchema.void({\n    Request: DeleteProjectionTurnsByThreadInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_turns\n        WHERE thread_id = ${threadId}\n          AND turn_id IS NULL\n          AND state = 'pending'\n          AND checkpoint_turn_count IS NULL\n      `,\n  });\n\n  const insertPendingProjectionTurn = SqlSchema.void({\n    Request: ProjectionPendingTurnStart,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_turns (\n          thread_id,\n          turn_id,\n          pending_message_id,\n          source_proposed_plan_thread_id,\n          source_proposed_plan_id,\n          assistant_message_id,\n          state,\n          requested_at,\n          started_at,\n          completed_at,\n          checkpoint_turn_count,\n          checkpoint_ref,\n          checkpoint_status,\n          checkpoint_files_json\n        )\n        VALUES (\n          ${row.threadId},\n          NULL,\n          ${row.messageId},\n          ${row.sourceProposedPlanThreadId},\n          ${row.sourceProposedPlanId},\n          NULL,\n          'pending',\n          ${row.requestedAt},\n          NULL,\n          NULL,\n          NULL,\n          NULL,\n          NULL,\n          '[]'\n        )\n      `,\n  });\n\n  const getPendingProjectionTurn = SqlSchema.findOneOption({\n    Request: GetProjectionPendingTurnStartInput,\n    Result: ProjectionPendingTurnStart,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          pending_message_id AS \"messageId\",\n          source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          source_proposed_plan_id AS \"sourceProposedPlanId\",\n          requested_at AS \"requestedAt\"\n        FROM projection_turns\n        WHERE thread_id = ${threadId}\n          AND turn_id IS NULL\n          AND state = 'pending'\n          AND pending_message_id IS NOT NULL\n          AND checkpoint_turn_count IS NULL\n        ORDER BY requested_at DESC\n        LIMIT 1\n      `,\n  });\n\n  const listProjectionTurnsByThread = SqlSchema.findAll({\n    Request: ListProjectionTurnsByThreadInput,\n    Result: ProjectionTurnDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          pending_message_id AS \"pendingMessageId\",\n          source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          source_proposed_plan_id AS \"sourceProposedPlanId\",\n          assistant_message_id AS \"assistantMessageId\",\n          state,\n          requested_at AS \"requestedAt\",\n          started_at AS \"startedAt\",\n          completed_at AS \"completedAt\",\n          checkpoint_turn_count AS \"checkpointTurnCount\",\n          checkpoint_ref AS \"checkpointRef\",\n          checkpoint_status AS \"checkpointStatus\",\n          checkpoint_files_json AS \"checkpointFiles\"\n        FROM projection_turns\n        WHERE thread_id = ${threadId}\n        ORDER BY\n          CASE\n            WHEN checkpoint_turn_count IS NULL THEN 1\n            ELSE 0\n          END ASC,\n          checkpoint_turn_count ASC,\n          requested_at ASC,\n          turn_id ASC\n      `,\n  });\n\n  const getProjectionTurnByTurnId = SqlSchema.findOneOption({\n    Request: GetProjectionTurnByTurnIdInput,\n    Result: ProjectionTurnByIdDbRowSchema,\n    execute: ({ threadId, turnId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          pending_message_id AS \"pendingMessageId\",\n          source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          source_proposed_plan_id AS \"sourceProposedPlanId\",\n          assistant_message_id AS \"assistantMessageId\",\n          state,\n          requested_at AS \"requestedAt\",\n          started_at AS \"startedAt\",\n          completed_at AS \"completedAt\",\n          checkpoint_turn_count AS \"checkpointTurnCount\",\n          checkpoint_ref AS \"checkpointRef\",\n          checkpoint_status AS \"checkpointStatus\",\n          checkpoint_files_json AS \"checkpointFiles\"\n        FROM projection_turns\n        WHERE thread_id = ${threadId}\n          AND turn_id = ${turnId}\n        LIMIT 1\n      `,\n  });\n\n  const clearCheckpointTurnConflictRow = SqlSchema.void({\n    Request: ClearCheckpointTurnConflictInput,\n    execute: ({ threadId, turnId, checkpointTurnCount }) =>\n      sql`\n        UPDATE projection_turns\n        SET\n          checkpoint_turn_count = NULL,\n          checkpoint_ref = NULL,\n          checkpoint_status = NULL,\n          checkpoint_files_json = '[]'\n        WHERE thread_id = ${threadId}\n          AND checkpoint_turn_count = ${checkpointTurnCount}\n          AND (turn_id IS NULL OR turn_id <> ${turnId})\n      `,\n  });\n\n  const deleteProjectionTurnsByThread = SqlSchema.void({\n    Request: DeleteProjectionTurnsByThreadInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_turns\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsertByTurnId: ProjectionTurnRepositoryShape[\"upsertByTurnId\"] = (row) =>\n    upsertProjectionTurnById(row).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionTurnRepository.upsertByTurnId:query\",\n          \"ProjectionTurnRepository.upsertByTurnId:encodeRequest\",\n        ),\n      ),\n    );\n\n  const replacePendingTurnStart: ProjectionTurnRepositoryShape[\"replacePendingTurnStart\"] = (row) =>\n    sql\n      .withTransaction(\n        clearPendingProjectionTurnsByThread({ threadId: row.threadId }).pipe(\n          Effect.flatMap(() => insertPendingProjectionTurn(row)),\n        ),\n      )\n      .pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionTurnRepository.replacePendingTurnStart:query\",\n            \"ProjectionTurnRepository.replacePendingTurnStart:encodeRequest\",\n          ),\n        ),\n      );\n\n  const getPendingTurnStartByThreadId: ProjectionTurnRepositoryShape[\"getPendingTurnStartByThreadId\"] =\n    (input) =>\n      getPendingProjectionTurn(input).pipe(\n        Effect.mapError(\n          toPersistenceSqlError(\"ProjectionTurnRepository.getPendingTurnStartByThreadId:query\"),\n        ),\n      );\n\n  const deletePendingTurnStartByThreadId: ProjectionTurnRepositoryShape[\"deletePendingTurnStartByThreadId\"] =\n    (input) =>\n      clearPendingProjectionTurnsByThread(input).pipe(\n        Effect.mapError(\n          toPersistenceSqlError(\"ProjectionTurnRepository.deletePendingTurnStartByThreadId:query\"),\n        ),\n      );\n\n  const listByThreadId: ProjectionTurnRepositoryShape[\"listByThreadId\"] = (input) =>\n    listProjectionTurnsByThread(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionTurnRepository.listByThreadId:query\",\n          \"ProjectionTurnRepository.listByThreadId:decodeRows\",\n        ),\n      ),\n      Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionTurn>>),\n    );\n\n  const getByTurnId: ProjectionTurnRepositoryShape[\"getByTurnId\"] = (input) =>\n    getProjectionTurnByTurnId(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionTurnRepository.getByTurnId:query\",\n          \"ProjectionTurnRepository.getByTurnId:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((rowOption) =>\n        Option.match(rowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionTurnById>)),\n        }),\n      ),\n    );\n\n  const clearCheckpointTurnConflict: ProjectionTurnRepositoryShape[\"clearCheckpointTurnConflict\"] =\n    (input) =>\n      clearCheckpointTurnConflictRow(input).pipe(\n        Effect.mapError(\n          toPersistenceSqlError(\"ProjectionTurnRepository.clearCheckpointTurnConflict:query\"),\n        ),\n      );\n\n  const deleteByThreadId: ProjectionTurnRepositoryShape[\"deleteByThreadId\"] = (input) =>\n    deleteProjectionTurnsByThread(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionTurnRepository.deleteByThreadId:query\")),\n    );\n\n  return {\n    upsertByTurnId,\n    replacePendingTurnStart,\n    getPendingTurnStartByThreadId,\n    deletePendingTurnStartByThreadId,\n    listByThreadId,\n    getByTurnId,\n    clearCheckpointTurnConflict,\n    deleteByThreadId,\n  } satisfies ProjectionTurnRepositoryShape;\n});\n\nexport const ProjectionTurnRepositoryLive = Layer.effect(\n  ProjectionTurnRepository,\n  makeProjectionTurnRepository,\n);\n","import * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\n\nimport { toPersistenceSqlError } from \"../Errors.ts\";\nimport {\n  DeleteProjectionThreadInput,\n  GetProjectionThreadInput,\n  ListProjectionThreadsByProjectInput,\n  ProjectionThread,\n  ProjectionThreadRepository,\n  type ProjectionThreadRepositoryShape,\n} from \"../Services/ProjectionThreads.ts\";\nimport { ModelSelection } from \"@t3tools/contracts\";\n\nconst ProjectionThreadDbRow = ProjectionThread.mapFields(\n  Struct.assign({\n    modelSelection: Schema.fromJsonString(ModelSelection),\n  }),\n);\ntype ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;\n\nconst makeProjectionThreadRepository = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertProjectionThreadRow = SqlSchema.void({\n    Request: ProjectionThread,\n    execute: (row) =>\n      sql`\n        INSERT INTO projection_threads (\n          thread_id,\n          project_id,\n          title,\n          model_selection_json,\n          runtime_mode,\n          interaction_mode,\n          branch,\n          worktree_path,\n          latest_turn_id,\n          created_at,\n          updated_at,\n          archived_at,\n          settled_override,\n          settled_at,\n          snoozed_until,\n          snoozed_at,\n          pinned_at,\n          pin_order_key,\n          title_regeneration_request_id,\n          title_regeneration_started_at,\n          latest_user_message_at,\n          pending_approval_count,\n          pending_user_input_count,\n          has_actionable_proposed_plan,\n          deleted_at\n        )\n        VALUES (\n          ${row.threadId},\n          ${row.projectId},\n          ${row.title},\n          ${JSON.stringify(row.modelSelection)},\n          ${row.runtimeMode},\n          ${row.interactionMode},\n          ${row.branch},\n          ${row.worktreePath},\n          ${row.latestTurnId},\n          ${row.createdAt},\n          ${row.updatedAt},\n          ${row.archivedAt},\n          ${row.settledOverride},\n          ${row.settledAt},\n          ${row.snoozedUntil},\n          ${row.snoozedAt},\n          ${row.pinnedAt},\n          ${row.pinOrderKey ?? null},\n          ${row.titleRegenerationRequestId ?? null},\n          ${row.titleRegenerationStartedAt ?? null},\n          ${row.latestUserMessageAt},\n          ${row.pendingApprovalCount},\n          ${row.pendingUserInputCount},\n          ${row.hasActionableProposedPlan},\n          ${row.deletedAt}\n        )\n        ON CONFLICT (thread_id)\n        DO UPDATE SET\n          project_id = excluded.project_id,\n          title = excluded.title,\n          model_selection_json = excluded.model_selection_json,\n          runtime_mode = excluded.runtime_mode,\n          interaction_mode = excluded.interaction_mode,\n          branch = excluded.branch,\n          worktree_path = excluded.worktree_path,\n          latest_turn_id = excluded.latest_turn_id,\n          created_at = excluded.created_at,\n          updated_at = excluded.updated_at,\n          archived_at = excluded.archived_at,\n          settled_override = excluded.settled_override,\n          settled_at = excluded.settled_at,\n          snoozed_until = excluded.snoozed_until,\n          snoozed_at = excluded.snoozed_at,\n          pinned_at = excluded.pinned_at,\n          pin_order_key = excluded.pin_order_key,\n          title_regeneration_request_id = excluded.title_regeneration_request_id,\n          title_regeneration_started_at = excluded.title_regeneration_started_at,\n          latest_user_message_at = excluded.latest_user_message_at,\n          pending_approval_count = excluded.pending_approval_count,\n          pending_user_input_count = excluded.pending_user_input_count,\n          has_actionable_proposed_plan = excluded.has_actionable_proposed_plan,\n          deleted_at = excluded.deleted_at\n      `,\n  });\n\n  const getProjectionThreadRow = SqlSchema.findOneOption({\n    Request: GetProjectionThreadInput,\n    Result: ProjectionThreadDbRow,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          pin_order_key AS \"pinOrderKey\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const listProjectionThreadRows = SqlSchema.findAll({\n    Request: ListProjectionThreadsByProjectInput,\n    Result: ProjectionThreadDbRow,\n    execute: ({ projectId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          pin_order_key AS \"pinOrderKey\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE project_id = ${projectId}\n        ORDER BY created_at ASC, thread_id ASC\n      `,\n  });\n\n  const deleteProjectionThreadRow = SqlSchema.void({\n    Request: DeleteProjectionThreadInput,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM projection_threads\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProjectionThreadRepositoryShape[\"upsert\"] = (row) =>\n    upsertProjectionThreadRow(row).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadRepository.upsert:query\")),\n    );\n\n  const getById: ProjectionThreadRepositoryShape[\"getById\"] = (input) =>\n    getProjectionThreadRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadRepository.getById:query\")),\n    );\n\n  const listByProjectId: ProjectionThreadRepositoryShape[\"listByProjectId\"] = (input) =>\n    listProjectionThreadRows(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadRepository.listByProjectId:query\")),\n    );\n\n  const deleteById: ProjectionThreadRepositoryShape[\"deleteById\"] = (input) =>\n    deleteProjectionThreadRow(input).pipe(\n      Effect.mapError(toPersistenceSqlError(\"ProjectionThreadRepository.deleteById:query\")),\n    );\n\n  return {\n    upsert,\n    getById,\n    listByProjectId,\n    deleteById,\n  } satisfies ProjectionThreadRepositoryShape;\n});\n\nexport const ProjectionThreadRepositoryLive = Layer.effect(\n  ProjectionThreadRepository,\n  makeProjectionThreadRepository,\n);\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodePath from \"node:path\";\n\nexport function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {\n  const normalized = NodePath.normalize(rawRelativePath).replace(/^[/\\\\]+/, \"\");\n  if (normalized.length === 0 || normalized.startsWith(\"..\") || normalized.includes(\"\\0\")) {\n    return null;\n  }\n  return normalized.replace(/\\\\/g, \"/\");\n}\n\nexport function resolveAttachmentRelativePath(input: {\n  readonly attachmentsDir: string;\n  readonly relativePath: string;\n}): string | null {\n  const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);\n  if (!normalizedRelativePath) {\n    return null;\n  }\n\n  const attachmentsRoot = NodePath.resolve(input.attachmentsDir);\n  const filePath = NodePath.resolve(NodePath.join(attachmentsRoot, normalizedRelativePath));\n  if (!filePath.startsWith(`${attachmentsRoot}${NodePath.sep}`)) {\n    return null;\n  }\n  return filePath;\n}\n","import Mime from \"@effect/platform-node/Mime\";\n\nexport const IMAGE_EXTENSION_BY_MIME_TYPE: Record<string, string> = {\n  \"image/avif\": \".avif\",\n  \"image/bmp\": \".bmp\",\n  \"image/gif\": \".gif\",\n  \"image/heic\": \".heic\",\n  \"image/heif\": \".heif\",\n  \"image/jpeg\": \".jpg\",\n  \"image/jpg\": \".jpg\",\n  \"image/png\": \".png\",\n  \"image/svg+xml\": \".svg\",\n  \"image/tiff\": \".tiff\",\n  \"image/webp\": \".webp\",\n};\n\nexport const SAFE_IMAGE_FILE_EXTENSIONS = new Set([\n  \".avif\",\n  \".bmp\",\n  \".gif\",\n  \".heic\",\n  \".heif\",\n  \".ico\",\n  \".jpeg\",\n  \".jpg\",\n  \".png\",\n  \".svg\",\n  \".tiff\",\n  \".webp\",\n]);\n\n// Whether `code` is a character the base64 payload may contain, aside from\n// the whitespace handled separately below.\nfunction isBase64Char(code: number): boolean {\n  return (\n    (code >= 0x61 && code <= 0x7a) || // a-z\n    (code >= 0x41 && code <= 0x5a) || // A-Z\n    (code >= 0x30 && code <= 0x39) || // 0-9\n    code === 0x2b || // +\n    code === 0x2f || // /\n    code === 0x3d // =\n  );\n}\n\nfunction isBase64Whitespace(code: number): boolean {\n  return code === 0x0d || code === 0x0a || code === 0x20; // \\r \\n space\n}\n\n// Data URLs carry the full image payload, so this parser must never run a\n// regex across the payload: V8's regex engine borrows the JS call stack, and\n// matching a multi-megabyte string from a deep call stack (e.g. inside fiber\n// execution) throws \"Maximum call stack size exceeded\".\nexport function parseBase64DataUrl(\n  dataUrl: string,\n): { readonly mimeType: string; readonly base64: string } | null {\n  const trimmed = dataUrl.trim();\n  if (trimmed.slice(0, 5).toLowerCase() !== \"data:\") return null;\n\n  const commaIndex = trimmed.indexOf(\",\");\n  if (commaIndex === -1) return null;\n  const header = trimmed.slice(5, commaIndex);\n  if (header.length === 0) return null;\n\n  const headerParts: Array<string> = [];\n  for (const part of header.split(\";\")) {\n    const partTrimmed = part.trim();\n    if (partTrimmed.length > 0) {\n      headerParts.push(partTrimmed);\n    }\n  }\n  if (headerParts.length < 2) {\n    return null;\n  }\n  const trailingToken = headerParts.at(-1)?.toLowerCase();\n  if (trailingToken !== \"base64\") {\n    return null;\n  }\n\n  const mimeType = headerParts[0]?.toLowerCase();\n  if (!mimeType) return null;\n\n  const payload = trimmed.slice(commaIndex + 1);\n  const runs: Array<string> = [];\n  let runStart = -1;\n  for (let index = 0; index < payload.length; index += 1) {\n    const code = payload.charCodeAt(index);\n    if (isBase64Char(code)) {\n      if (runStart === -1) runStart = index;\n      continue;\n    }\n    if (!isBase64Whitespace(code)) return null;\n    if (runStart !== -1) {\n      runs.push(payload.slice(runStart, index));\n      runStart = -1;\n    }\n  }\n  if (runStart !== -1) {\n    runs.push(payload.slice(runStart));\n  }\n  const base64 = runs.length === 1 ? runs[0]! : runs.join(\"\");\n  if (base64.length === 0 || base64.length % 4 !== 0) return null;\n  const firstPad = base64.indexOf(\"=\");\n  if (firstPad !== -1) {\n    // '=' is only valid as one or two trailing padding characters; Node's\n    // decoder would otherwise silently truncate at the first '='.\n    if (base64.length - firstPad > 2) return null;\n    for (let index = firstPad; index < base64.length; index += 1) {\n      if (base64.charCodeAt(index) !== 0x3d) return null;\n    }\n  }\n\n  return { mimeType, base64 };\n}\n\nexport function inferImageExtension(input: { mimeType: string; fileName?: string }): string {\n  const key = input.mimeType.toLowerCase();\n  const fromMime = Object.hasOwn(IMAGE_EXTENSION_BY_MIME_TYPE, key)\n    ? IMAGE_EXTENSION_BY_MIME_TYPE[key]\n    : undefined;\n  if (fromMime) {\n    return fromMime;\n  }\n\n  const fromMimeExtension = Mime.getExtension(input.mimeType);\n  if (fromMimeExtension && SAFE_IMAGE_FILE_EXTENSIONS.has(fromMimeExtension)) {\n    return fromMimeExtension;\n  }\n\n  const fileName = input.fileName?.trim() ?? \"\";\n  const extensionMatch = /\\.([a-z0-9]{1,8})$/i.exec(fileName);\n  const fileNameExtension = extensionMatch ? `.${extensionMatch[1]!.toLowerCase()}` : \"\";\n  if (SAFE_IMAGE_FILE_EXTENSIONS.has(fileNameExtension)) {\n    return fileNameExtension;\n  }\n\n  return \".bin\";\n}\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeCrypto from \"node:crypto\";\nimport * as NodeFS from \"node:fs\";\n\nimport type { ChatAttachment } from \"@t3tools/contracts\";\n\nimport {\n  normalizeAttachmentRelativePath,\n  resolveAttachmentRelativePath,\n} from \"./attachmentPaths.ts\";\nimport { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from \"./imageMime.ts\";\n\nconst ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, \".bin\"];\nconst ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;\nconst ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = \"[a-z0-9_]+(?:-[a-z0-9_]+)*\";\nconst ATTACHMENT_ID_UUID_PATTERN = \"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\";\nconst ATTACHMENT_ID_PATTERN = new RegExp(\n  `^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,\n  \"i\",\n);\n\nexport function toSafeThreadAttachmentSegment(threadId: string): string | null {\n  const segment = threadId\n    .trim()\n    .toLowerCase()\n    .replace(/[^a-z0-9_-]+/gi, \"-\")\n    .replace(/-+/g, \"-\")\n    .replace(/^[-_]+|[-_]+$/g, \"\")\n    .slice(0, ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS)\n    .replace(/[-_]+$/g, \"\");\n  if (segment.length === 0) {\n    return null;\n  }\n  return segment;\n}\n\nexport function createAttachmentId(threadId: string): string | null {\n  const threadSegment = toSafeThreadAttachmentSegment(threadId);\n  if (!threadSegment) {\n    return null;\n  }\n  return `${threadSegment}-${NodeCrypto.randomUUID()}`;\n}\n\nexport function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {\n  const normalizedId = normalizeAttachmentRelativePath(attachmentId);\n  if (!normalizedId || normalizedId.includes(\"/\") || normalizedId.includes(\".\")) {\n    return null;\n  }\n  const match = normalizedId.match(ATTACHMENT_ID_PATTERN);\n  if (!match) {\n    return null;\n  }\n  return match[1]?.toLowerCase() ?? null;\n}\n\nexport function attachmentRelativePath(attachment: ChatAttachment): string {\n  switch (attachment.type) {\n    case \"image\": {\n      const extension = inferImageExtension({\n        mimeType: attachment.mimeType,\n        fileName: attachment.name,\n      });\n      return `${attachment.id}${extension}`;\n    }\n  }\n}\n\nexport function resolveAttachmentPath(input: {\n  readonly attachmentsDir: string;\n  readonly attachment: ChatAttachment;\n}): string | null {\n  return resolveAttachmentRelativePath({\n    attachmentsDir: input.attachmentsDir,\n    relativePath: attachmentRelativePath(input.attachment),\n  });\n}\n\nexport function resolveAttachmentPathById(input: {\n  readonly attachmentsDir: string;\n  readonly attachmentId: string;\n}): string | null {\n  const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);\n  if (!normalizedId || normalizedId.includes(\"/\") || normalizedId.includes(\".\")) {\n    return null;\n  }\n  for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {\n    const maybePath = resolveAttachmentRelativePath({\n      attachmentsDir: input.attachmentsDir,\n      relativePath: `${normalizedId}${extension}`,\n    });\n    if (maybePath && NodeFS.existsSync(maybePath)) {\n      return maybePath;\n    }\n  }\n  return null;\n}\n\nexport function parseAttachmentIdFromRelativePath(relativePath: string): string | null {\n  const normalized = normalizeAttachmentRelativePath(relativePath);\n  if (!normalized || normalized.includes(\"/\")) {\n    return null;\n  }\n  const extensionIndex = normalized.lastIndexOf(\".\");\n  if (extensionIndex <= 0) {\n    return null;\n  }\n  const id = normalized.slice(0, extensionIndex);\n  return id.length > 0 && !id.includes(\".\") ? id : null;\n}\n","import {\n  ApprovalRequestId,\n  type ChatAttachment,\n  type OrchestrationEvent,\n  type OrchestrationSessionStatus,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Stream from \"effect/Stream\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\nimport { toPersistenceSqlError, type ProjectionRepositoryError } from \"../../persistence/Errors.ts\";\nimport { OrchestrationEventStore } from \"../../persistence/Services/OrchestrationEventStore.ts\";\nimport { ProjectionPendingApprovalRepository } from \"../../persistence/Services/ProjectionPendingApprovals.ts\";\nimport { ProjectionProjectRepository } from \"../../persistence/Services/ProjectionProjects.ts\";\nimport { ProjectionStateRepository } from \"../../persistence/Services/ProjectionState.ts\";\nimport { ProjectionThreadActivityRepository } from \"../../persistence/Services/ProjectionThreadActivities.ts\";\nimport { type ProjectionThreadActivity } from \"../../persistence/Services/ProjectionThreadActivities.ts\";\nimport {\n  type ProjectionThreadMessage,\n  ProjectionThreadMessageRepository,\n} from \"../../persistence/Services/ProjectionThreadMessages.ts\";\nimport {\n  type ProjectionThreadProposedPlan,\n  ProjectionThreadProposedPlanRepository,\n} from \"../../persistence/Services/ProjectionThreadProposedPlans.ts\";\nimport { ProjectionThreadSessionRepository } from \"../../persistence/Services/ProjectionThreadSessions.ts\";\nimport {\n  type ProjectionTurn,\n  ProjectionTurnRepository,\n} from \"../../persistence/Services/ProjectionTurns.ts\";\nimport { ProjectionThreadRepository } from \"../../persistence/Services/ProjectionThreads.ts\";\nimport { ProjectionPendingApprovalRepositoryLive } from \"../../persistence/Layers/ProjectionPendingApprovals.ts\";\nimport { ProjectionProjectRepositoryLive } from \"../../persistence/Layers/ProjectionProjects.ts\";\nimport { ProjectionStateRepositoryLive } from \"../../persistence/Layers/ProjectionState.ts\";\nimport { ProjectionThreadActivityRepositoryLive } from \"../../persistence/Layers/ProjectionThreadActivities.ts\";\nimport { ProjectionThreadMessageRepositoryLive } from \"../../persistence/Layers/ProjectionThreadMessages.ts\";\nimport { ProjectionThreadProposedPlanRepositoryLive } from \"../../persistence/Layers/ProjectionThreadProposedPlans.ts\";\nimport { ProjectionThreadSessionRepositoryLive } from \"../../persistence/Layers/ProjectionThreadSessions.ts\";\nimport { ProjectionTurnRepositoryLive } from \"../../persistence/Layers/ProjectionTurns.ts\";\nimport { ProjectionThreadRepositoryLive } from \"../../persistence/Layers/ProjectionThreads.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport {\n  OrchestrationProjectionPipeline,\n  type OrchestrationProjectionPipelineShape,\n} from \"../Services/ProjectionPipeline.ts\";\nimport {\n  attachmentRelativePath,\n  parseAttachmentIdFromRelativePath,\n  parseThreadSegmentFromAttachmentId,\n  toSafeThreadAttachmentSegment,\n} from \"../../attachmentStore.ts\";\n\nexport const ORCHESTRATION_PROJECTOR_NAMES = {\n  projects: \"projection.projects\",\n  threads: \"projection.threads\",\n  threadMessages: \"projection.thread-messages\",\n  threadProposedPlans: \"projection.thread-proposed-plans\",\n  threadActivities: \"projection.thread-activities\",\n  threadSessions: \"projection.thread-sessions\",\n  threadTurns: \"projection.thread-turns\",\n  checkpoints: \"projection.checkpoints\",\n  pendingApprovals: \"projection.pending-approvals\",\n} as const;\n\ntype ProjectorName =\n  (typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];\n\n/**\n * Turn state to settle still-running turns with when their session leaves the\n * \"running\" status, or null while the session is (re)starting or running and\n * turns must stay unsettled.\n */\nfunction settledTurnStateForSessionStatus(\n  status: OrchestrationSessionStatus,\n): \"completed\" | \"interrupted\" | \"error\" | null {\n  switch (status) {\n    case \"idle\":\n    case \"ready\":\n      return \"completed\";\n    case \"error\":\n      return \"error\";\n    case \"interrupted\":\n    case \"stopped\":\n      return \"interrupted\";\n    case \"starting\":\n    case \"running\":\n      return null;\n  }\n}\n\ninterface ProjectorDefinition {\n  readonly name: ProjectorName;\n  readonly apply: (\n    event: OrchestrationEvent,\n    attachmentSideEffects: AttachmentSideEffects,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\ninterface AttachmentSideEffects {\n  readonly deletedThreadIds: Set<string>;\n  readonly prunedThreadRelativePaths: Map<string, Set<string>>;\n}\n\nconst materializeAttachmentsForProjection = Effect.fn(\"materializeAttachmentsForProjection\")(\n  (input: { readonly attachments: ReadonlyArray<ChatAttachment> }) =>\n    Effect.succeed(input.attachments.length === 0 ? [] : input.attachments),\n);\n\nfunction extractActivityRequestId(payload: unknown): ApprovalRequestId | null {\n  if (typeof payload !== \"object\" || payload === null) {\n    return null;\n  }\n  const requestId = (payload as Record<string, unknown>).requestId;\n  return typeof requestId === \"string\" ? ApprovalRequestId.make(requestId) : null;\n}\n\nfunction isStalePendingApprovalFailureDetail(detail: string | null): boolean {\n  if (detail === null) {\n    return false;\n  }\n  return (\n    detail.includes(\"stale pending approval request\") ||\n    detail.includes(\"unknown pending approval request\") ||\n    detail.includes(\"unknown pending permission request\")\n  );\n}\n\nfunction derivePendingUserInputCountFromActivities(\n  activities: ReadonlyArray<ProjectionThreadActivity>,\n): number {\n  const openRequestIds = new Set<string>();\n  const ordered = [...activities].toSorted(\n    (left, right) =>\n      left.createdAt.localeCompare(right.createdAt) ||\n      left.activityId.localeCompare(right.activityId),\n  );\n\n  for (const activity of ordered) {\n    const requestId = extractActivityRequestId(activity.payload);\n    if (requestId === null) {\n      continue;\n    }\n    const payload =\n      typeof activity.payload === \"object\" && activity.payload !== null\n        ? (activity.payload as Record<string, unknown>)\n        : null;\n    const detail = typeof payload?.detail === \"string\" ? payload.detail.toLowerCase() : null;\n\n    if (activity.kind === \"user-input.requested\") {\n      openRequestIds.add(requestId);\n      continue;\n    }\n\n    if (activity.kind === \"user-input.resolved\") {\n      openRequestIds.delete(requestId);\n      continue;\n    }\n\n    if (\n      activity.kind === \"provider.user-input.respond.failed\" &&\n      detail !== null &&\n      (detail.includes(\"stale pending user-input request\") ||\n        detail.includes(\"unknown pending user-input request\") ||\n        detail.includes(\"unknown pending user input request\") ||\n        detail.includes(\"unknown pending codex user input request\"))\n    ) {\n      openRequestIds.delete(requestId);\n    }\n  }\n\n  return openRequestIds.size;\n}\n\nfunction deriveHasActionableProposedPlan(input: {\n  readonly latestTurnId: string | null;\n  readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;\n}): boolean {\n  const sorted = [...input.proposedPlans].toSorted(\n    (left, right) =>\n      left.updatedAt.localeCompare(right.updatedAt) || left.planId.localeCompare(right.planId),\n  );\n\n  let latestForTurn: ProjectionThreadProposedPlan | null = null;\n  if (input.latestTurnId !== null) {\n    for (let index = sorted.length - 1; index >= 0; index -= 1) {\n      const plan = sorted[index];\n      if (plan?.turnId === input.latestTurnId) {\n        latestForTurn = plan;\n        break;\n      }\n    }\n  }\n  if (latestForTurn !== null) {\n    return latestForTurn.implementedAt === null;\n  }\n\n  const latestPlan = sorted.at(-1) ?? null;\n  return latestPlan !== null && latestPlan.implementedAt === null;\n}\n\nfunction retainProjectionMessagesAfterRevert(\n  messages: ReadonlyArray<ProjectionThreadMessage>,\n  turns: ReadonlyArray<ProjectionTurn>,\n  turnCount: number,\n): ReadonlyArray<ProjectionThreadMessage> {\n  const retainedMessageIds = new Set<string>();\n  const retainedTurnIds = new Set<string>();\n  const keptTurns = turns.filter(\n    (turn) =>\n      turn.turnId !== null &&\n      turn.checkpointTurnCount !== null &&\n      turn.checkpointTurnCount <= turnCount,\n  );\n  for (const turn of keptTurns) {\n    if (turn.turnId !== null) {\n      retainedTurnIds.add(turn.turnId);\n    }\n    if (turn.pendingMessageId !== null) {\n      retainedMessageIds.add(turn.pendingMessageId);\n    }\n    if (turn.assistantMessageId !== null) {\n      retainedMessageIds.add(turn.assistantMessageId);\n    }\n  }\n\n  for (const message of messages) {\n    if (message.role === \"system\") {\n      retainedMessageIds.add(message.messageId);\n      continue;\n    }\n    if (message.turnId !== null && retainedTurnIds.has(message.turnId)) {\n      retainedMessageIds.add(message.messageId);\n    }\n  }\n\n  const retainedUserCount = messages.filter(\n    (message) => message.role === \"user\" && retainedMessageIds.has(message.messageId),\n  ).length;\n  const missingUserCount = Math.max(0, turnCount - retainedUserCount);\n  if (missingUserCount > 0) {\n    const fallbackUserMessages = messages\n      .filter(\n        (message) =>\n          message.role === \"user\" &&\n          !retainedMessageIds.has(message.messageId) &&\n          (message.turnId === null || retainedTurnIds.has(message.turnId)),\n      )\n      .toSorted(\n        (left, right) =>\n          left.createdAt.localeCompare(right.createdAt) ||\n          left.messageId.localeCompare(right.messageId),\n      )\n      .slice(0, missingUserCount);\n    for (const message of fallbackUserMessages) {\n      retainedMessageIds.add(message.messageId);\n    }\n  }\n\n  const retainedAssistantCount = messages.filter(\n    (message) => message.role === \"assistant\" && retainedMessageIds.has(message.messageId),\n  ).length;\n  const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount);\n  if (missingAssistantCount > 0) {\n    const fallbackAssistantMessages = messages\n      .filter(\n        (message) =>\n          message.role === \"assistant\" &&\n          !retainedMessageIds.has(message.messageId) &&\n          (message.turnId === null || retainedTurnIds.has(message.turnId)),\n      )\n      .toSorted(\n        (left, right) =>\n          left.createdAt.localeCompare(right.createdAt) ||\n          left.messageId.localeCompare(right.messageId),\n      )\n      .slice(0, missingAssistantCount);\n    for (const message of fallbackAssistantMessages) {\n      retainedMessageIds.add(message.messageId);\n    }\n  }\n\n  return messages.filter((message) => retainedMessageIds.has(message.messageId));\n}\n\nfunction retainProjectionActivitiesAfterRevert(\n  activities: ReadonlyArray<ProjectionThreadActivity>,\n  turns: ReadonlyArray<ProjectionTurn>,\n  turnCount: number,\n): ReadonlyArray<ProjectionThreadActivity> {\n  const retainedTurnIds = new Set<string>(\n    turns\n      .filter(\n        (turn) =>\n          turn.turnId !== null &&\n          turn.checkpointTurnCount !== null &&\n          turn.checkpointTurnCount <= turnCount,\n      )\n      .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),\n  );\n  return activities.filter(\n    (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId),\n  );\n}\n\nfunction retainProjectionProposedPlansAfterRevert(\n  proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>,\n  turns: ReadonlyArray<ProjectionTurn>,\n  turnCount: number,\n): ReadonlyArray<ProjectionThreadProposedPlan> {\n  const retainedTurnIds = new Set<string>(\n    turns\n      .filter(\n        (turn) =>\n          turn.turnId !== null &&\n          turn.checkpointTurnCount !== null &&\n          turn.checkpointTurnCount <= turnCount,\n      )\n      .flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),\n  );\n  return proposedPlans.filter(\n    (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),\n  );\n}\n\nfunction collectThreadAttachmentRelativePaths(\n  threadId: string,\n  messages: ReadonlyArray<ProjectionThreadMessage>,\n): Set<string> {\n  const threadSegment = toSafeThreadAttachmentSegment(threadId);\n  if (!threadSegment) {\n    return new Set();\n  }\n  const relativePaths = new Set<string>();\n  for (const message of messages) {\n    for (const attachment of message.attachments ?? []) {\n      if (attachment.type !== \"image\") {\n        continue;\n      }\n      const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachment.id);\n      if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {\n        continue;\n      }\n      relativePaths.add(attachmentRelativePath(attachment));\n    }\n  }\n  return relativePaths;\n}\n\nconst runAttachmentSideEffects = Effect.fn(\"runAttachmentSideEffects\")(function* (\n  sideEffects: AttachmentSideEffects,\n) {\n  const serverConfig = yield* Effect.service(ServerConfig);\n  const fileSystem = yield* Effect.service(FileSystem.FileSystem);\n  const path = yield* Effect.service(Path.Path);\n\n  const attachmentsRootDir = serverConfig.attachmentsDir;\n  const readAttachmentRootEntries = fileSystem\n    .readDirectory(attachmentsRootDir, { recursive: false })\n    .pipe(Effect.orElseSucceed(() => [] as Array<string>));\n\n  const removeDeletedThreadAttachmentEntry = Effect.fn(\"removeDeletedThreadAttachmentEntry\")(\n    function* (threadSegment: string, entry: string) {\n      const normalizedEntry = entry.replace(/^[/\\\\]+/, \"\").replace(/\\\\/g, \"/\");\n      if (normalizedEntry.length === 0 || normalizedEntry.includes(\"/\")) {\n        return;\n      }\n      const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry);\n      if (!attachmentId) {\n        return;\n      }\n      const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);\n      if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {\n        return;\n      }\n      yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), {\n        force: true,\n      });\n    },\n  );\n\n  const deleteThreadAttachments = Effect.fn(\"deleteThreadAttachments\")(function* (\n    threadId: string,\n  ) {\n    const threadSegment = toSafeThreadAttachmentSegment(threadId);\n    if (!threadSegment) {\n      yield* Effect.logWarning(\"skipping attachment cleanup for unsafe thread id\", {\n        threadId,\n      });\n      return;\n    }\n\n    const entries = yield* readAttachmentRootEntries;\n    yield* Effect.forEach(\n      entries,\n      (entry) => removeDeletedThreadAttachmentEntry(threadSegment, entry),\n      {\n        concurrency: 1,\n      },\n    );\n  });\n\n  const pruneThreadAttachmentEntry = Effect.fn(\"pruneThreadAttachmentEntry\")(function* (\n    threadSegment: string,\n    keptThreadRelativePaths: Set<string>,\n    entry: string,\n  ) {\n    const relativePath = entry.replace(/^[/\\\\]+/, \"\").replace(/\\\\/g, \"/\");\n    if (relativePath.length === 0 || relativePath.includes(\"/\")) {\n      return;\n    }\n    const attachmentId = parseAttachmentIdFromRelativePath(relativePath);\n    if (!attachmentId) {\n      return;\n    }\n    const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId);\n    if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) {\n      return;\n    }\n\n    const absolutePath = path.join(attachmentsRootDir, relativePath);\n    const fileInfo = yield* fileSystem.stat(absolutePath).pipe(Effect.orElseSucceed(() => null));\n    if (!fileInfo || fileInfo.type !== \"File\") {\n      return;\n    }\n\n    if (!keptThreadRelativePaths.has(relativePath)) {\n      yield* fileSystem.remove(absolutePath, { force: true });\n    }\n  });\n\n  const pruneThreadAttachments = Effect.fn(\"pruneThreadAttachments\")(function* (\n    threadId: string,\n    keptThreadRelativePaths: Set<string>,\n  ) {\n    if (sideEffects.deletedThreadIds.has(threadId)) {\n      return;\n    }\n\n    const threadSegment = toSafeThreadAttachmentSegment(threadId);\n    if (!threadSegment) {\n      yield* Effect.logWarning(\"skipping attachment prune for unsafe thread id\", { threadId });\n      return;\n    }\n\n    const entries = yield* readAttachmentRootEntries;\n    yield* Effect.forEach(\n      entries,\n      (entry) => pruneThreadAttachmentEntry(threadSegment, keptThreadRelativePaths, entry),\n      { concurrency: 1 },\n    );\n  });\n\n  yield* Effect.forEach(sideEffects.deletedThreadIds, deleteThreadAttachments, {\n    concurrency: 1,\n  });\n\n  yield* Effect.forEach(\n    sideEffects.prunedThreadRelativePaths.entries(),\n    ([threadId, keptThreadRelativePaths]) =>\n      pruneThreadAttachments(threadId, keptThreadRelativePaths),\n    { concurrency: 1 },\n  );\n});\n\nconst makeOrchestrationProjectionPipeline = Effect.fn(\"makeOrchestrationProjectionPipeline\")(\n  function* () {\n    const sql = yield* SqlClient.SqlClient;\n    const eventStore = yield* OrchestrationEventStore;\n    const projectionStateRepository = yield* ProjectionStateRepository;\n    const projectionProjectRepository = yield* ProjectionProjectRepository;\n    const projectionThreadRepository = yield* ProjectionThreadRepository;\n    const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;\n    const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;\n    const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;\n    const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;\n    const projectionTurnRepository = yield* ProjectionTurnRepository;\n    const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;\n\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const serverConfig = yield* ServerConfig;\n\n    const applyProjectsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyProjectsProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"project.created\":\n          yield* projectionProjectRepository.upsert({\n            projectId: event.payload.projectId,\n            title: event.payload.title,\n            workspaceRoot: event.payload.workspaceRoot,\n            defaultModelSelection: event.payload.defaultModelSelection,\n            scripts: event.payload.scripts,\n            createdAt: event.payload.createdAt,\n            updatedAt: event.payload.updatedAt,\n            deletedAt: null,\n          });\n          return;\n\n        case \"project.meta-updated\": {\n          const existingRow = yield* projectionProjectRepository.getById({\n            projectId: event.payload.projectId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionProjectRepository.upsert({\n            ...existingRow.value,\n            ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),\n            ...(event.payload.workspaceRoot !== undefined\n              ? { workspaceRoot: event.payload.workspaceRoot }\n              : {}),\n            ...(event.payload.defaultModelSelection !== undefined\n              ? { defaultModelSelection: event.payload.defaultModelSelection }\n              : {}),\n            ...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"project.deleted\": {\n          const existingRow = yield* projectionProjectRepository.getById({\n            projectId: event.payload.projectId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionProjectRepository.upsert({\n            ...existingRow.value,\n            deletedAt: event.payload.deletedAt,\n            updatedAt: event.payload.deletedAt,\n          });\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const refreshThreadShellSummary = Effect.fn(\"refreshThreadShellSummary\")(function* (\n      threadId: ThreadId,\n    ) {\n      const existingRow = yield* projectionThreadRepository.getById({\n        threadId,\n      });\n      if (Option.isNone(existingRow)) {\n        return;\n      }\n\n      const [messages, proposedPlans, activities, pendingApprovals] = yield* Effect.all([\n        projectionThreadMessageRepository.listByThreadId({ threadId }),\n        projectionThreadProposedPlanRepository.listByThreadId({ threadId }),\n        projectionThreadActivityRepository.listByThreadId({ threadId }),\n        projectionPendingApprovalRepository.listByThreadId({ threadId }),\n      ]);\n\n      let latestUserMessageAt: string | null = null;\n      for (const message of messages) {\n        if (\n          message.role === \"user\" &&\n          (latestUserMessageAt === null || message.createdAt > latestUserMessageAt)\n        ) {\n          latestUserMessageAt = message.createdAt;\n        }\n      }\n\n      const pendingApprovalCount = pendingApprovals.filter(\n        (approval) => approval.status === \"pending\",\n      ).length;\n      const pendingUserInputCount = derivePendingUserInputCountFromActivities(activities);\n      const hasActionableProposedPlan = deriveHasActionableProposedPlan({\n        latestTurnId: existingRow.value.latestTurnId,\n        proposedPlans,\n      });\n\n      yield* projectionThreadRepository.upsert({\n        ...existingRow.value,\n        latestUserMessageAt,\n        pendingApprovalCount,\n        pendingUserInputCount,\n        hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0,\n      });\n    });\n\n    const applyThreadsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadsProjection\",\n    )(function* (event, attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.created\":\n          yield* projectionThreadRepository.upsert({\n            threadId: event.payload.threadId,\n            projectId: event.payload.projectId,\n            title: event.payload.title,\n            modelSelection: event.payload.modelSelection,\n            runtimeMode: event.payload.runtimeMode,\n            interactionMode: event.payload.interactionMode,\n            branch: event.payload.branch,\n            worktreePath: event.payload.worktreePath,\n            latestTurnId: null,\n            createdAt: event.payload.createdAt,\n            updatedAt: event.payload.updatedAt,\n            archivedAt: null,\n            settledOverride: null,\n            settledAt: null,\n            snoozedUntil: null,\n            snoozedAt: null,\n            pinnedAt: null,\n            pinOrderKey: null,\n            titleRegenerationRequestId: null,\n            titleRegenerationStartedAt: null,\n            latestUserMessageAt: null,\n            pendingApprovalCount: 0,\n            pendingUserInputCount: 0,\n            hasActionableProposedPlan: 0,\n            deletedAt: null,\n          });\n          return;\n\n        case \"thread.archived\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            archivedAt: event.payload.archivedAt,\n            titleRegenerationRequestId: null,\n            titleRegenerationStartedAt: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.unarchived\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            archivedAt: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.settled\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            settledOverride: \"settled\",\n            settledAt: event.payload.settledAt,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.unsettled\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            settledOverride: event.payload.reason === \"user\" ? \"active\" : null,\n            settledAt: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.snoozed\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            snoozedUntil: event.payload.snoozedUntil,\n            snoozedAt: event.payload.snoozedAt,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.unsnoozed\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            snoozedUntil: null,\n            snoozedAt: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.pinned\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            pinnedAt: event.payload.pinnedAt,\n            ...(event.payload.pinOrderKey !== undefined\n              ? { pinOrderKey: event.payload.pinOrderKey }\n              : {}),\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.unpinned\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            pinnedAt: null,\n            pinOrderKey: null,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.pin-reordered\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            pinOrderKey: event.payload.orderKey,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.meta-updated\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            ...(event.payload.title !== undefined ? { title: event.payload.title } : {}),\n            ...(event.payload.titleRegeneration !== undefined\n              ? {\n                  titleRegenerationRequestId: event.payload.titleRegeneration?.requestId ?? null,\n                  titleRegenerationStartedAt: event.payload.titleRegeneration?.startedAt ?? null,\n                }\n              : {}),\n            ...(event.payload.modelSelection !== undefined\n              ? { modelSelection: event.payload.modelSelection }\n              : {}),\n            ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),\n            ...(event.payload.worktreePath !== undefined\n              ? { worktreePath: event.payload.worktreePath }\n              : {}),\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.runtime-mode-set\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            runtimeMode: event.payload.runtimeMode,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.interaction-mode-set\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            interactionMode: event.payload.interactionMode,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.deleted\": {\n          attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            deletedAt: event.payload.deletedAt,\n            updatedAt: event.payload.deletedAt,\n          });\n          return;\n        }\n\n        case \"thread.message-sent\":\n        case \"thread.proposed-plan-upserted\":\n        case \"thread.activity-appended\":\n        case \"thread.approval-response-requested\":\n        case \"thread.user-input-response-requested\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            updatedAt: event.occurredAt,\n          });\n          yield* refreshThreadShellSummary(event.payload.threadId);\n          return;\n        }\n\n        case \"thread.session-set\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            // activeTurnId describes current work; a terminal session must not erase history.\n            latestTurnId: event.payload.session.activeTurnId ?? existingRow.value.latestTurnId,\n            updatedAt: event.occurredAt,\n          });\n          yield* refreshThreadShellSummary(event.payload.threadId);\n          return;\n        }\n\n        case \"thread.turn-diff-completed\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            latestTurnId: event.payload.turnId,\n            updatedAt: event.occurredAt,\n          });\n          yield* refreshThreadShellSummary(event.payload.threadId);\n          return;\n        }\n\n        case \"thread.reverted\": {\n          const existingRow = yield* projectionThreadRepository.getById({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isNone(existingRow)) {\n            return;\n          }\n\n          const retainedTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          let latestTurnId: ProjectionTurn[\"turnId\"] = null;\n          let latestCheckpointTurnCount = -1;\n          for (let index = 0; index < retainedTurns.length; index += 1) {\n            const turn = retainedTurns[index];\n            if (\n              !turn ||\n              turn.turnId === null ||\n              turn.checkpointTurnCount === null ||\n              turn.checkpointTurnCount > event.payload.turnCount\n            ) {\n              continue;\n            }\n            if (turn.checkpointTurnCount > latestCheckpointTurnCount) {\n              latestCheckpointTurnCount = turn.checkpointTurnCount;\n              latestTurnId = turn.turnId;\n            }\n          }\n\n          yield* projectionThreadRepository.upsert({\n            ...existingRow.value,\n            latestTurnId,\n            updatedAt: event.occurredAt,\n          });\n          yield* refreshThreadShellSummary(event.payload.threadId);\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyThreadMessagesProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadMessagesProjection\",\n    )(function* (event, attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.message-sent\": {\n          const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({\n            messageId: event.payload.messageId,\n          });\n          const previousMessage = Option.getOrUndefined(existingMessage);\n          const nextText = Option.match(existingMessage, {\n            onNone: () => event.payload.text,\n            onSome: (message) => {\n              if (event.payload.streaming) {\n                return `${message.text}${event.payload.text}`;\n              }\n              if (event.payload.text.length === 0) {\n                return message.text;\n              }\n              return event.payload.text;\n            },\n          });\n          const nextAttachments =\n            event.payload.attachments !== undefined\n              ? yield* materializeAttachmentsForProjection({\n                  attachments: event.payload.attachments,\n                })\n              : previousMessage?.attachments;\n          yield* projectionThreadMessageRepository.upsert({\n            messageId: event.payload.messageId,\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n            role: event.payload.role,\n            text: nextText,\n            ...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),\n            isStreaming: event.payload.streaming,\n            createdAt: previousMessage?.createdAt ?? event.payload.createdAt,\n            updatedAt: event.payload.updatedAt,\n          });\n          return;\n        }\n\n        case \"thread.reverted\": {\n          const existingRows = yield* projectionThreadMessageRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          if (existingRows.length === 0) {\n            return;\n          }\n\n          const existingTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const keptRows = retainProjectionMessagesAfterRevert(\n            existingRows,\n            existingTurns,\n            event.payload.turnCount,\n          );\n          if (keptRows.length === existingRows.length) {\n            return;\n          }\n\n          yield* projectionThreadMessageRepository.deleteByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(keptRows, projectionThreadMessageRepository.upsert, {\n            concurrency: 1,\n          }).pipe(Effect.asVoid);\n          attachmentSideEffects.prunedThreadRelativePaths.set(\n            event.payload.threadId,\n            collectThreadAttachmentRelativePaths(event.payload.threadId, keptRows),\n          );\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyThreadProposedPlansProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadProposedPlansProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.proposed-plan-upserted\":\n          yield* projectionThreadProposedPlanRepository.upsert({\n            planId: event.payload.proposedPlan.id,\n            threadId: event.payload.threadId,\n            turnId: event.payload.proposedPlan.turnId,\n            planMarkdown: event.payload.proposedPlan.planMarkdown,\n            implementedAt: event.payload.proposedPlan.implementedAt,\n            implementationThreadId: event.payload.proposedPlan.implementationThreadId,\n            createdAt: event.payload.proposedPlan.createdAt,\n            updatedAt: event.payload.proposedPlan.updatedAt,\n          });\n          return;\n\n        case \"thread.reverted\": {\n          const existingRows = yield* projectionThreadProposedPlanRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          if (existingRows.length === 0) {\n            return;\n          }\n\n          const existingTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const keptRows = retainProjectionProposedPlansAfterRevert(\n            existingRows,\n            existingTurns,\n            event.payload.turnCount,\n          );\n          if (keptRows.length === existingRows.length) {\n            return;\n          }\n\n          yield* projectionThreadProposedPlanRepository.deleteByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(keptRows, projectionThreadProposedPlanRepository.upsert, {\n            concurrency: 1,\n          }).pipe(Effect.asVoid);\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyThreadActivitiesProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadActivitiesProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.activity-appended\":\n          yield* projectionThreadActivityRepository.upsert({\n            activityId: event.payload.activity.id,\n            threadId: event.payload.threadId,\n            turnId: event.payload.activity.turnId,\n            tone: event.payload.activity.tone,\n            kind: event.payload.activity.kind,\n            summary: event.payload.activity.summary,\n            payload: event.payload.activity.payload,\n            ...(event.payload.activity.sequence !== undefined\n              ? { sequence: event.payload.activity.sequence }\n              : {}),\n            createdAt: event.payload.activity.createdAt,\n          });\n          return;\n\n        case \"thread.reverted\": {\n          const existingRows = yield* projectionThreadActivityRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          if (existingRows.length === 0) {\n            return;\n          }\n          const existingTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const keptRows = retainProjectionActivitiesAfterRevert(\n            existingRows,\n            existingTurns,\n            event.payload.turnCount,\n          );\n          if (keptRows.length === existingRows.length) {\n            return;\n          }\n          yield* projectionThreadActivityRepository.deleteByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(keptRows, projectionThreadActivityRepository.upsert, {\n            concurrency: 1,\n          }).pipe(Effect.asVoid);\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyThreadSessionsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadSessionsProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      if (event.type !== \"thread.session-set\") {\n        return;\n      }\n      yield* projectionThreadSessionRepository.upsert({\n        threadId: event.payload.threadId,\n        status: event.payload.session.status,\n        providerName: event.payload.session.providerName,\n        providerInstanceId: event.payload.session.providerInstanceId ?? null,\n        runtimeMode: event.payload.session.runtimeMode,\n        activeTurnId: event.payload.session.activeTurnId,\n        lastError: event.payload.session.lastError,\n        updatedAt: event.payload.session.updatedAt,\n      });\n    });\n\n    const applyThreadTurnsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyThreadTurnsProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.turn-start-requested\": {\n          yield* projectionTurnRepository.replacePendingTurnStart({\n            threadId: event.payload.threadId,\n            messageId: event.payload.messageId,\n            sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,\n            sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,\n            requestedAt: event.payload.createdAt,\n          });\n          return;\n        }\n\n        case \"thread.session-set\": {\n          const turnId = event.payload.session.activeTurnId;\n          if (turnId === null || event.payload.session.status !== \"running\") {\n            if (\n              event.payload.session.status === \"error\" ||\n              event.payload.session.status === \"stopped\" ||\n              event.payload.session.status === \"interrupted\"\n            ) {\n              yield* projectionTurnRepository.deletePendingTurnStartByThreadId({\n                threadId: event.payload.threadId,\n              });\n            }\n            // Leaving the \"running\" session status is the turn-end signal:\n            // settle still-running turns so their duration reflects the whole\n            // turn rather than the last assistant message.\n            const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);\n            if (settledTurnState === null) {\n              return;\n            }\n            const existingTurns = yield* projectionTurnRepository.listByThreadId({\n              threadId: event.payload.threadId,\n            });\n            yield* Effect.forEach(\n              existingTurns.filter((turn) => turn.turnId !== null && turn.state === \"running\"),\n              (turn) =>\n                turn.turnId === null\n                  ? Effect.void\n                  : projectionTurnRepository.upsertByTurnId({\n                      ...turn,\n                      turnId: turn.turnId,\n                      state: settledTurnState,\n                      // A running turn's completedAt can only hold a mid-turn\n                      // placeholder checkpoint timestamp — the session leaving\n                      // \"running\" is the authoritative turn end.\n                      completedAt: event.payload.session.updatedAt,\n                    }),\n              { concurrency: 1 },\n            );\n            return;\n          }\n\n          // A new active turn supersedes any still-running turn on the same\n          // thread — steering can open a new turn without the provider ever\n          // completing the previous one.\n          const otherRunningTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(\n            otherRunningTurns.filter(\n              (turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === \"running\",\n            ),\n            (turn) =>\n              turn.turnId === null\n                ? Effect.void\n                : projectionTurnRepository.upsertByTurnId({\n                    ...turn,\n                    turnId: turn.turnId,\n                    state: \"completed\",\n                    completedAt: event.payload.session.updatedAt,\n                  }),\n            { concurrency: 1 },\n          );\n\n          const existingTurn = yield* projectionTurnRepository.getByTurnId({\n            threadId: event.payload.threadId,\n            turnId,\n          });\n          const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({\n            threadId: event.payload.threadId,\n          });\n          if (Option.isSome(existingTurn)) {\n            const nextState =\n              existingTurn.value.state === \"completed\" || existingTurn.value.state === \"error\"\n                ? existingTurn.value.state\n                : \"running\";\n            yield* projectionTurnRepository.upsertByTurnId({\n              ...existingTurn.value,\n              state: nextState,\n              pendingMessageId:\n                existingTurn.value.pendingMessageId ??\n                (Option.isSome(pendingTurnStart) ? pendingTurnStart.value.messageId : null),\n              sourceProposedPlanThreadId:\n                existingTurn.value.sourceProposedPlanThreadId ??\n                (Option.isSome(pendingTurnStart)\n                  ? pendingTurnStart.value.sourceProposedPlanThreadId\n                  : null),\n              sourceProposedPlanId:\n                existingTurn.value.sourceProposedPlanId ??\n                (Option.isSome(pendingTurnStart)\n                  ? pendingTurnStart.value.sourceProposedPlanId\n                  : null),\n              startedAt:\n                existingTurn.value.startedAt ??\n                (Option.isSome(pendingTurnStart)\n                  ? pendingTurnStart.value.requestedAt\n                  : event.occurredAt),\n              requestedAt:\n                existingTurn.value.requestedAt ??\n                (Option.isSome(pendingTurnStart)\n                  ? pendingTurnStart.value.requestedAt\n                  : event.occurredAt),\n            });\n          } else {\n            yield* projectionTurnRepository.upsertByTurnId({\n              turnId,\n              threadId: event.payload.threadId,\n              pendingMessageId: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.messageId\n                : null,\n              sourceProposedPlanThreadId: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.sourceProposedPlanThreadId\n                : null,\n              sourceProposedPlanId: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.sourceProposedPlanId\n                : null,\n              assistantMessageId: null,\n              state: \"running\",\n              requestedAt: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.requestedAt\n                : event.occurredAt,\n              startedAt: Option.isSome(pendingTurnStart)\n                ? pendingTurnStart.value.requestedAt\n                : event.occurredAt,\n              completedAt: null,\n              checkpointTurnCount: null,\n              checkpointRef: null,\n              checkpointStatus: null,\n              checkpointFiles: [],\n            });\n          }\n\n          yield* projectionTurnRepository.deletePendingTurnStartByThreadId({\n            threadId: event.payload.threadId,\n          });\n          return;\n        }\n\n        case \"thread.message-sent\": {\n          if (event.payload.turnId === null || event.payload.role !== \"assistant\") {\n            return;\n          }\n          // A completed assistant message only settles the turn once the\n          // session is no longer running it — providers may emit several\n          // assistant messages per turn (commentary between tool calls), and\n          // the turn must stay unsettled until the provider reports turn end\n          // (projected as thread.session-set leaving the \"running\" status).\n          const session = yield* projectionThreadSessionRepository.getByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const turnStillRunning =\n            Option.isSome(session) &&\n            session.value.status === \"running\" &&\n            session.value.activeTurnId === event.payload.turnId;\n          const settlesTurn = !event.payload.streaming && !turnStillRunning;\n          const existingTurn = yield* projectionTurnRepository.getByTurnId({\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n          });\n          if (Option.isSome(existingTurn)) {\n            yield* projectionTurnRepository.upsertByTurnId({\n              ...existingTurn.value,\n              assistantMessageId: event.payload.messageId,\n              state: settlesTurn\n                ? existingTurn.value.state === \"interrupted\"\n                  ? \"interrupted\"\n                  : existingTurn.value.state === \"error\"\n                    ? \"error\"\n                    : \"completed\"\n                : existingTurn.value.state,\n              completedAt: settlesTurn\n                ? (existingTurn.value.completedAt ?? event.payload.updatedAt)\n                : existingTurn.value.completedAt,\n              startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,\n              requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,\n            });\n            return;\n          }\n          yield* projectionTurnRepository.upsertByTurnId({\n            turnId: event.payload.turnId,\n            threadId: event.payload.threadId,\n            pendingMessageId: null,\n            sourceProposedPlanThreadId: null,\n            sourceProposedPlanId: null,\n            assistantMessageId: event.payload.messageId,\n            state: settlesTurn ? \"completed\" : \"running\",\n            requestedAt: event.payload.createdAt,\n            startedAt: event.payload.createdAt,\n            completedAt: settlesTurn ? event.payload.updatedAt : null,\n            checkpointTurnCount: null,\n            checkpointRef: null,\n            checkpointStatus: null,\n            checkpointFiles: [],\n          });\n          return;\n        }\n\n        case \"thread.turn-interrupt-requested\": {\n          if (event.payload.turnId === undefined) {\n            return;\n          }\n          const existingTurn = yield* projectionTurnRepository.getByTurnId({\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n          });\n          if (Option.isSome(existingTurn)) {\n            yield* projectionTurnRepository.upsertByTurnId({\n              ...existingTurn.value,\n              state: \"interrupted\",\n              completedAt: existingTurn.value.completedAt ?? event.payload.createdAt,\n              startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,\n              requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,\n            });\n            return;\n          }\n          yield* projectionTurnRepository.upsertByTurnId({\n            turnId: event.payload.turnId,\n            threadId: event.payload.threadId,\n            pendingMessageId: null,\n            sourceProposedPlanThreadId: null,\n            sourceProposedPlanId: null,\n            assistantMessageId: null,\n            state: \"interrupted\",\n            requestedAt: event.payload.createdAt,\n            startedAt: event.payload.createdAt,\n            completedAt: event.payload.createdAt,\n            checkpointTurnCount: null,\n            checkpointRef: null,\n            checkpointStatus: null,\n            checkpointFiles: [],\n          });\n          return;\n        }\n\n        case \"thread.turn-diff-completed\": {\n          // Mid-turn diff updates produce placeholder checkpoints; record the\n          // checkpoint, but don't settle a turn its session is still running.\n          const session = yield* projectionThreadSessionRepository.getByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const turnStillRunning =\n            Option.isSome(session) &&\n            session.value.status === \"running\" &&\n            session.value.activeTurnId === event.payload.turnId;\n          const existingTurn = yield* projectionTurnRepository.getByTurnId({\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n          });\n          const nextState = event.payload.status === \"error\" ? \"error\" : \"completed\";\n          yield* projectionTurnRepository.clearCheckpointTurnConflict({\n            threadId: event.payload.threadId,\n            turnId: event.payload.turnId,\n            checkpointTurnCount: event.payload.checkpointTurnCount,\n          });\n\n          if (Option.isSome(existingTurn)) {\n            yield* projectionTurnRepository.upsertByTurnId({\n              ...existingTurn.value,\n              assistantMessageId: event.payload.assistantMessageId,\n              state: turnStillRunning ? existingTurn.value.state : nextState,\n              checkpointTurnCount: event.payload.checkpointTurnCount,\n              checkpointRef: event.payload.checkpointRef,\n              checkpointStatus: event.payload.status,\n              checkpointFiles: event.payload.files,\n              startedAt: existingTurn.value.startedAt ?? event.payload.completedAt,\n              requestedAt: existingTurn.value.requestedAt ?? event.payload.completedAt,\n              completedAt: event.payload.completedAt,\n            });\n            return;\n          }\n          yield* projectionTurnRepository.upsertByTurnId({\n            turnId: event.payload.turnId,\n            threadId: event.payload.threadId,\n            pendingMessageId: null,\n            sourceProposedPlanThreadId: null,\n            sourceProposedPlanId: null,\n            assistantMessageId: event.payload.assistantMessageId,\n            state: turnStillRunning ? \"running\" : nextState,\n            requestedAt: event.payload.completedAt,\n            startedAt: event.payload.completedAt,\n            completedAt: event.payload.completedAt,\n            checkpointTurnCount: event.payload.checkpointTurnCount,\n            checkpointRef: event.payload.checkpointRef,\n            checkpointStatus: event.payload.status,\n            checkpointFiles: event.payload.files,\n          });\n          return;\n        }\n\n        case \"thread.reverted\": {\n          const existingTurns = yield* projectionTurnRepository.listByThreadId({\n            threadId: event.payload.threadId,\n          });\n          const keptTurns = existingTurns.filter(\n            (turn) =>\n              turn.turnId !== null &&\n              turn.checkpointTurnCount !== null &&\n              turn.checkpointTurnCount <= event.payload.turnCount,\n          );\n          yield* projectionTurnRepository.deleteByThreadId({\n            threadId: event.payload.threadId,\n          });\n          yield* Effect.forEach(\n            keptTurns,\n            (turn) =>\n              turn.turnId === null\n                ? Effect.void\n                : projectionTurnRepository.upsertByTurnId({\n                    ...turn,\n                    turnId: turn.turnId,\n                  }),\n            { concurrency: 1 },\n          ).pipe(Effect.asVoid);\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const applyCheckpointsProjection: ProjectorDefinition[\"apply\"] = () => Effect.void;\n\n    const applyPendingApprovalsProjection: ProjectorDefinition[\"apply\"] = Effect.fn(\n      \"applyPendingApprovalsProjection\",\n    )(function* (event, _attachmentSideEffects) {\n      switch (event.type) {\n        case \"thread.activity-appended\": {\n          const requestId =\n            extractActivityRequestId(event.payload.activity.payload) ??\n            event.metadata.requestId ??\n            null;\n          if (requestId === null) {\n            return;\n          }\n          const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({\n            requestId,\n          });\n          if (event.payload.activity.kind === \"approval.resolved\") {\n            const resolvedDecisionRaw =\n              typeof event.payload.activity.payload === \"object\" &&\n              event.payload.activity.payload !== null &&\n              \"decision\" in event.payload.activity.payload\n                ? (event.payload.activity.payload as { decision?: unknown }).decision\n                : null;\n            const resolvedDecision =\n              resolvedDecisionRaw === \"accept\" ||\n              resolvedDecisionRaw === \"acceptForSession\" ||\n              resolvedDecisionRaw === \"decline\" ||\n              resolvedDecisionRaw === \"cancel\"\n                ? resolvedDecisionRaw\n                : null;\n            yield* projectionPendingApprovalRepository.upsert({\n              requestId,\n              threadId: Option.isSome(existingRow)\n                ? existingRow.value.threadId\n                : event.payload.threadId,\n              turnId: Option.isSome(existingRow)\n                ? existingRow.value.turnId\n                : event.payload.activity.turnId,\n              status: \"resolved\",\n              decision: resolvedDecision,\n              createdAt: Option.isSome(existingRow)\n                ? existingRow.value.createdAt\n                : event.payload.activity.createdAt,\n              resolvedAt: event.payload.activity.createdAt,\n            });\n            return;\n          }\n          if (event.payload.activity.kind === \"provider.approval.respond.failed\") {\n            const payload =\n              typeof event.payload.activity.payload === \"object\" &&\n              event.payload.activity.payload !== null\n                ? (event.payload.activity.payload as Record<string, unknown>)\n                : null;\n            const detail =\n              typeof payload?.detail === \"string\" ? payload.detail.toLowerCase() : null;\n            if (isStalePendingApprovalFailureDetail(detail)) {\n              if (Option.isNone(existingRow)) {\n                return;\n              }\n              if (existingRow.value.status === \"resolved\") {\n                return;\n              }\n              yield* projectionPendingApprovalRepository.upsert({\n                requestId,\n                threadId: existingRow.value.threadId,\n                turnId: existingRow.value.turnId,\n                status: \"resolved\",\n                decision: null,\n                createdAt: existingRow.value.createdAt,\n                resolvedAt: event.payload.activity.createdAt,\n              });\n              return;\n            }\n            return;\n          }\n          // Only approval-requested activities should create pending-approval\n          // rows.  Other activity kinds that happen to carry a requestId\n          // (e.g. user-input.requested / user-input.resolved) must not\n          // pollute this projection — they have their own accounting via\n          // derivePendingUserInputCountFromActivities.\n          if (event.payload.activity.kind !== \"approval.requested\") {\n            return;\n          }\n          if (Option.isSome(existingRow) && existingRow.value.status === \"resolved\") {\n            return;\n          }\n          yield* projectionPendingApprovalRepository.upsert({\n            requestId,\n            threadId: event.payload.threadId,\n            turnId: event.payload.activity.turnId,\n            status: \"pending\",\n            decision: null,\n            createdAt: Option.isSome(existingRow)\n              ? existingRow.value.createdAt\n              : event.payload.activity.createdAt,\n            resolvedAt: null,\n          });\n          return;\n        }\n\n        case \"thread.approval-response-requested\": {\n          const existingRow = yield* projectionPendingApprovalRepository.getByRequestId({\n            requestId: event.payload.requestId,\n          });\n          yield* projectionPendingApprovalRepository.upsert({\n            requestId: event.payload.requestId,\n            threadId: Option.isSome(existingRow)\n              ? existingRow.value.threadId\n              : event.payload.threadId,\n            turnId: Option.isSome(existingRow) ? existingRow.value.turnId : null,\n            status: \"resolved\",\n            decision: event.payload.decision,\n            createdAt: Option.isSome(existingRow)\n              ? existingRow.value.createdAt\n              : event.payload.createdAt,\n            resolvedAt: event.payload.createdAt,\n          });\n          return;\n        }\n\n        default:\n          return;\n      }\n    });\n\n    const projectors: ReadonlyArray<ProjectorDefinition> = [\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.projects,\n        apply: applyProjectsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,\n        apply: applyThreadMessagesProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,\n        apply: applyThreadProposedPlansProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,\n        apply: applyThreadActivitiesProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,\n        apply: applyThreadSessionsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,\n        apply: applyThreadTurnsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints,\n        apply: applyCheckpointsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals,\n        apply: applyPendingApprovalsProjection,\n      },\n      {\n        name: ORCHESTRATION_PROJECTOR_NAMES.threads,\n        apply: applyThreadsProjection,\n      },\n    ];\n\n    const runProjectorForEvent = Effect.fn(\"runProjectorForEvent\")(function* (\n      projector: ProjectorDefinition,\n      event: OrchestrationEvent,\n    ) {\n      const attachmentSideEffects: AttachmentSideEffects = {\n        deletedThreadIds: new Set<string>(),\n        prunedThreadRelativePaths: new Map<string, Set<string>>(),\n      };\n\n      yield* sql.withTransaction(\n        projector.apply(event, attachmentSideEffects).pipe(\n          Effect.flatMap(() =>\n            projectionStateRepository.upsert({\n              projector: projector.name,\n              lastAppliedSequence: event.sequence,\n              updatedAt: event.occurredAt,\n            }),\n          ),\n        ),\n      );\n\n      yield* runAttachmentSideEffects(attachmentSideEffects).pipe(\n        Effect.catch((cause) =>\n          Effect.logWarning(\"failed to apply projected attachment side-effects\", {\n            projector: projector.name,\n            sequence: event.sequence,\n            eventType: event.type,\n            cause,\n          }),\n        ),\n      );\n    });\n\n    const bootstrapProjector = (projector: ProjectorDefinition) =>\n      projectionStateRepository\n        .getByProjector({\n          projector: projector.name,\n        })\n        .pipe(\n          Effect.flatMap((stateRow) =>\n            Stream.runForEach(\n              eventStore.readFromSequence(\n                Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0,\n              ),\n              (event) => runProjectorForEvent(projector, event),\n            ),\n          ),\n        );\n\n    const projectEvent: OrchestrationProjectionPipelineShape[\"projectEvent\"] = (event) =>\n      Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), {\n        concurrency: 1,\n      }).pipe(\n        Effect.provideService(FileSystem.FileSystem, fileSystem),\n        Effect.provideService(Path.Path, path),\n        Effect.provideService(ServerConfig, serverConfig),\n        Effect.asVoid,\n        Effect.catchTag(\"SqlError\", (sqlError) =>\n          Effect.fail(toPersistenceSqlError(\"ProjectionPipeline.projectEvent:query\")(sqlError)),\n        ),\n      );\n\n    const bootstrap: OrchestrationProjectionPipelineShape[\"bootstrap\"] = Effect.forEach(\n      projectors,\n      bootstrapProjector,\n      { concurrency: 1 },\n    ).pipe(\n      Effect.provideService(FileSystem.FileSystem, fileSystem),\n      Effect.provideService(Path.Path, path),\n      Effect.provideService(ServerConfig, serverConfig),\n      Effect.asVoid,\n      Effect.tap(() =>\n        Effect.logDebug(\"orchestration projection pipeline bootstrapped\").pipe(\n          Effect.annotateLogs({ projectors: projectors.length }),\n        ),\n      ),\n      Effect.catchTag(\"SqlError\", (sqlError) =>\n        Effect.fail(toPersistenceSqlError(\"ProjectionPipeline.bootstrap:query\")(sqlError)),\n      ),\n    );\n\n    return {\n      bootstrap,\n      projectEvent,\n    } satisfies OrchestrationProjectionPipelineShape;\n  },\n);\n\nexport const OrchestrationProjectionPipelineLive = Layer.effect(\n  OrchestrationProjectionPipeline,\n  makeOrchestrationProjectionPipeline(),\n).pipe(\n  Layer.provideMerge(ProjectionProjectRepositoryLive),\n  Layer.provideMerge(ProjectionThreadRepositoryLive),\n  Layer.provideMerge(ProjectionThreadMessageRepositoryLive),\n  Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),\n  Layer.provideMerge(ProjectionThreadActivityRepositoryLive),\n  Layer.provideMerge(ProjectionThreadSessionRepositoryLive),\n  Layer.provideMerge(ProjectionTurnRepositoryLive),\n  Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),\n  Layer.provideMerge(ProjectionStateRepositoryLive),\n);\n","/**\n * ProjectionCheckpointRepository - Projection repository interface for checkpoints.\n *\n * Owns persistence operations for projected checkpoint summaries in thread\n * timelines.\n *\n * @module ProjectionCheckpointRepository\n */\nimport {\n  CheckpointRef,\n  IsoDateTime,\n  MessageId,\n  NonNegativeInt,\n  OrchestrationCheckpointFile,\n  OrchestrationCheckpointStatus,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Context from \"effect/Context\";\nimport * as Schema from \"effect/Schema\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type { ProjectionRepositoryError } from \"../Errors.ts\";\n\nexport const ProjectionCheckpoint = Schema.Struct({\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: OrchestrationCheckpointStatus,\n  files: Schema.Array(OrchestrationCheckpointFile),\n  assistantMessageId: Schema.NullOr(MessageId),\n  completedAt: IsoDateTime,\n});\nexport type ProjectionCheckpoint = typeof ProjectionCheckpoint.Type;\n\nexport const ListByThreadIdInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type ListByThreadIdInput = typeof ListByThreadIdInput.Type;\n\nexport const GetByThreadAndTurnCountInput = Schema.Struct({\n  threadId: ThreadId,\n  checkpointTurnCount: NonNegativeInt,\n});\nexport type GetByThreadAndTurnCountInput = typeof GetByThreadAndTurnCountInput.Type;\n\nexport const DeleteByThreadIdInput = Schema.Struct({\n  threadId: ThreadId,\n});\nexport type DeleteByThreadIdInput = typeof DeleteByThreadIdInput.Type;\n\n/**\n * ProjectionCheckpointRepositoryShape - Service API for projected checkpoints.\n */\nexport interface ProjectionCheckpointRepositoryShape {\n  /**\n   * Insert or replace a projected checkpoint row.\n   *\n   * Upserts by composite key `(threadId, checkpointTurnCount)`.\n   */\n  readonly upsert: (row: ProjectionCheckpoint) => Effect.Effect<void, ProjectionRepositoryError>;\n\n  /**\n   * List projected checkpoints for a thread.\n   *\n   * Returned in ascending checkpoint turn-count order.\n   */\n  readonly listByThreadId: (\n    input: ListByThreadIdInput,\n  ) => Effect.Effect<ReadonlyArray<ProjectionCheckpoint>, ProjectionRepositoryError>;\n\n  /**\n   * Read a projected checkpoint by thread and turn-count key.\n   */\n  readonly getByThreadAndTurnCount: (\n    input: GetByThreadAndTurnCountInput,\n  ) => Effect.Effect<Option.Option<ProjectionCheckpoint>, ProjectionRepositoryError>;\n\n  /**\n   * Delete projected checkpoint rows by thread.\n   */\n  readonly deleteByThreadId: (\n    input: DeleteByThreadIdInput,\n  ) => Effect.Effect<void, ProjectionRepositoryError>;\n}\n\n/**\n * ProjectionCheckpointRepository - Service tag for checkpoint projection persistence.\n */\nexport class ProjectionCheckpointRepository extends Context.Service<\n  ProjectionCheckpointRepository,\n  ProjectionCheckpointRepositoryShape\n>()(\"t3/persistence/Services/ProjectionCheckpoints/ProjectionCheckpointRepository\") {}\n","/**\n * ThreadBackgroundLivenessService - in-memory per-thread background liveness\n * for the sidebar status pill.\n *\n * The turn can settle while native background work runs on (subagent fleets,\n * workflow runs, Monitor watch loops); the shell previously showed nothing.\n * Ingestion records task lifecycle transitions and the shell query reads the\n * derived state at mapping time — no persistence, no migration. After a\n * server restart the registry is empty until new task events arrive, which\n * matches reality: orphaned background work is not live.\n *\n * \"monitoring\" is reserved for watch loops (monitor tasks and background\n * shells) when they are the ONLY live work; any agent work presents as\n * \"working\".\n *\n * @module ThreadBackgroundLivenessService\n */\nimport { INERT_TASK_TYPES, MONITOR_TASK_TYPES } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nexport type ThreadBackgroundLiveness = \"working\" | \"monitoring\" | null;\n\ninterface ThreadLivenessState {\n  readonly agents: Set<string>;\n  readonly monitors: Set<string>;\n}\n\n// Classification sets are the shared contracts copies (MONITOR_TASK_TYPES:\n// watch loops — monitor tasks plus background shells, which in practice are\n// PR babysitting/log tails since pacing sleeps complete inside the turn;\n// INERT_TASK_TYPES: plan-mode bookkeeping) so this registry, ingestion's\n// agentKind stamp, and the client fold can never drift apart.\n\nconst TERMINAL_STATUSES: ReadonlySet<string> = new Set([\n  \"completed\",\n  \"failed\",\n  \"stopped\",\n  \"cancelled\",\n  \"interrupted\",\n]);\n\nexport class ThreadBackgroundLivenessService extends Context.Service<\n  ThreadBackgroundLivenessService,\n  {\n    /**\n     * Feed one task lifecycle transition. taskType may be absent on\n     * synthesized rows (workflow members, Codex children) — those count as\n     * agents. agentId marks a task launched from inside a subagent: its\n     * internal shells are covered by the owning agent's liveness, but a\n     * NESTED AGENT (agentId + agent-flavored taskType) still counts — it\n     * can outlive its parent and must keep the thread Working.\n     */\n    readonly recordTaskLiveness: (input: {\n      readonly threadId: string;\n      readonly taskId: string;\n      readonly taskType: string | undefined;\n      readonly status: string | undefined;\n      readonly kind: \"started\" | \"progress\" | \"updated\" | \"completed\";\n      readonly agentId?: string | undefined;\n    }) => void;\n\n    /** Session death orphans all of a thread's background work. */\n    readonly clearThreadLiveness: (threadId: string) => void;\n\n    /**\n     * Two-state vocabulary by design: any live agent work is \"working\";\n     * \"monitoring\" only when watch loops are the ONLY live work.\n     */\n    readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;\n  }\n>()(\"t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService\") {}\n\nexport function make(): ThreadBackgroundLivenessService[\"Service\"] {\n  const stateByThreadId = new Map<string, ThreadLivenessState>();\n\n  const stateFor = (threadId: string): ThreadLivenessState => {\n    const existing = stateByThreadId.get(threadId);\n    if (existing) {\n      return existing;\n    }\n    const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };\n    stateByThreadId.set(threadId, created);\n    return created;\n  };\n\n  // Classification is per-transition, not sticky: a task first seen without\n  // a taskType may later reveal itself as a shell, become inert, or turn out\n  // to be agent-owned. Every path drops any prior entry for the taskId so a\n  // stale bucket assignment can't pin the thread's status (review finding).\n  const drop = (threadId: string, taskId: string) => {\n    const state = stateByThreadId.get(threadId);\n    if (!state) {\n      return;\n    }\n    state.agents.delete(taskId);\n    state.monitors.delete(taskId);\n    if (state.agents.size === 0 && state.monitors.size === 0) {\n      stateByThreadId.delete(threadId);\n    }\n  };\n\n  return {\n    recordTaskLiveness: (input) => {\n      const taskType = input.taskType;\n      if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {\n        drop(input.threadId, input.taskId);\n        return;\n      }\n      // A subagent's internal non-agent work (its own shells/monitors) is\n      // covered by the owning agent's liveness. Nested agents fall through:\n      // they can outlive their parent (review finding).\n      if (\n        input.agentId !== undefined &&\n        (taskType === undefined || MONITOR_TASK_TYPES.has(taskType))\n      ) {\n        drop(input.threadId, input.taskId);\n        return;\n      }\n\n      // Idle counts as not-live: a resting (resumable) Codex child isn't\n      // doing anything, and an all-idle fleet must not pin Working.\n      const terminal =\n        input.kind === \"completed\" ||\n        input.status === \"idle\" ||\n        (input.status !== undefined && TERMINAL_STATUSES.has(input.status));\n      if (terminal) {\n        drop(input.threadId, input.taskId);\n        return;\n      }\n\n      drop(input.threadId, input.taskId);\n      const state = stateFor(input.threadId);\n      const bucket =\n        taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;\n      bucket.add(input.taskId);\n    },\n\n    clearThreadLiveness: (threadId) => {\n      stateByThreadId.delete(threadId);\n    },\n\n    getThreadBackgroundLiveness: (threadId) => {\n      const state = stateByThreadId.get(threadId);\n      if (!state) {\n        return null;\n      }\n      if (state.agents.size > 0) {\n        return \"working\";\n      }\n      if (state.monitors.size > 0) {\n        return \"monitoring\";\n      }\n      return null;\n    },\n  };\n}\n\nexport const layer = Layer.effect(ThreadBackgroundLivenessService, Effect.sync(make));\n","/**\n * ThreadPlanProgressService - in-memory per-thread plan progress for the\n * Working indicators (sidebar rows, in-chat working line).\n *\n * Plans are a progress annotation, not a surface of their own: the useful\n * kernel of a turn.plan.updated event is \"which step is the agent on right\n * now\". Ingestion records the current step here and the shell query reads it\n * at mapping time — no persistence, no migration (same pattern as\n * ThreadBackgroundLivenessService). Cleared when the turn settles or the\n * session dies, so a finished plan never lingers as stale UI.\n *\n * @module ThreadPlanProgressService\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nexport interface ThreadPlanProgress {\n  readonly step: string;\n  readonly completedSteps: number;\n  readonly totalSteps: number;\n}\n\ninterface PlanStepInput {\n  readonly step: string;\n  readonly status: string;\n}\n\nexport class ThreadPlanProgressService extends Context.Service<\n  ThreadPlanProgressService,\n  {\n    /**\n     * Feed one turn.plan.updated payload. An all-completed plan clears the\n     * entry (the turn is wrapping up; nothing is \"in progress\" anymore).\n     */\n    readonly recordPlanProgress: (threadId: string, plan: ReadonlyArray<PlanStepInput>) => void;\n\n    /** Turn settled or session died: the working indicator reverts to plain. */\n    readonly clearThreadPlanProgress: (threadId: string) => void;\n\n    readonly getThreadPlanProgress: (threadId: string) => ThreadPlanProgress | null;\n  }\n>()(\"t3/orchestration/ThreadPlanProgress/ThreadPlanProgressService\") {}\n\nexport function make(): ThreadPlanProgressService[\"Service\"] {\n  const progressByThreadId = new Map<string, ThreadPlanProgress>();\n\n  return {\n    recordPlanProgress: (threadId, plan) => {\n      const totalSteps = plan.length;\n      const completedSteps = plan.filter((step) => step.status === \"completed\").length;\n      // Current step: the in-progress one, else the first pending one (a\n      // plan that was just written has no in-progress step yet).\n      const current =\n        plan.find((step) => step.status === \"inProgress\") ??\n        plan.find((step) => step.status !== \"completed\");\n      if (totalSteps === 0 || completedSteps === totalSteps || current === undefined) {\n        progressByThreadId.delete(threadId);\n        return;\n      }\n      progressByThreadId.set(threadId, {\n        step: current.step,\n        completedSteps,\n        totalSteps,\n      });\n    },\n\n    clearThreadPlanProgress: (threadId) => {\n      progressByThreadId.delete(threadId);\n    },\n\n    getThreadPlanProgress: (threadId) => progressByThreadId.get(threadId) ?? null,\n  };\n}\n\nexport const layer = Layer.effect(ThreadPlanProgressService, Effect.sync(make));\n","import type { ThreadId } from \"@t3tools/contracts\";\n\n/**\n * Opaque, exclusive cursor for windowed thread detail reads. Encodes the thread\n * id and the keyset boundary of an already-delivered page: the boundary turn's\n * anchor timestamp (`COALESCE(requested_at, started_at, '')`) and turn id.\n * Passing it back requests the adjacent disjoint slice of strictly older turns\n * under `(anchor, turn_id)` ordering.\n *\n * The boundary is deliberately NOT a `projection_turns.row_id`: row ids are\n * rewritten by the revert projector (delete + re-upsert) and by projection\n * rebuilds, which would silently invalidate every persisted cursor with no\n * event emitted. The (anchor, turnId) pair is derived from event content, so\n * cursors survive both and no client-side refresh machinery is needed. The\n * anchor doubles as the time bound for rows with no turn linkage (straggler\n * user messages, turnless activities). The thread id is embedded so a cursor\n * can never be replayed against a different thread. Clients must treat the\n * string as opaque.\n */\nexport interface ThreadDetailPageCursor {\n  readonly threadId: ThreadId;\n  readonly beforeAnchorAt: string;\n  /** Boundary turn id; \"\" for the rare turn row with a null turn_id. */\n  readonly beforeTurnId: string;\n}\n\nexport function encodeThreadDetailPageCursor(cursor: ThreadDetailPageCursor): string {\n  return Buffer.from(\n    JSON.stringify({ t: cursor.threadId, a: cursor.beforeAnchorAt, i: cursor.beforeTurnId }),\n  ).toString(\"base64url\");\n}\n\n/**\n * Returns null for anything that is not a well-formed cursor. Callers degrade\n * a malformed or foreign-thread cursor to a first-page request.\n */\nexport function decodeThreadDetailPageCursor(encoded: string): ThreadDetailPageCursor | null {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(Buffer.from(encoded, \"base64url\").toString(\"utf8\"));\n  } catch {\n    return null;\n  }\n  if (parsed === null || typeof parsed !== \"object\") {\n    return null;\n  }\n  const record = parsed as Record<string, unknown>;\n  if (typeof record.t !== \"string\" || record.t.length === 0) {\n    return null;\n  }\n  // Empty strings are valid boundary values, not malformed input: the anchor\n  // is COALESCE(requested_at, started_at, ''), so a boundary turn with no\n  // timestamps encodes a: \"\" (and sorts before every real anchor, correctly\n  // ending the walk); the turn key is \"\" for a null turn_id.\n  if (typeof record.a !== \"string\") {\n    return null;\n  }\n  if (typeof record.i !== \"string\") {\n    return null;\n  }\n  return { threadId: record.t as ThreadId, beforeAnchorAt: record.a, beforeTurnId: record.i };\n}\n","import type { SourceControlProviderInfo, SourceControlProviderKind } from \"@t3tools/contracts\";\n\nexport interface ChangeRequestPresentation {\n  readonly icon: \"github\" | \"gitlab\" | \"azure-devops\" | \"bitbucket\" | \"change-request\";\n  readonly providerName: string;\n  readonly shortName: string;\n  readonly longName: string;\n  readonly pluralLongName: string;\n  readonly providerLongName: string;\n  readonly checkoutCommandExample?: string;\n  readonly urlExample: string;\n}\n\nexport interface ChangeRequestTerminology {\n  readonly shortLabel: string;\n  readonly singular: string;\n}\n\nexport const DEFAULT_CHANGE_REQUEST_TERMINOLOGY: ChangeRequestTerminology = {\n  shortLabel: \"PR\",\n  singular: \"pull request\",\n};\n\nconst GITHUB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"github\",\n  providerName: \"GitHub\",\n  shortName: \"PR\",\n  longName: \"pull request\",\n  pluralLongName: \"pull requests\",\n  providerLongName: \"GitHub pull request\",\n  checkoutCommandExample: \"gh pr checkout 123\",\n  urlExample: \"https://github.com/owner/repo/pull/42\",\n};\n\nconst GITLAB_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"gitlab\",\n  providerName: \"GitLab\",\n  shortName: \"MR\",\n  longName: \"merge request\",\n  pluralLongName: \"merge requests\",\n  providerLongName: \"GitLab merge request\",\n  checkoutCommandExample: \"glab mr checkout 123\",\n  urlExample: \"https://gitlab.com/group/project/-/merge_requests/42\",\n};\n\nconst AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"azure-devops\",\n  providerName: \"Azure DevOps\",\n  shortName: \"PR\",\n  longName: \"pull request\",\n  pluralLongName: \"pull requests\",\n  providerLongName: \"Azure DevOps pull request\",\n  checkoutCommandExample: \"az repos pr checkout --id 123\",\n  urlExample: \"https://dev.azure.com/org/project/_git/repo/pullrequest/42\",\n};\n\nconst BITBUCKET_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"bitbucket\",\n  providerName: \"Bitbucket\",\n  shortName: \"PR\",\n  longName: \"pull request\",\n  pluralLongName: \"pull requests\",\n  providerLongName: \"Bitbucket pull request\",\n  urlExample: \"https://bitbucket.org/workspace/repo/pull-requests/42\",\n};\n\nconst GENERIC_CHANGE_REQUEST_PRESENTATION: ChangeRequestPresentation = {\n  icon: \"change-request\",\n  providerName: \"source control\",\n  shortName: \"change request\",\n  longName: \"change request\",\n  pluralLongName: \"change requests\",\n  providerLongName: \"change request\",\n  urlExample: \"#42\",\n};\n\nexport function resolveChangeRequestPresentation(\n  provider: SourceControlProviderInfo | null | undefined,\n): ChangeRequestPresentation {\n  switch (provider?.kind) {\n    case \"github\":\n    case undefined:\n      return GITHUB_CHANGE_REQUEST_PRESENTATION;\n    case \"gitlab\":\n      return GITLAB_CHANGE_REQUEST_PRESENTATION;\n    case \"azure-devops\":\n      return AZURE_DEVOPS_CHANGE_REQUEST_PRESENTATION;\n    case \"bitbucket\":\n      return BITBUCKET_CHANGE_REQUEST_PRESENTATION;\n    case \"unknown\":\n      return GENERIC_CHANGE_REQUEST_PRESENTATION;\n  }\n}\n\nexport function resolveChangeRequestPresentationForKind(\n  kind: SourceControlProviderKind,\n): ChangeRequestPresentation {\n  return resolveChangeRequestPresentation({ kind, name: \"\", baseUrl: \"\" });\n}\n\nexport function formatChangeRequestAction(\n  verb: \"View\" | \"Create\",\n  presentation: ChangeRequestPresentation,\n): string {\n  return `${verb} ${presentation.shortName}`;\n}\n\nexport function formatCreateChangeRequestPhrase(presentation: ChangeRequestPresentation): string {\n  return `create ${presentation.shortName}`;\n}\n\nexport function getChangeRequestTerminology(\n  provider: SourceControlProviderInfo | null | undefined,\n): ChangeRequestTerminology {\n  if (!provider) {\n    return DEFAULT_CHANGE_REQUEST_TERMINOLOGY;\n  }\n\n  const presentation = resolveChangeRequestPresentation(provider);\n  return {\n    shortLabel: presentation.shortName,\n    singular: presentation.longName,\n  };\n}\n\nexport function getChangeRequestTerminologyForKind(\n  kind: SourceControlProviderKind,\n): ChangeRequestTerminology {\n  const presentation = resolveChangeRequestPresentationForKind(kind);\n  return {\n    shortLabel: presentation.shortName,\n    singular: presentation.longName,\n  };\n}\n\nfunction parseRemoteHost(remoteUrl: string): string | null {\n  const trimmed = remoteUrl.trim();\n  if (trimmed.length === 0) {\n    return null;\n  }\n\n  if (trimmed.startsWith(\"git@\")) {\n    const hostWithPath = trimmed.slice(\"git@\".length);\n    const separatorIndex = hostWithPath.search(/[:/]/);\n    if (separatorIndex <= 0) {\n      return null;\n    }\n    return hostWithPath.slice(0, separatorIndex).toLowerCase();\n  }\n\n  try {\n    return new URL(trimmed).host.toLowerCase();\n  } catch {\n    return null;\n  }\n}\n\nfunction parseHostName(host: string): string {\n  try {\n    return new URL(`https://${host}`).hostname.toLowerCase();\n  } catch {\n    return host.replace(/:\\d+$/u, \"\").toLowerCase();\n  }\n}\n\nfunction toBaseUrl(host: string): string {\n  return `https://${host}`;\n}\n\nfunction isGitHubHost(host: string): boolean {\n  return host === \"github.com\" || host.includes(\"github\");\n}\n\nfunction isGitLabHost(host: string): boolean {\n  return host === \"gitlab.com\" || host.includes(\"gitlab\");\n}\n\nfunction isAzureDevOpsHost(host: string): boolean {\n  return host === \"dev.azure.com\" || host.endsWith(\".visualstudio.com\");\n}\n\nfunction isBitbucketHost(host: string): boolean {\n  return host === \"bitbucket.org\" || host.includes(\"bitbucket\");\n}\n\nexport function detectSourceControlProviderFromRemoteUrl(\n  remoteUrl: string,\n): SourceControlProviderInfo | null {\n  const host = parseRemoteHost(remoteUrl);\n  if (!host) {\n    return null;\n  }\n  const hostname = parseHostName(host);\n\n  if (isGitHubHost(hostname)) {\n    return {\n      kind: \"github\",\n      name: hostname === \"github.com\" ? \"GitHub\" : \"GitHub Self-Hosted\",\n      baseUrl: toBaseUrl(host),\n    };\n  }\n\n  if (isGitLabHost(hostname)) {\n    return {\n      kind: \"gitlab\",\n      name: hostname === \"gitlab.com\" ? \"GitLab\" : \"GitLab Self-Hosted\",\n      baseUrl: toBaseUrl(host),\n    };\n  }\n\n  if (isAzureDevOpsHost(hostname)) {\n    return {\n      kind: \"azure-devops\",\n      name: \"Azure DevOps\",\n      baseUrl: toBaseUrl(host),\n    };\n  }\n\n  if (isBitbucketHost(hostname)) {\n    return {\n      kind: \"bitbucket\",\n      name: hostname === \"bitbucket.org\" ? \"Bitbucket\" : \"Bitbucket Self-Hosted\",\n      baseUrl: toBaseUrl(host),\n    };\n  }\n\n  return {\n    kind: \"unknown\",\n    name: host,\n    baseUrl: toBaseUrl(host),\n  };\n}\n","import type {\n  VcsRef,\n  SourceControlProviderInfo,\n  VcsStatusLocalResult,\n  VcsStatusRemoteResult,\n  VcsStatusResult,\n  VcsStatusStreamEvent,\n} from \"@t3tools/contracts\";\nimport * as Arr from \"effect/Array\";\nimport * as Result from \"effect/Result\";\nimport { detectSourceControlProviderFromRemoteUrl } from \"./sourceControl.ts\";\n\nexport const WORKTREE_BRANCH_PREFIX = \"synaptic\";\n// Canonical form is `synaptic/<8 hex>`. Older mobile builds generated `<prefix>/<uuid>`\n// via Crypto.randomUUID() (always RFC 4122 v4), so the matcher also accepts exactly\n// that shape — version nibble `4`, variant nibble `[89ab]` — to keep those threads\n// eligible for branch regeneration without loosening beyond what was ever generated.\nconst TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(\n  `^${WORKTREE_BRANCH_PREFIX}\\\\/(?:[0-9a-f]{8}|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$`,\n);\n\n/**\n * Sanitize an arbitrary string into a valid, lowercase git refName fragment.\n * Strips quotes, collapses separators, limits to 64 chars.\n */\nexport function sanitizeBranchFragment(raw: string): string {\n  const normalized = raw\n    .trim()\n    .toLowerCase()\n    .replace(/['\"`]/g, \"\")\n    .replace(/^[./\\s_-]+|[./\\s_-]+$/g, \"\");\n\n  const branchFragment = normalized\n    .replace(/[^a-z0-9/_-]+/g, \"-\")\n    .replace(/\\/+/g, \"/\")\n    .replace(/-+/g, \"-\")\n    .replace(/^[./_-]+|[./_-]+$/g, \"\")\n    .slice(0, 64)\n    .replace(/[./_-]+$/g, \"\");\n\n  return branchFragment.length > 0 ? branchFragment : \"update\";\n}\n\n/**\n * Sanitize a string into a `feature/…` refName name.\n * Preserves an existing `feature/` prefix or slash-separated namespace.\n */\nexport function sanitizeFeatureBranchName(raw: string): string {\n  const sanitized = sanitizeBranchFragment(raw);\n  if (sanitized.includes(\"/\")) {\n    return sanitized.startsWith(\"feature/\") ? sanitized : `feature/${sanitized}`;\n  }\n  return `feature/${sanitized}`;\n}\n\nconst AUTO_FEATURE_BRANCH_FALLBACK = \"feature/update\";\n\n/**\n * Resolve a unique `feature/…` refName name that doesn't collide with\n * any existing refName. Appends a numeric suffix when needed.\n */\nexport function resolveAutoFeatureBranchName(\n  existingBranchNames: readonly string[],\n  preferredBranch?: string,\n): string {\n  const preferred = preferredBranch?.trim();\n  const resolvedBase = sanitizeFeatureBranchName(\n    preferred && preferred.length > 0 ? preferred : AUTO_FEATURE_BRANCH_FALLBACK,\n  );\n  const existingNames = new Set(existingBranchNames.map((refName) => refName.toLowerCase()));\n\n  if (!existingNames.has(resolvedBase)) {\n    return resolvedBase;\n  }\n\n  let suffix = 2;\n  while (existingNames.has(`${resolvedBase}-${suffix}`)) {\n    suffix += 1;\n  }\n\n  return `${resolvedBase}-${suffix}`;\n}\n\n/**\n * Strip the remote prefix from a remote ref such as `origin/feature/demo`.\n */\nexport function deriveLocalBranchNameFromRemoteRef(branchName: string): string {\n  const firstSeparatorIndex = branchName.indexOf(\"/\");\n  if (firstSeparatorIndex <= 0 || firstSeparatorIndex === branchName.length - 1) {\n    return branchName;\n  }\n  return branchName.slice(firstSeparatorIndex + 1);\n}\n\nexport function buildTemporaryWorktreeBranchName(\n  randomHex: (byteLength: number) => string,\n): string {\n  // Normalize to exactly 8 lowercase hex chars so a UUID-shaped callback\n  // still produces the canonical temporary branch form.\n  const token = randomHex(4)\n    .toLowerCase()\n    .replace(/[^0-9a-f]/g, \"\")\n    .slice(0, 8);\n  return `${WORKTREE_BRANCH_PREFIX}/${token}`;\n}\n\nexport function isTemporaryWorktreeBranch(refName: string): boolean {\n  return TEMP_WORKTREE_BRANCH_PATTERN.test(refName.trim().toLowerCase());\n}\n\n/**\n * Normalize a git remote URL into a stable comparison key.\n */\nexport function normalizeGitRemoteUrl(value: string): string {\n  const normalized = value\n    .trim()\n    .replace(/\\/+$/g, \"\")\n    .replace(/\\.git$/i, \"\")\n    .toLowerCase();\n\n  if (/^(?:ssh|https?|git):\\/\\//i.test(normalized)) {\n    try {\n      const url = new URL(normalized);\n      const repositoryPath = url.pathname\n        .split(\"/\")\n        .filter((segment) => segment.length > 0)\n        .join(\"/\");\n      if (url.hostname && repositoryPath.includes(\"/\")) {\n        return `${url.hostname}/${repositoryPath}`;\n      }\n    } catch {\n      return normalized;\n    }\n  }\n\n  const scpStyleHostAndPath = /^git@([^:/\\s]+)[:/]([^/\\s]+(?:\\/[^/\\s]+)+)$/i.exec(normalized);\n  if (scpStyleHostAndPath?.[1] && scpStyleHostAndPath[2]) {\n    return `${scpStyleHostAndPath[1]}/${scpStyleHostAndPath[2]}`;\n  }\n\n  return normalized;\n}\n\n/**\n * Best-effort parse of a GitHub `owner/repo` identifier from common remote URL shapes.\n */\nexport function parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {\n  const trimmed = url?.trim() ?? \"\";\n  if (trimmed.length === 0) {\n    return null;\n  }\n\n  const match =\n    /^(?:git@github\\.com:|ssh:\\/\\/git@github\\.com\\/|https:\\/\\/github\\.com\\/|git:\\/\\/github\\.com\\/)([^/\\s]+\\/[^/\\s]+?)(?:\\.git)?\\/?$/i.exec(\n      trimmed,\n    );\n  const repositoryNameWithOwner = match?.[1]?.trim() ?? \"\";\n  return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;\n}\n\nfunction deriveLocalBranchNameCandidatesFromRemoteRef(\n  branchName: string,\n  remoteName?: string,\n): ReadonlyArray<string> {\n  const candidates = new Set<string>();\n  const firstSlashCandidate = deriveLocalBranchNameFromRemoteRef(branchName);\n  if (firstSlashCandidate.length > 0) {\n    candidates.add(firstSlashCandidate);\n  }\n\n  if (remoteName) {\n    const remotePrefix = `${remoteName}/`;\n    if (branchName.startsWith(remotePrefix) && branchName.length > remotePrefix.length) {\n      candidates.add(branchName.slice(remotePrefix.length));\n    }\n  }\n\n  return [...candidates];\n}\n\n/**\n * Hide `origin/*` remote refs when a matching local refName already exists.\n */\nexport function dedupeRemoteBranchesWithLocalMatches(\n  refs: ReadonlyArray<VcsRef>,\n): ReadonlyArray<VcsRef> {\n  const localBranchNames = new Set(\n    Arr.filterMap(refs, (refName) =>\n      refName.isRemote ? Result.failVoid : Result.succeed(refName.name),\n    ),\n  );\n\n  return refs.filter((refName) => {\n    if (!refName.isRemote) {\n      return true;\n    }\n\n    if (refName.remoteName !== \"origin\") {\n      return true;\n    }\n\n    const localBranchCandidates = deriveLocalBranchNameCandidatesFromRemoteRef(\n      refName.name,\n      refName.remoteName,\n    );\n    return !localBranchCandidates.some((candidate) => localBranchNames.has(candidate));\n  });\n}\n\nexport function detectSourceControlProviderFromGitRemoteUrl(\n  remoteUrl: string,\n): SourceControlProviderInfo | null {\n  return detectSourceControlProviderFromRemoteUrl(remoteUrl);\n}\n\nconst EMPTY_GIT_STATUS_REMOTE: VcsStatusRemoteResult = {\n  hasUpstream: false,\n  aheadCount: 0,\n  behindCount: 0,\n  aheadOfDefaultCount: 0,\n  pr: null,\n};\n\nexport function mergeGitStatusParts(\n  local: VcsStatusLocalResult,\n  remote: VcsStatusRemoteResult | null,\n): VcsStatusResult {\n  return {\n    ...local,\n    ...(remote ?? EMPTY_GIT_STATUS_REMOTE),\n  };\n}\n\nfunction toRemoteStatusPart(status: VcsStatusResult): VcsStatusRemoteResult {\n  return {\n    hasUpstream: status.hasUpstream,\n    aheadCount: status.aheadCount,\n    behindCount: status.behindCount,\n    ...(status.aheadOfDefaultCount === undefined\n      ? {}\n      : { aheadOfDefaultCount: status.aheadOfDefaultCount }),\n    pr: status.pr,\n  };\n}\n\nfunction toLocalStatusPart(status: VcsStatusResult): VcsStatusLocalResult {\n  return {\n    isRepo: status.isRepo,\n    ...(status.sourceControlProvider\n      ? { sourceControlProvider: status.sourceControlProvider }\n      : {}),\n    hasPrimaryRemote: status.hasPrimaryRemote,\n    isDefaultRef: status.isDefaultRef,\n    refName: status.refName,\n    hasWorkingTreeChanges: status.hasWorkingTreeChanges,\n    workingTree: status.workingTree,\n  };\n}\n\nexport function applyGitStatusStreamEvent(\n  current: VcsStatusResult | null,\n  event: VcsStatusStreamEvent,\n): VcsStatusResult {\n  switch (event._tag) {\n    case \"snapshot\":\n      return mergeGitStatusParts(event.local, event.remote);\n    case \"localUpdated\":\n      return mergeGitStatusParts(event.local, current ? toRemoteStatusPart(current) : null);\n    case \"remoteUpdated\":\n      if (current === null) {\n        return mergeGitStatusParts(\n          {\n            isRepo: true,\n            hasPrimaryRemote: false,\n            isDefaultRef: false,\n            refName: null,\n            hasWorkingTreeChanges: false,\n            workingTree: { files: [], insertions: 0, deletions: 0 },\n          },\n          event.remote,\n        );\n      }\n      return mergeGitStatusParts(toLocalStatusPart(current), event.remote);\n  }\n}\n","import * as Effect from \"effect/Effect\";\nimport * as Stream from \"effect/Stream\";\n\nexport interface CollectedUint8StreamText {\n  readonly text: string;\n  readonly truncated: boolean;\n  readonly bytes: number;\n}\n\ninterface CollectState {\n  chunks: Uint8Array[];\n  readonly bytes: number;\n  readonly truncated: boolean;\n}\n\nexport const collectUint8StreamText = <E>(input: {\n  readonly stream: Stream.Stream<Uint8Array, E>;\n  readonly maxBytes?: number | undefined;\n  readonly truncatedMarker?: string | null | undefined;\n}): Effect.Effect<CollectedUint8StreamText, E> => {\n  const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;\n  const truncatedMarker = input.truncatedMarker ?? \"\";\n\n  return input.stream.pipe(\n    Stream.runFold(\n      (): CollectState => ({\n        chunks: [],\n        bytes: 0,\n        truncated: false,\n      }),\n      (state, chunk): CollectState => {\n        /*\n         * keep draining after truncation so the child process can exit normally.\n         * its a know issue that on windows killing after the output cap can force an expensive taskkill operation and hurt performance\n         */\n        if (state.truncated) {\n          return state;\n        }\n\n        const remainingBytes = maxBytes - state.bytes;\n        if (remainingBytes <= 0) {\n          return {\n            ...state,\n            truncated: true,\n          };\n        }\n\n        const nextChunk =\n          chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;\n        state.chunks.push(nextChunk);\n        const bytes = state.bytes + nextChunk.byteLength;\n        const truncated = chunk.byteLength > remainingBytes;\n\n        return {\n          chunks: state.chunks,\n          bytes,\n          truncated,\n        };\n      },\n    ),\n    Effect.map((state): CollectedUint8StreamText => {\n      const text = Buffer.concat(state.chunks, state.bytes).toString(\"utf8\");\n      return {\n        text: state.truncated && truncatedMarker.length > 0 ? `${text}${truncatedMarker}` : text,\n        bytes: state.bytes,\n        truncated: state.truncated,\n      };\n    }),\n  );\n};\n","import * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport {\n  collectUint8StreamText,\n  type CollectedUint8StreamText,\n} from \"./stream/collectUint8StreamText.ts\";\n\nexport interface ProcessRunInput {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly cwd?: string | undefined;\n  readonly spawnCwd?: string | undefined;\n  readonly timeout?: Duration.Input | undefined;\n  readonly env?: NodeJS.ProcessEnv | undefined;\n  readonly stdin?: string | undefined;\n  readonly maxOutputBytes?: number | undefined;\n  readonly outputMode?: \"error\" | \"truncate\" | undefined;\n  readonly truncatedMarker?: string | undefined;\n  /**\n   * On timeout, return a synthetic timedOut result.\n   * Partial stdout/stderr are not preserved.\n   */\n  readonly timeoutBehavior?: \"error\" | \"timedOutResult\" | undefined;\n}\n\nexport interface ProcessRunOutput {\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly code: ChildProcessSpawner.ExitCode | null;\n  readonly timedOut: boolean;\n  readonly stdoutTruncated: boolean;\n  readonly stderrTruncated: boolean;\n}\n\nconst ProcessInvocationFields = {\n  command: Schema.String,\n  argumentCount: Schema.Number,\n  cwd: Schema.optional(Schema.String),\n  spawnCwd: Schema.optional(Schema.String),\n};\n\nconst formatProcessInvocation = (input: {\n  readonly command: string;\n  readonly cwd?: string | undefined;\n  readonly spawnCwd?: string | undefined;\n}): string => {\n  const executionCwd = input.spawnCwd ?? input.cwd;\n  return executionCwd === undefined\n    ? `'${input.command}'`\n    : `'${input.command}' in '${executionCwd}'`;\n};\n\nexport class ProcessSpawnError extends Schema.TaggedErrorClass<ProcessSpawnError>()(\n  \"ProcessSpawnError\",\n  {\n    ...ProcessInvocationFields,\n    resolvedCommand: Schema.optional(Schema.String),\n    resolvedArgumentCount: Schema.optional(Schema.Number),\n    shell: Schema.optional(Schema.Boolean),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to spawn process ${formatProcessInvocation(this)}`;\n  }\n}\n\nexport class ProcessStdinError extends Schema.TaggedErrorClass<ProcessStdinError>()(\n  \"ProcessStdinError\",\n  {\n    ...ProcessInvocationFields,\n    stdinBytes: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to write stdin for process ${formatProcessInvocation(this)}`;\n  }\n}\n\nexport class ProcessOutputLimitError extends Schema.TaggedErrorClass<ProcessOutputLimitError>()(\n  \"ProcessOutputLimitError\",\n  {\n    ...ProcessInvocationFields,\n    stream: Schema.Literals([\"stdout\", \"stderr\"]),\n    maxBytes: Schema.Number,\n    observedBytes: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Process ${formatProcessInvocation(this)} ${this.stream} produced ${this.observedBytes} bytes, exceeding the ${this.maxBytes} byte limit`;\n  }\n}\n\nexport class ProcessReadError extends Schema.TaggedErrorClass<ProcessReadError>()(\n  \"ProcessReadError\",\n  {\n    ...ProcessInvocationFields,\n    stream: Schema.Literals([\"stdout\", \"stderr\", \"exitCode\"]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to read ${this.stream} for process ${formatProcessInvocation(this)}`;\n  }\n}\n\nexport class ProcessTimeoutError extends Schema.TaggedErrorClass<ProcessTimeoutError>()(\n  \"ProcessTimeoutError\",\n  {\n    ...ProcessInvocationFields,\n    timeoutMs: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Process ${formatProcessInvocation(this)} timed out after ${this.timeoutMs}ms`;\n  }\n}\n\nexport const ProcessRunError = Schema.Union([\n  ProcessSpawnError,\n  ProcessStdinError,\n  ProcessOutputLimitError,\n  ProcessReadError,\n  ProcessTimeoutError,\n]);\nexport type ProcessRunError = typeof ProcessRunError.Type;\n\nexport class ProcessRunner extends Context.Service<\n  ProcessRunner,\n  {\n    readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;\n  }\n>()(\"t3/processRunner\") {}\n\nconst DEFAULT_TIMEOUT = \"60 seconds\";\nconst DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;\n\nconst WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [\n  /is not recognized as an internal or external command/i,\n  /n.o . reconhecido como um comando interno/i,\n  /non . riconosciuto come comando interno o esterno/i,\n  /n.est pas reconnu en tant que commande interne/i,\n  /no se reconoce como un comando interno o externo/i,\n  /wird nicht als interner oder externer befehl/i,\n] as const;\n\nfunction hasWindowsCommandNotFoundMessage(output: string): boolean {\n  return WINDOWS_COMMAND_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(output));\n}\n\nexport const isWindowsCommandNotFound = Effect.fn(\"processRunner.isWindowsCommandNotFound\")(\n  function* (code: number | null, stderr: string) {\n    const platform = yield* HostProcessPlatform;\n    if (platform !== \"win32\") return false;\n    if (code === 9009) return true;\n    return hasWindowsCommandNotFoundMessage(stderr);\n  },\n);\n\nconst collectText = Effect.fn(\"processRunner.collectText\")(function* (input: {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly cwd?: string | undefined;\n  readonly spawnCwd?: string | undefined;\n  readonly streamName: \"stdout\" | \"stderr\";\n  readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;\n  readonly maxOutputBytes: number;\n  readonly outputMode: \"error\" | \"truncate\";\n  readonly truncatedMarker: string;\n}) {\n  const stream = input.stream.pipe(\n    Stream.mapError(\n      (cause) =>\n        new ProcessReadError({\n          command: input.command,\n          argumentCount: input.args.length,\n          cwd: input.cwd,\n          spawnCwd: input.spawnCwd,\n          stream: input.streamName,\n          cause,\n        }),\n    ),\n  );\n\n  if (input.outputMode === \"truncate\") {\n    return yield* collectUint8StreamText({\n      stream,\n      maxBytes: input.maxOutputBytes,\n      truncatedMarker: input.truncatedMarker,\n    });\n  }\n\n  return yield* stream.pipe(\n    Stream.runFoldEffect<\n      {\n        readonly chunks: Uint8Array<ArrayBufferLike>[];\n        readonly bytes: number;\n      },\n      Uint8Array<ArrayBufferLike>,\n      ProcessOutputLimitError | ProcessReadError,\n      never\n    >(\n      () => ({ chunks: [], bytes: 0 }),\n      (state, chunk) => {\n        const remainingBytes = input.maxOutputBytes - state.bytes;\n        if (chunk.byteLength > remainingBytes) {\n          return Effect.fail(\n            new ProcessOutputLimitError({\n              command: input.command,\n              argumentCount: input.args.length,\n              cwd: input.cwd,\n              spawnCwd: input.spawnCwd,\n              stream: input.streamName,\n              maxBytes: input.maxOutputBytes,\n              observedBytes: state.bytes + chunk.byteLength,\n            }),\n          );\n        }\n\n        state.chunks.push(chunk);\n        return Effect.succeed({\n          chunks: state.chunks,\n          bytes: state.bytes + chunk.byteLength,\n        });\n      },\n    ),\n    Effect.map(\n      (state): CollectedUint8StreamText => ({\n        text: Buffer.concat(state.chunks, state.bytes).toString(\"utf8\"),\n        bytes: state.bytes,\n        truncated: false,\n      }),\n    ),\n  );\n});\n\nfunction finalizeRunProcess<R>(\n  effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,\n  input: ProcessRunInput,\n): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {\n  const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);\n  const timeoutBehavior = input.timeoutBehavior ?? \"error\";\n\n  return effect.pipe(\n    Effect.scoped,\n    Effect.timeoutOption(timeout),\n    Effect.flatMap((result) => {\n      if (Option.isSome(result)) {\n        return Effect.succeed(result.value);\n      }\n      if (timeoutBehavior === \"timedOutResult\") {\n        return Effect.succeed({\n          stdout: \"\",\n          stderr: \"\",\n          code: null,\n          timedOut: true,\n          stdoutTruncated: false,\n          stderrTruncated: false,\n        } satisfies ProcessRunOutput);\n      }\n      return Effect.fail(\n        new ProcessTimeoutError({\n          command: input.command,\n          argumentCount: input.args.length,\n          cwd: input.cwd,\n          spawnCwd: input.spawnCwd,\n          timeoutMs: Duration.toMillis(timeout),\n        }),\n      );\n    }),\n  );\n}\n\nconst runProcessCore = Effect.fn(\"processRunner.runProcessCore\")(function* (\n  spawner: ChildProcessSpawner.ChildProcessSpawner[\"Service\"],\n  input: ProcessRunInput,\n): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {\n  const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n  const outputMode = input.outputMode ?? \"error\";\n  const truncatedMarker = input.truncatedMarker ?? \"\";\n  const extendEnv = input.env !== undefined;\n  const spawnCommand = yield* resolveSpawnCommand(\n    input.command,\n    input.args,\n    input.env === undefined ? {} : { env: input.env, extendEnv },\n  );\n\n  const child = yield* spawner\n    .spawn(\n      ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        ...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),\n        ...(input.env !== undefined\n          ? {\n              env: input.env,\n              extendEnv,\n            }\n          : {}),\n        shell: spawnCommand.shell,\n      }),\n    )\n    .pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProcessSpawnError({\n            command: input.command,\n            argumentCount: input.args.length,\n            cwd: input.cwd,\n            spawnCwd: input.spawnCwd,\n            resolvedCommand: spawnCommand.command,\n            resolvedArgumentCount: spawnCommand.args.length,\n            shell: spawnCommand.shell,\n            cause,\n          }),\n      ),\n    );\n\n  const stdin = input.stdin;\n  const writeStdin =\n    stdin === undefined\n      ? Effect.void\n      : Stream.run(Stream.encodeText(Stream.make(stdin)), child.stdin).pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProcessStdinError({\n                command: input.command,\n                argumentCount: input.args.length,\n                cwd: input.cwd,\n                spawnCwd: input.spawnCwd,\n                stdinBytes: Buffer.byteLength(stdin),\n                cause,\n              }),\n          ),\n        );\n\n  const [stdout, stderr] = yield* Effect.all(\n    [\n      collectText({\n        command: input.command,\n        args: input.args,\n        cwd: input.cwd,\n        spawnCwd: input.spawnCwd,\n        streamName: \"stdout\",\n        stream: child.stdout,\n        maxOutputBytes,\n        outputMode,\n        truncatedMarker,\n      }),\n      collectText({\n        command: input.command,\n        args: input.args,\n        cwd: input.cwd,\n        spawnCwd: input.spawnCwd,\n        streamName: \"stderr\",\n        stream: child.stderr,\n        maxOutputBytes,\n        outputMode,\n        truncatedMarker,\n      }),\n      writeStdin,\n    ],\n    { concurrency: \"unbounded\" },\n  );\n\n  const exitCode = yield* child.exitCode.pipe(\n    Effect.mapError(\n      (cause) =>\n        new ProcessReadError({\n          command: input.command,\n          argumentCount: input.args.length,\n          cwd: input.cwd,\n          spawnCwd: input.spawnCwd,\n          stream: \"exitCode\",\n          cause,\n        }),\n    ),\n  );\n\n  return {\n    stdout: stdout.text,\n    stderr: stderr.text,\n    code: exitCode,\n    timedOut: false,\n    stdoutTruncated: stdout.truncated,\n    stderrTruncated: stderr.truncated,\n  } satisfies ProcessRunOutput;\n});\n\nexport const make = Effect.fn(\"ProcessRunner.make\")(function* () {\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\n  const run: ProcessRunner[\"Service\"][\"run\"] = (input) =>\n    finalizeRunProcess(runProcessCore(spawner, input), input);\n\n  return ProcessRunner.of({\n    run,\n  });\n});\n\nexport const layer = Layer.effect(ProcessRunner, make());\n","import type { RepositoryIdentity } from \"@t3tools/contracts\";\nimport {\n  detectSourceControlProviderFromGitRemoteUrl,\n  normalizeGitRemoteUrl,\n} from \"@t3tools/shared/git\";\nimport * as Cache from \"effect/Cache\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\n\nimport * as ProcessRunner from \"../processRunner.ts\";\n\nconst DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY = 512;\nconst DEFAULT_POSITIVE_CACHE_TTL = Duration.minutes(1);\nconst DEFAULT_NEGATIVE_CACHE_TTL = Duration.minutes(1);\n\nexport interface RepositoryIdentityResolverOptions {\n  readonly cacheCapacity?: number;\n  readonly positiveCacheTtl?: Duration.Input;\n  readonly negativeCacheTtl?: Duration.Input;\n}\n\nexport class RepositoryIdentityResolver extends Context.Service<\n  RepositoryIdentityResolver,\n  {\n    readonly resolve: (cwd: string) => Effect.Effect<RepositoryIdentity | null>;\n  }\n>()(\"t3/project/RepositoryIdentityResolver\") {}\n\nfunction parseRemoteFetchUrls(stdout: string): Map<string, string> {\n  const remotes = new Map<string, string>();\n  for (const line of stdout.split(\"\\n\")) {\n    const trimmed = line.trim();\n    if (trimmed.length === 0) continue;\n    const match = /^(\\S+)\\s+(\\S+)\\s+\\((fetch|push)\\)$/.exec(trimmed);\n    if (!match) continue;\n    const [, remoteName = \"\", remoteUrl = \"\", direction = \"\"] = match;\n    if (direction !== \"fetch\" || remoteName.length === 0 || remoteUrl.length === 0) {\n      continue;\n    }\n    remotes.set(remoteName, remoteUrl);\n  }\n  return remotes;\n}\n\nfunction pickPrimaryRemote(\n  remotes: ReadonlyMap<string, string>,\n): { readonly remoteName: string; readonly remoteUrl: string } | null {\n  for (const preferredRemoteName of [\"upstream\", \"origin\"] as const) {\n    const remoteUrl = remotes.get(preferredRemoteName);\n    if (remoteUrl) {\n      return { remoteName: preferredRemoteName, remoteUrl };\n    }\n  }\n\n  const [remoteName, remoteUrl] =\n    [...remotes.entries()].toSorted(([left], [right]) => left.localeCompare(right))[0] ?? [];\n  return remoteName && remoteUrl ? { remoteName, remoteUrl } : null;\n}\n\nfunction buildRepositoryIdentity(input: {\n  readonly remoteName: string;\n  readonly remoteUrl: string;\n  readonly rootPath: string;\n}): RepositoryIdentity {\n  const canonicalKey = normalizeGitRemoteUrl(input.remoteUrl);\n  const sourceControlProvider = detectSourceControlProviderFromGitRemoteUrl(input.remoteUrl);\n  const repositoryPath = canonicalKey.split(\"/\").slice(1).join(\"/\");\n  const repositoryPathSegments = repositoryPath.split(\"/\").filter((segment) => segment.length > 0);\n  const [owner] = repositoryPathSegments;\n  const repositoryName = repositoryPathSegments.at(-1);\n\n  return {\n    canonicalKey,\n    locator: {\n      source: \"git-remote\",\n      remoteName: input.remoteName,\n      remoteUrl: input.remoteUrl,\n    },\n    rootPath: input.rootPath,\n    ...(repositoryPath ? { displayName: repositoryPath } : {}),\n    ...(sourceControlProvider ? { provider: sourceControlProvider.kind } : {}),\n    ...(owner ? { owner } : {}),\n    ...(repositoryName ? { name: repositoryName } : {}),\n  };\n}\n\nconst resolveRepositoryIdentityCacheKey = Effect.fn(\"RepositoryIdentityResolver.resolveCacheKey\")(\n  function* (cwd: string) {\n    const processRunner = yield* ProcessRunner.ProcessRunner;\n    let cacheKey = cwd;\n\n    // git is a real executable on every platform — no cmd.exe shell mode, which\n    // would split paths containing spaces during cmd's re-tokenization.\n    const topLevelResult = yield* processRunner\n      .run({\n        command: \"git\",\n        args: [\"-C\", cwd, \"rev-parse\", \"--show-toplevel\"],\n        timeoutBehavior: \"timedOutResult\",\n      })\n      .pipe(Effect.option);\n    if (topLevelResult._tag === \"None\" || topLevelResult.value.code !== 0) {\n      return cacheKey;\n    }\n\n    const candidate = topLevelResult.value.stdout.trim();\n    if (candidate.length > 0) {\n      cacheKey = candidate;\n    }\n\n    return cacheKey;\n  },\n);\n\nconst resolveRepositoryIdentityFromCacheKey = Effect.fn(\n  \"RepositoryIdentityResolver.resolveFromCacheKey\",\n)(function* (\n  cacheKey: string,\n): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n  const remoteResult = yield* processRunner\n    .run({\n      command: \"git\",\n      args: [\"-C\", cacheKey, \"remote\", \"-v\"],\n      timeoutBehavior: \"timedOutResult\",\n    })\n    .pipe(Effect.option);\n  if (remoteResult._tag === \"None\" || remoteResult.value.code !== 0) {\n    return null;\n  }\n\n  const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.value.stdout));\n  return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;\n});\n\nexport const make = Effect.fn(\"RepositoryIdentityResolver.make\")(function* (\n  options: RepositoryIdentityResolverOptions = {},\n) {\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n\n  const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(\n    (cacheKey) =>\n      resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(\n        Effect.provideService(ProcessRunner.ProcessRunner, processRunner),\n      ),\n    {\n      capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,\n      timeToLive: Exit.match({\n        onSuccess: (value) =>\n          value === null\n            ? (options.negativeCacheTtl ?? DEFAULT_NEGATIVE_CACHE_TTL)\n            : (options.positiveCacheTtl ?? DEFAULT_POSITIVE_CACHE_TTL),\n        onFailure: () => Duration.zero,\n      }),\n    },\n  );\n\n  const resolve: RepositoryIdentityResolver[\"Service\"][\"resolve\"] = Effect.fn(\n    \"RepositoryIdentityResolver.resolve\",\n  )(function* (cwd) {\n    const cacheKey = yield* resolveRepositoryIdentityCacheKey(cwd).pipe(\n      Effect.provideService(ProcessRunner.ProcessRunner, processRunner),\n    );\n    return yield* Cache.get(repositoryIdentityCache, cacheKey);\n  });\n\n  return RepositoryIdentityResolver.of({ resolve });\n});\n\nexport const layer = Layer.effect(RepositoryIdentityResolver, make()).pipe(\n  Layer.provide(ProcessRunner.layer),\n);\n","import {\n  ChatAttachment,\n  CheckpointRef,\n  IsoDateTime,\n  MessageId,\n  NonNegativeInt,\n  OrchestrationCheckpointFile,\n  OrchestrationProposedPlanId,\n  OrchestrationReadModel,\n  OrchestrationThreadSearchSource,\n  OrchestrationShellSnapshot,\n  OrchestrationThread,\n  OrchestrationThreadDetailSnapshot,\n  ProjectScript,\n  TurnId,\n  type OrchestrationCheckpointSummary,\n  type OrchestrationLatestTurn,\n  type OrchestrationMessage,\n  type OrchestrationProjectShell,\n  type OrchestrationProposedPlan,\n  type OrchestrationProject,\n  type OrchestrationSession,\n  type OrchestrationThreadActivity,\n  type OrchestrationThreadShell,\n  ModelSelection,\n  ProjectId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Arr from \"effect/Array\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport {\n  isPersistenceError,\n  toPersistenceDecodeError,\n  toPersistenceSqlError,\n  type ProjectionRepositoryError,\n} from \"../../persistence/Errors.ts\";\nimport { ProjectionCheckpoint } from \"../../persistence/Services/ProjectionCheckpoints.ts\";\nimport { ThreadBackgroundLivenessService } from \"../ThreadBackgroundLiveness.ts\";\nimport { ThreadPlanProgressService } from \"../ThreadPlanProgress.ts\";\nimport { ProjectionProject } from \"../../persistence/Services/ProjectionProjects.ts\";\nimport { ProjectionState } from \"../../persistence/Services/ProjectionState.ts\";\nimport { ProjectionThreadActivity } from \"../../persistence/Services/ProjectionThreadActivities.ts\";\nimport { ProjectionThreadMessage } from \"../../persistence/Services/ProjectionThreadMessages.ts\";\nimport { ProjectionThreadProposedPlan } from \"../../persistence/Services/ProjectionThreadProposedPlans.ts\";\nimport { ProjectionThreadSession } from \"../../persistence/Services/ProjectionThreadSessions.ts\";\nimport { ProjectionThread } from \"../../persistence/Services/ProjectionThreads.ts\";\nimport {\n  decodeThreadDetailPageCursor,\n  encodeThreadDetailPageCursor,\n} from \"../threadDetailCursor.ts\";\nimport * as RepositoryIdentityResolver from \"../../project/RepositoryIdentityResolver.ts\";\nimport { ORCHESTRATION_PROJECTOR_NAMES } from \"./ProjectionPipeline.ts\";\nimport {\n  ProjectionSnapshotQuery,\n  type ProjectionFullThreadDiffContext,\n  type ProjectionSnapshotCounts,\n  type ProjectionThreadCheckpointContext,\n  type ProjectionSnapshotQueryShape,\n} from \"../Services/ProjectionSnapshotQuery.ts\";\n\nconst decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);\nconst decodeShellSnapshot = Schema.decodeUnknownEffect(OrchestrationShellSnapshot);\nconst decodeThread = Schema.decodeUnknownEffect(OrchestrationThread);\nconst ProjectionProjectDbRowSchema = ProjectionProject.mapFields(\n  Struct.assign({\n    defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),\n    scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),\n  }),\n);\nconst ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(\n  Struct.assign({\n    isStreaming: Schema.Number,\n    attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),\n  }),\n);\nconst ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;\nconst ProjectionThreadDbRowSchema = ProjectionThread.mapFields(\n  Struct.assign({\n    modelSelection: Schema.fromJsonString(ModelSelection),\n  }),\n);\nconst ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(\n  Struct.assign({\n    payload: Schema.fromJsonString(Schema.Unknown),\n    sequence: Schema.NullOr(NonNegativeInt),\n  }),\n);\nconst ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;\nconst ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(\n  Struct.assign({\n    files: Schema.fromJsonString(Schema.Array(OrchestrationCheckpointFile)),\n  }),\n);\nconst ProjectionLatestTurnDbRowSchema = Schema.Struct({\n  threadId: ProjectionThread.fields.threadId,\n  turnId: TurnId,\n  state: Schema.String,\n  requestedAt: IsoDateTime,\n  startedAt: Schema.NullOr(IsoDateTime),\n  completedAt: Schema.NullOr(IsoDateTime),\n  assistantMessageId: Schema.NullOr(MessageId),\n  sourceProposedPlanThreadId: Schema.NullOr(ThreadId),\n  sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),\n});\nconst ProjectionStateDbRowSchema = ProjectionState;\nconst ProjectionCountsRowSchema = Schema.Struct({\n  projectCount: Schema.Number,\n  threadCount: Schema.Number,\n});\nconst ProjectionThreadSearchRequest = Schema.Struct({\n  pattern: Schema.String,\n  limit: Schema.Int,\n});\nconst ProjectionThreadSearchRow = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  source: OrchestrationThreadSearchSource,\n  matchText: Schema.String,\n  messageCreatedAt: Schema.NullOr(IsoDateTime),\n});\nconst WorkspaceRootLookupInput = Schema.Struct({\n  workspaceRoot: Schema.String,\n});\nconst ProjectIdLookupInput = Schema.Struct({\n  projectId: ProjectId,\n});\nconst ThreadIdLookupInput = Schema.Struct({\n  threadId: ThreadId,\n});\n// Windowed reads order turns by the stable keyset (anchor, turn key), where\n// anchor is requested_at and turn key is\n// COALESCE(turn_id, ''). Both are event-derived, so cursors survive the\n// revert projector's row-id rewrite and full projection rebuilds.\nconst ThreadTurnWindowLookupInput = Schema.Struct({\n  threadId: ThreadId,\n  // Exclusive keyset upper bound. Sentinels \"~\"/\"\" mean unbounded (\"~\" sorts\n  // after every ISO timestamp).\n  beforeAnchorAt: Schema.String,\n  beforeTurnKey: Schema.String,\n  userTurnLimit: Schema.Number,\n  maxRawTurns: Schema.Number,\n});\nconst ProjectionTurnWindowRowSchema = Schema.Struct({\n  // The turn's timeline anchor, used to bound rows that have no turn linkage\n  // (user messages and turnless activities) to the same page window.\n  anchorAt: Schema.String,\n  turnKey: Schema.String,\n});\nconst ThreadTurnRangeLookupInput = Schema.Struct({\n  threadId: ThreadId,\n  // Turn-linked rows are bounded by the keyset range [min, before) over\n  // (anchor, turn key); turnless rows by the matching [minAnchorAt,\n  // beforeAnchorAt) time range. Unbounded ends use sentinels: \"\" for the\n  // lower bound, \"~\" (sorts after ISO dates) for the upper bound.\n  minAnchorAt: Schema.String,\n  minTurnKey: Schema.String,\n  beforeAnchorAt: Schema.String,\n  beforeTurnKey: Schema.String,\n});\nconst ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;\nconst ProjectionThreadIdLookupRowSchema = Schema.Struct({\n  threadId: ThreadId,\n});\nconst ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  workspaceRoot: Schema.String,\n  worktreePath: Schema.NullOr(Schema.String),\n});\nconst FullThreadDiffContextLookupInput = Schema.Struct({\n  threadId: ThreadId,\n  checkpointTurnCount: NonNegativeInt,\n});\nconst ProjectionFullThreadDiffContextRowSchema = Schema.Struct({\n  threadId: ThreadId,\n  projectId: ProjectId,\n  workspaceRoot: Schema.String,\n  worktreePath: Schema.NullOr(Schema.String),\n  latestCheckpointTurnCount: Schema.NullOr(NonNegativeInt),\n  toCheckpointRef: Schema.NullOr(CheckpointRef),\n});\n\nconst REQUIRED_SNAPSHOT_PROJECTORS = [\n  ORCHESTRATION_PROJECTOR_NAMES.projects,\n  ORCHESTRATION_PROJECTOR_NAMES.threads,\n  ORCHESTRATION_PROJECTOR_NAMES.threadMessages,\n  ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,\n  ORCHESTRATION_PROJECTOR_NAMES.threadActivities,\n  ORCHESTRATION_PROJECTOR_NAMES.threadSessions,\n  ORCHESTRATION_PROJECTOR_NAMES.checkpoints,\n] as const;\n\nfunction maxIso(left: string | null, right: string): string {\n  if (left === null) {\n    return right;\n  }\n  return left > right ? left : right;\n}\n\nfunction escapeLikePattern(value: string): string {\n  return value.replaceAll(\"!\", \"!!\").replaceAll(\"%\", \"!%\").replaceAll(\"_\", \"!_\");\n}\n\nfunction foldAsciiCase(value: string): string {\n  return value.replace(/[A-Z]/g, (character) => character.toLowerCase());\n}\n\nfunction buildSearchSnippet(text: string, query: string): string {\n  const normalizedText = text.replace(/\\s+/g, \" \").trim();\n  if (normalizedText.length <= 240) {\n    return normalizedText;\n  }\n\n  const normalizedQuery = foldAsciiCase(query.replace(/\\s+/g, \" \").trim());\n  const matchIndex = foldAsciiCase(normalizedText).indexOf(normalizedQuery);\n  const bodyLength = 236;\n  const idealStart = Math.max(0, matchIndex - 72);\n  const start = Math.min(idealStart, normalizedText.length - bodyLength);\n  const end = Math.min(normalizedText.length, start + bodyLength);\n  return `${start > 0 ? \"…\" : \"\"}${normalizedText.slice(start, end)}${\n    end < normalizedText.length ? \"…\" : \"\"\n  }`;\n}\n\nfunction computeSnapshotSequence(\n  stateRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionStateDbRowSchema>>,\n): number {\n  if (stateRows.length === 0) {\n    return 0;\n  }\n  const sequenceByProjector = new Map(\n    stateRows.map((row) => [row.projector, row.lastAppliedSequence] as const),\n  );\n\n  let minSequence = Number.POSITIVE_INFINITY;\n  for (const projector of REQUIRED_SNAPSHOT_PROJECTORS) {\n    const sequence = sequenceByProjector.get(projector);\n    if (sequence === undefined) {\n      return 0;\n    }\n    if (sequence < minSequence) {\n      minSequence = sequence;\n    }\n  }\n\n  return Number.isFinite(minSequence) ? minSequence : 0;\n}\n\nfunction mapLatestTurn(\n  row: Schema.Schema.Type<typeof ProjectionLatestTurnDbRowSchema>,\n): OrchestrationLatestTurn {\n  return {\n    turnId: row.turnId,\n    state:\n      row.state === \"error\"\n        ? \"error\"\n        : row.state === \"interrupted\"\n          ? \"interrupted\"\n          : row.state === \"completed\"\n            ? \"completed\"\n            : \"running\",\n    requestedAt: row.requestedAt,\n    startedAt: row.startedAt,\n    completedAt: row.completedAt,\n    assistantMessageId: row.assistantMessageId,\n    ...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null\n      ? {\n          sourceProposedPlan: {\n            threadId: row.sourceProposedPlanThreadId,\n            planId: row.sourceProposedPlanId,\n          },\n        }\n      : {}),\n  };\n}\n\nfunction mapTitleRegeneration(row: Schema.Schema.Type<typeof ProjectionThreadDbRowSchema>) {\n  return row.titleRegenerationRequestId != null && row.titleRegenerationStartedAt != null\n    ? {\n        requestId: row.titleRegenerationRequestId,\n        startedAt: row.titleRegenerationStartedAt,\n      }\n    : null;\n}\n\nfunction mapSessionRow(\n  row: Schema.Schema.Type<typeof ProjectionThreadSessionDbRowSchema>,\n): OrchestrationSession {\n  return {\n    threadId: row.threadId,\n    status: row.status,\n    providerName: row.providerName,\n    ...(row.providerInstanceId !== null ? { providerInstanceId: row.providerInstanceId } : {}),\n    runtimeMode: row.runtimeMode,\n    activeTurnId: row.activeTurnId,\n    lastError: row.lastError,\n    updatedAt: row.updatedAt,\n  };\n}\n\nfunction mapProjectShellRow(\n  row: Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>,\n  repositoryIdentity: OrchestrationProject[\"repositoryIdentity\"],\n): OrchestrationProjectShell {\n  return {\n    id: row.projectId,\n    title: row.title,\n    workspaceRoot: row.workspaceRoot,\n    repositoryIdentity,\n    defaultModelSelection: row.defaultModelSelection,\n    scripts: row.scripts,\n    createdAt: row.createdAt,\n    updatedAt: row.updatedAt,\n  };\n}\n\nfunction mapProposedPlanRow(\n  row: Schema.Schema.Type<typeof ProjectionThreadProposedPlanDbRowSchema>,\n): OrchestrationProposedPlan {\n  return {\n    id: row.planId,\n    turnId: row.turnId,\n    planMarkdown: row.planMarkdown,\n    implementedAt: row.implementedAt,\n    implementationThreadId: row.implementationThreadId,\n    createdAt: row.createdAt,\n    updatedAt: row.updatedAt,\n  };\n}\n\nfunction toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {\n  return (cause: unknown): ProjectionRepositoryError =>\n    Schema.isSchemaError(cause)\n      ? toPersistenceDecodeError(decodeOperation)(cause)\n      : toPersistenceSqlError(sqlOperation)(cause);\n}\n\nconst makeProjectionSnapshotQuery = Effect.gen(function* () {\n  const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;\n  const threadPlanProgress = yield* ThreadPlanProgressService;\n  const sql = yield* SqlClient.SqlClient;\n  const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;\n  const repositoryIdentityResolutionConcurrency = 4;\n  const resolveRepositoryIdentitiesForProjects = Effect.fn(\n    \"ProjectionSnapshotQuery.resolveRepositoryIdentitiesForProjects\",\n  )(function* (\n    projectRows: ReadonlyArray<Schema.Schema.Type<typeof ProjectionProjectDbRowSchema>>,\n    options?: {\n      readonly includeDeleted?: boolean;\n    },\n  ) {\n    const filteredProjectRows =\n      options?.includeDeleted === true\n        ? projectRows\n        : projectRows.filter((row) => row.deletedAt === null);\n    const uniqueWorkspaceRoots = [...new Set(filteredProjectRows.map((row) => row.workspaceRoot))];\n    const repositoryIdentityByWorkspaceRoot = new Map(\n      yield* Effect.forEach(\n        uniqueWorkspaceRoots,\n        (workspaceRoot) =>\n          repositoryIdentityResolver\n            .resolve(workspaceRoot)\n            .pipe(Effect.map((identity) => [workspaceRoot, identity] as const)),\n        { concurrency: repositoryIdentityResolutionConcurrency },\n      ),\n    );\n\n    return new Map(\n      filteredProjectRows.map((row) => [\n        row.projectId,\n        repositoryIdentityByWorkspaceRoot.get(row.workspaceRoot) ?? null,\n      ]),\n    );\n  });\n\n  const listProjectRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionProjectDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        ORDER BY created_at ASC, project_id ASC\n      `,\n  });\n\n  const listThreadRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          pin_order_key AS \"pinOrderKey\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        ORDER BY created_at ASC, thread_id ASC\n      `,\n  });\n\n  const listActiveThreadRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          pin_order_key AS \"pinOrderKey\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE deleted_at IS NULL\n          AND archived_at IS NULL\n        ORDER BY project_id ASC, created_at ASC, thread_id ASC\n      `,\n  });\n\n  const listArchivedThreadRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          pin_order_key AS \"pinOrderKey\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE deleted_at IS NULL\n          AND archived_at IS NOT NULL\n        ORDER BY project_id ASC, archived_at DESC, thread_id DESC\n      `,\n  });\n\n  const listThreadMessageRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadMessageDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          message_id AS \"messageId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          role,\n          text,\n          attachments_json AS \"attachments\",\n          is_streaming AS \"isStreaming\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_messages\n        ORDER BY thread_id ASC, created_at ASC, message_id ASC\n      `,\n  });\n\n  const listThreadProposedPlanRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadProposedPlanDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          plan_id AS \"planId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          plan_markdown AS \"planMarkdown\",\n          implemented_at AS \"implementedAt\",\n          implementation_thread_id AS \"implementationThreadId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_proposed_plans\n        ORDER BY thread_id ASC, created_at ASC, plan_id ASC\n      `,\n  });\n\n  const listThreadActivityRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadActivityDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          activity_id AS \"activityId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          tone,\n          kind,\n          summary,\n          payload_json AS \"payload\",\n          sequence,\n          created_at AS \"createdAt\"\n        FROM projection_thread_activities\n        ORDER BY\n          thread_id ASC,\n          sequence ASC,\n          created_at ASC,\n          activity_id ASC\n      `,\n  });\n\n  const listThreadSessionRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadSessionDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          status,\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          provider_session_id AS \"providerSessionId\",\n          provider_thread_id AS \"providerThreadId\",\n          runtime_mode AS \"runtimeMode\",\n          active_turn_id AS \"activeTurnId\",\n          last_error AS \"lastError\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions\n        ORDER BY thread_id ASC\n      `,\n  });\n\n  const listActiveThreadSessionRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadSessionDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          sessions.thread_id AS \"threadId\",\n          sessions.status,\n          sessions.provider_name AS \"providerName\",\n          sessions.provider_instance_id AS \"providerInstanceId\",\n          sessions.provider_session_id AS \"providerSessionId\",\n          sessions.provider_thread_id AS \"providerThreadId\",\n          sessions.runtime_mode AS \"runtimeMode\",\n          sessions.active_turn_id AS \"activeTurnId\",\n          sessions.last_error AS \"lastError\",\n          sessions.updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions sessions\n        INNER JOIN projection_threads threads\n          ON threads.thread_id = sessions.thread_id\n        WHERE threads.deleted_at IS NULL\n          AND threads.archived_at IS NULL\n        ORDER BY sessions.thread_id ASC\n      `,\n  });\n\n  const listArchivedThreadSessionRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionThreadSessionDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          sessions.thread_id AS \"threadId\",\n          sessions.status,\n          sessions.provider_name AS \"providerName\",\n          sessions.provider_instance_id AS \"providerInstanceId\",\n          sessions.provider_session_id AS \"providerSessionId\",\n          sessions.provider_thread_id AS \"providerThreadId\",\n          sessions.runtime_mode AS \"runtimeMode\",\n          sessions.active_turn_id AS \"activeTurnId\",\n          sessions.last_error AS \"lastError\",\n          sessions.updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions sessions\n        INNER JOIN projection_threads threads\n          ON threads.thread_id = sessions.thread_id\n        WHERE threads.deleted_at IS NULL\n          AND threads.archived_at IS NOT NULL\n        ORDER BY sessions.thread_id ASC\n      `,\n  });\n\n  const listCheckpointRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionCheckpointDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          checkpoint_turn_count AS \"checkpointTurnCount\",\n          checkpoint_ref AS \"checkpointRef\",\n          checkpoint_status AS \"status\",\n          checkpoint_files_json AS \"files\",\n          assistant_message_id AS \"assistantMessageId\",\n          completed_at AS \"completedAt\"\n        FROM projection_turns\n        WHERE checkpoint_turn_count IS NOT NULL\n        ORDER BY thread_id ASC, checkpoint_turn_count ASC\n      `,\n  });\n\n  const listLatestTurnRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionLatestTurnDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          turns.thread_id AS \"threadId\",\n          turns.turn_id AS \"turnId\",\n          turns.state,\n          turns.requested_at AS \"requestedAt\",\n          turns.started_at AS \"startedAt\",\n          turns.completed_at AS \"completedAt\",\n          turns.assistant_message_id AS \"assistantMessageId\",\n          turns.source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          turns.source_proposed_plan_id AS \"sourceProposedPlanId\"\n        FROM projection_threads threads\n        JOIN projection_turns turns\n          ON turns.thread_id = threads.thread_id\n          AND turns.turn_id = threads.latest_turn_id\n        WHERE threads.latest_turn_id IS NOT NULL\n        ORDER BY turns.thread_id ASC\n      `,\n  });\n\n  const listActiveLatestTurnRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionLatestTurnDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          turns.thread_id AS \"threadId\",\n          turns.turn_id AS \"turnId\",\n          turns.state,\n          turns.requested_at AS \"requestedAt\",\n          turns.started_at AS \"startedAt\",\n          turns.completed_at AS \"completedAt\",\n          turns.assistant_message_id AS \"assistantMessageId\",\n          turns.source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          turns.source_proposed_plan_id AS \"sourceProposedPlanId\"\n        FROM projection_threads threads\n        JOIN projection_turns turns\n          ON turns.thread_id = threads.thread_id\n          AND turns.turn_id = threads.latest_turn_id\n        WHERE threads.deleted_at IS NULL\n          AND threads.archived_at IS NULL\n          AND threads.latest_turn_id IS NOT NULL\n        ORDER BY turns.thread_id ASC\n      `,\n  });\n\n  const listArchivedLatestTurnRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionLatestTurnDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          turns.thread_id AS \"threadId\",\n          turns.turn_id AS \"turnId\",\n          turns.state,\n          turns.requested_at AS \"requestedAt\",\n          turns.started_at AS \"startedAt\",\n          turns.completed_at AS \"completedAt\",\n          turns.assistant_message_id AS \"assistantMessageId\",\n          turns.source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          turns.source_proposed_plan_id AS \"sourceProposedPlanId\"\n        FROM projection_threads threads\n        JOIN projection_turns turns\n          ON turns.thread_id = threads.thread_id\n          AND turns.turn_id = threads.latest_turn_id\n        WHERE threads.deleted_at IS NULL\n          AND threads.archived_at IS NOT NULL\n          AND threads.latest_turn_id IS NOT NULL\n        ORDER BY turns.thread_id ASC\n      `,\n  });\n\n  const listProjectionStateRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProjectionStateDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          projector,\n          last_applied_sequence AS \"lastAppliedSequence\",\n          updated_at AS \"updatedAt\"\n        FROM projection_state\n      `,\n  });\n\n  const readProjectionCounts = SqlSchema.findOne({\n    Request: Schema.Void,\n    Result: ProjectionCountsRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          (SELECT COUNT(*) FROM projection_projects) AS \"projectCount\",\n          (SELECT COUNT(*) FROM projection_threads) AS \"threadCount\"\n      `,\n  });\n\n  const searchActiveThreadRows = SqlSchema.findAll({\n    Request: ProjectionThreadSearchRequest,\n    Result: ProjectionThreadSearchRow,\n    execute: ({ pattern, limit }) =>\n      sql`\n        WITH ranked AS (\n          SELECT\n            threads.thread_id AS thread_id,\n            threads.project_id AS project_id,\n            CASE messages.role\n              WHEN 'user' THEN 'user'\n              ELSE 'assistant'\n            END AS source,\n            messages.text AS match_text,\n            messages.created_at AS message_created_at,\n            CASE messages.role\n              WHEN 'user' THEN 0\n              ELSE 1\n            END AS match_rank,\n            threads.updated_at AS thread_updated_at,\n            ROW_NUMBER() OVER (\n              PARTITION BY threads.thread_id\n              ORDER BY\n                CASE messages.role\n                  WHEN 'user' THEN 0\n                  ELSE 1\n                END ASC,\n                messages.created_at DESC,\n                messages.message_id ASC\n            ) AS thread_match_rank\n          FROM projection_thread_messages AS messages\n          INNER JOIN projection_threads AS threads\n            ON threads.thread_id = messages.thread_id\n          INNER JOIN projection_projects AS projects\n            ON projects.project_id = threads.project_id\n          WHERE threads.deleted_at IS NULL\n            AND threads.archived_at IS NULL\n            AND projects.deleted_at IS NULL\n            AND messages.is_streaming = 0\n            AND (\n              messages.role = 'user'\n              OR (\n                messages.role = 'assistant'\n                AND messages.message_id IN (\n                  SELECT turns.assistant_message_id\n                  FROM projection_turns AS turns\n                  WHERE turns.assistant_message_id IS NOT NULL\n                )\n              )\n            )\n            AND messages.text LIKE ${pattern} ESCAPE '!'\n        )\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          source,\n          match_text AS \"matchText\",\n          message_created_at AS \"messageCreatedAt\"\n        FROM ranked\n        WHERE thread_match_rank = 1\n        ORDER BY\n          match_rank ASC,\n          thread_updated_at DESC,\n          thread_id ASC\n        LIMIT ${limit}\n      `,\n  });\n\n  const getActiveProjectRowByWorkspaceRoot = SqlSchema.findOneOption({\n    Request: WorkspaceRootLookupInput,\n    Result: ProjectionProjectLookupRowSchema,\n    execute: ({ workspaceRoot }) =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        WHERE workspace_root = ${workspaceRoot}\n          AND deleted_at IS NULL\n        ORDER BY created_at ASC, project_id ASC\n        LIMIT 1\n      `,\n  });\n\n  const getActiveProjectRowById = SqlSchema.findOneOption({\n    Request: ProjectIdLookupInput,\n    Result: ProjectionProjectLookupRowSchema,\n    execute: ({ projectId }) =>\n      sql`\n        SELECT\n          project_id AS \"projectId\",\n          title,\n          workspace_root AS \"workspaceRoot\",\n          default_model_selection_json AS \"defaultModelSelection\",\n          scripts_json AS \"scripts\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_projects\n        WHERE project_id = ${projectId}\n          AND deleted_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({\n    Request: ProjectIdLookupInput,\n    Result: ProjectionThreadIdLookupRowSchema,\n    execute: ({ projectId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\"\n        FROM projection_threads\n        WHERE project_id = ${projectId}\n          AND deleted_at IS NULL\n          AND archived_at IS NULL\n        ORDER BY created_at ASC, thread_id ASC\n        LIMIT 1\n      `,\n  });\n\n  const getThreadCheckpointContextThreadRow = SqlSchema.findOneOption({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadCheckpointContextThreadRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          threads.thread_id AS \"threadId\",\n          threads.project_id AS \"projectId\",\n          projects.workspace_root AS \"workspaceRoot\",\n          threads.worktree_path AS \"worktreePath\"\n        FROM projection_threads AS threads\n        INNER JOIN projection_projects AS projects\n          ON projects.project_id = threads.project_id\n        WHERE threads.thread_id = ${threadId}\n          AND threads.deleted_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const getActiveThreadRowById = SqlSchema.findOneOption({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          project_id AS \"projectId\",\n          title,\n          model_selection_json AS \"modelSelection\",\n          runtime_mode AS \"runtimeMode\",\n          interaction_mode AS \"interactionMode\",\n          branch,\n          worktree_path AS \"worktreePath\",\n          latest_turn_id AS \"latestTurnId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\",\n          archived_at AS \"archivedAt\",\n          settled_override AS \"settledOverride\",\n          settled_at AS \"settledAt\",\n          snoozed_until AS \"snoozedUntil\",\n          snoozed_at AS \"snoozedAt\",\n          pinned_at AS \"pinnedAt\",\n          pin_order_key AS \"pinOrderKey\",\n          title_regeneration_request_id AS \"titleRegenerationRequestId\",\n          title_regeneration_started_at AS \"titleRegenerationStartedAt\",\n          latest_user_message_at AS \"latestUserMessageAt\",\n          pending_approval_count AS \"pendingApprovalCount\",\n          pending_user_input_count AS \"pendingUserInputCount\",\n          has_actionable_proposed_plan AS \"hasActionableProposedPlan\",\n          deleted_at AS \"deletedAt\"\n        FROM projection_threads\n        WHERE thread_id = ${threadId}\n          AND deleted_at IS NULL\n          AND archived_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const listThreadMessageRowsByThread = SqlSchema.findAll({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadMessageDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          message_id AS \"messageId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          role,\n          text,\n          attachments_json AS \"attachments\",\n          is_streaming AS \"isStreaming\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_messages\n        WHERE thread_id = ${threadId}\n        ORDER BY created_at ASC, message_id ASC\n      `,\n  });\n\n  const listThreadProposedPlanRowsByThread = SqlSchema.findAll({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadProposedPlanDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          plan_id AS \"planId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          plan_markdown AS \"planMarkdown\",\n          implemented_at AS \"implementedAt\",\n          implementation_thread_id AS \"implementationThreadId\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_proposed_plans\n        WHERE thread_id = ${threadId}\n        ORDER BY created_at ASC, plan_id ASC\n      `,\n  });\n\n  const listThreadActivityRowsByThread = SqlSchema.findAll({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadActivityDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          activity_id AS \"activityId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          tone,\n          kind,\n          summary,\n          payload_json AS \"payload\",\n          sequence,\n          created_at AS \"createdAt\"\n        FROM projection_thread_activities\n        WHERE thread_id = ${threadId}\n        ORDER BY\n          sequence ASC,\n          created_at ASC,\n          activity_id ASC\n      `,\n  });\n\n  const getThreadSessionRowByThread = SqlSchema.findOneOption({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionThreadSessionDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          status,\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          runtime_mode AS \"runtimeMode\",\n          active_turn_id AS \"activeTurnId\",\n          last_error AS \"lastError\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_sessions\n        WHERE thread_id = ${threadId}\n        LIMIT 1\n      `,\n  });\n\n  const getLatestTurnRowByThread = SqlSchema.findOneOption({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionLatestTurnDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          turns.thread_id AS \"threadId\",\n          turns.turn_id AS \"turnId\",\n          turns.state,\n          turns.requested_at AS \"requestedAt\",\n          turns.started_at AS \"startedAt\",\n          turns.completed_at AS \"completedAt\",\n          turns.assistant_message_id AS \"assistantMessageId\",\n          turns.source_proposed_plan_thread_id AS \"sourceProposedPlanThreadId\",\n          turns.source_proposed_plan_id AS \"sourceProposedPlanId\"\n        FROM projection_threads threads\n        JOIN projection_turns turns\n          ON turns.thread_id = threads.thread_id\n          AND turns.turn_id = threads.latest_turn_id\n        WHERE threads.thread_id = ${threadId}\n          AND threads.deleted_at IS NULL\n          AND threads.archived_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const listCheckpointRowsByThread = SqlSchema.findAll({\n    Request: ThreadIdLookupInput,\n    Result: ProjectionCheckpointDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          checkpoint_turn_count AS \"checkpointTurnCount\",\n          checkpoint_ref AS \"checkpointRef\",\n          checkpoint_status AS \"status\",\n          checkpoint_files_json AS \"files\",\n          assistant_message_id AS \"assistantMessageId\",\n          completed_at AS \"completedAt\"\n        FROM projection_turns\n        WHERE thread_id = ${threadId}\n          AND checkpoint_turn_count IS NOT NULL\n        ORDER BY checkpoint_turn_count ASC\n      `,\n  });\n\n  // Resolves a page of recent turns for a windowed thread detail read. Walks\n  // back from the exclusive (beforeAnchorAt, beforeTurnKey) keyset boundary\n  // (sentinels \"~\"/\"\" mean unbounded, i.e. the first page) until it has seen\n  // `userTurnLimit` user-anchored turns — turns whose pending message is a\n  // user message; subagent/fan-out turns between them ride along — or hits the\n  // `maxRawTurns` ceiling that bounds pathological fan-out. The `candidates`\n  // CTE applies the keyset bound and LIMIT before the window functions run;\n  // its ORDER BY uses raw columns so the migration-037\n  // (thread_id, requested_at, turn_id) index serves both range and order with\n  // no temp B-tree — the scan is genuinely bounded by the LIMIT. (Raw\n  // turn_id DESC places NULLs exactly where COALESCE-to-'' would, below every\n  // real id.) The caller derives the continuation cursor from the oldest\n  // returned row.\n  // Highest thread-DETAIL event sequence for this thread that the projection\n  // has applied (bounded by the global snapshot sequence read in the same\n  // transaction). This is the thread-scoped watermark a windowed page carries\n  // so clients can defer merging until their live subscription has caught up;\n  // the global sequence is not waitable per-thread. The event_type filter\n  // must match ws.ts's isThreadDetailEvent exactly: the subscription only\n  // delivers these types, so a watermark counting any other event could\n  // never be reached by the client and would park the page forever. Served\n  // by the event store's (aggregate_kind, stream_id, sequence) index.\n  const getThreadEventWatermarkRow = SqlSchema.findOneOption({\n    Request: Schema.Struct({ threadId: ThreadId, maxSequence: Schema.Number }),\n    Result: Schema.Struct({ threadSequence: Schema.NullOr(Schema.Number) }),\n    execute: ({ threadId, maxSequence }) =>\n      sql`\n        SELECT MAX(sequence) AS \"threadSequence\"\n        FROM orchestration_events\n        WHERE aggregate_kind = 'thread'\n          AND stream_id = ${threadId}\n          AND sequence <= ${maxSequence}\n          AND event_type IN (\n            'thread.message-sent',\n            'thread.proposed-plan-upserted',\n            'thread.activity-appended',\n            'thread.turn-diff-completed',\n            'thread.reverted',\n            'thread.session-set'\n          )\n      `,\n  });\n\n  const listTurnWindowRows = SqlSchema.findAll({\n    Request: ThreadTurnWindowLookupInput,\n    Result: ProjectionTurnWindowRowSchema,\n    execute: ({ threadId, beforeAnchorAt, beforeTurnKey, userTurnLimit, maxRawTurns }) =>\n      sql`\n        WITH candidates AS (\n          SELECT\n            turns.requested_at AS anchor_at,\n            COALESCE(turns.turn_id, '') AS turn_key,\n            turns.pending_message_id\n          FROM projection_turns AS turns\n          WHERE turns.thread_id = ${threadId}\n            AND (\n              turns.requested_at < ${beforeAnchorAt}\n              OR (\n                turns.requested_at = ${beforeAnchorAt}\n                AND COALESCE(turns.turn_id, '') < ${beforeTurnKey}\n              )\n            )\n          ORDER BY turns.requested_at DESC, turns.turn_id DESC\n          LIMIT ${maxRawTurns}\n        ),\n        walked AS (\n          SELECT\n            candidates.anchor_at,\n            candidates.turn_key,\n            CASE WHEN messages.role = 'user' THEN 1 ELSE 0 END AS is_user_turn,\n            SUM(CASE WHEN messages.role = 'user' THEN 1 ELSE 0 END) OVER (\n              ORDER BY candidates.anchor_at DESC, candidates.turn_key DESC\n            ) AS user_turns_seen\n          FROM candidates\n          LEFT JOIN projection_thread_messages AS messages\n            ON messages.message_id = candidates.pending_message_id\n        )\n        SELECT\n          anchor_at AS \"anchorAt\",\n          turn_key AS \"turnKey\"\n        FROM walked\n        WHERE user_turns_seen < ${userTurnLimit}\n          OR (user_turns_seen = ${userTurnLimit} AND is_user_turn = 1)\n        ORDER BY anchor_at ASC, turn_key ASC\n      `,\n  });\n\n  // Windowed variants of the two heavy collections. Turn-linked rows are\n  // bounded by the page's (anchor, turn key) keyset range over\n  // projection_turns; rows with no turn linkage (user messages always, and\n  // turnless activities like pre-turn context-window updates) are bounded by\n  // the matching turn-anchor time range so they land on the same page as the\n  // turns around them. Proposed plans and checkpoints stay unwindowed: they\n  // are metadata-scale.\n  const listThreadMessageRowsByThreadWindow = SqlSchema.findAll({\n    Request: ThreadTurnRangeLookupInput,\n    Result: ProjectionThreadMessageDbRowSchema,\n    execute: ({ threadId, minAnchorAt, minTurnKey, beforeAnchorAt, beforeTurnKey }) =>\n      sql`\n        SELECT\n          message_id AS \"messageId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          role,\n          text,\n          attachments_json AS \"attachments\",\n          is_streaming AS \"isStreaming\",\n          created_at AS \"createdAt\",\n          updated_at AS \"updatedAt\"\n        FROM projection_thread_messages\n        WHERE thread_id = ${threadId}\n          AND (\n            turn_id IN (\n              SELECT turn_id FROM projection_turns\n              WHERE thread_id = ${threadId}\n                AND turn_id IS NOT NULL\n                AND (\n                  requested_at > ${minAnchorAt}\n                  OR (\n                    requested_at = ${minAnchorAt}\n                    AND turn_id >= ${minTurnKey}\n                  )\n                )\n                AND (\n                  requested_at < ${beforeAnchorAt}\n                  OR (\n                    requested_at = ${beforeAnchorAt}\n                    AND turn_id < ${beforeTurnKey}\n                  )\n                )\n            )\n            OR (\n              turn_id IS NULL\n              AND created_at >= ${minAnchorAt}\n              AND created_at < ${beforeAnchorAt}\n            )\n          )\n        ORDER BY created_at ASC, message_id ASC\n      `,\n  });\n\n  const listThreadActivityRowsByThreadWindow = SqlSchema.findAll({\n    Request: ThreadTurnRangeLookupInput,\n    Result: ProjectionThreadActivityDbRowSchema,\n    execute: ({ threadId, minAnchorAt, minTurnKey, beforeAnchorAt, beforeTurnKey }) =>\n      sql`\n        SELECT\n          activity_id AS \"activityId\",\n          thread_id AS \"threadId\",\n          turn_id AS \"turnId\",\n          tone,\n          kind,\n          summary,\n          payload_json AS \"payload\",\n          sequence,\n          created_at AS \"createdAt\"\n        FROM projection_thread_activities\n        WHERE thread_id = ${threadId}\n          AND (\n            turn_id IN (\n              SELECT turn_id FROM projection_turns\n              WHERE thread_id = ${threadId}\n                AND turn_id IS NOT NULL\n                AND (\n                  requested_at > ${minAnchorAt}\n                  OR (\n                    requested_at = ${minAnchorAt}\n                    AND turn_id >= ${minTurnKey}\n                  )\n                )\n                AND (\n                  requested_at < ${beforeAnchorAt}\n                  OR (\n                    requested_at = ${beforeAnchorAt}\n                    AND turn_id < ${beforeTurnKey}\n                  )\n                )\n            )\n            OR (\n              turn_id IS NULL\n              AND created_at >= ${minAnchorAt}\n              AND created_at < ${beforeAnchorAt}\n            )\n          )\n        ORDER BY\n          sequence ASC,\n          created_at ASC,\n          activity_id ASC\n      `,\n  });\n\n  const getFullThreadDiffContextRow = SqlSchema.findOneOption({\n    Request: FullThreadDiffContextLookupInput,\n    Result: ProjectionFullThreadDiffContextRowSchema,\n    execute: ({ threadId, checkpointTurnCount }) =>\n      sql`\n        SELECT\n          threads.thread_id AS \"threadId\",\n          threads.project_id AS \"projectId\",\n          projects.workspace_root AS \"workspaceRoot\",\n          threads.worktree_path AS \"worktreePath\",\n          (\n            SELECT MAX(turns.checkpoint_turn_count)\n            FROM projection_turns AS turns\n            WHERE turns.thread_id = threads.thread_id\n              AND turns.checkpoint_turn_count IS NOT NULL\n          ) AS \"latestCheckpointTurnCount\",\n          (\n            SELECT turns.checkpoint_ref\n            FROM projection_turns AS turns\n            WHERE turns.thread_id = threads.thread_id\n              AND turns.checkpoint_turn_count = ${checkpointTurnCount}\n            LIMIT 1\n          ) AS \"toCheckpointRef\"\n        FROM projection_threads AS threads\n        INNER JOIN projection_projects AS projects\n          ON projects.project_id = threads.project_id\n        WHERE threads.thread_id = ${threadId}\n          AND threads.deleted_at IS NULL\n        LIMIT 1\n      `,\n  });\n\n  const getSnapshot: ProjectionSnapshotQueryShape[\"getSnapshot\"] = () =>\n    sql\n      .withTransaction(\n        Effect.all([\n          listProjectRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listProjects:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listProjects:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreads:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreads:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadMessageRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadMessages:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadMessages:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadProposedPlanRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadActivityRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadActivities:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadActivities:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadSessionRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadSessions:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listThreadSessions:decodeRows\",\n              ),\n            ),\n          ),\n          listCheckpointRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listCheckpoints:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listCheckpoints:decodeRows\",\n              ),\n            ),\n          ),\n          listLatestTurnRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listLatestTurns:decodeRows\",\n              ),\n            ),\n          ),\n          listProjectionStateRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getSnapshot:listProjectionState:query\",\n                \"ProjectionSnapshotQuery.getSnapshot:listProjectionState:decodeRows\",\n              ),\n            ),\n          ),\n        ]),\n      )\n      .pipe(\n        Effect.flatMap(\n          ([\n            projectRows,\n            threadRows,\n            messageRows,\n            proposedPlanRows,\n            activityRows,\n            sessionRows,\n            checkpointRows,\n            latestTurnRows,\n            stateRows,\n          ]) =>\n            Effect.gen(function* () {\n              const messagesByThread = new Map<string, Array<OrchestrationMessage>>();\n              const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();\n              const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();\n              const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();\n              const sessionsByThread = new Map<string, OrchestrationSession>();\n              const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();\n\n              let updatedAt: string | null = null;\n\n              for (const row of projectRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (const row of threadRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (const row of stateRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n\n              for (const row of messageRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n                const threadMessages = messagesByThread.get(row.threadId) ?? [];\n                threadMessages.push({\n                  id: row.messageId,\n                  role: row.role,\n                  text: row.text,\n                  ...(row.attachments !== null ? { attachments: row.attachments } : {}),\n                  turnId: row.turnId,\n                  streaming: row.isStreaming === 1,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                });\n                messagesByThread.set(row.threadId, threadMessages);\n              }\n\n              for (const row of proposedPlanRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n                const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];\n                threadProposedPlans.push({\n                  id: row.planId,\n                  turnId: row.turnId,\n                  planMarkdown: row.planMarkdown,\n                  implementedAt: row.implementedAt,\n                  implementationThreadId: row.implementationThreadId,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                });\n                proposedPlansByThread.set(row.threadId, threadProposedPlans);\n              }\n\n              for (const row of activityRows) {\n                updatedAt = maxIso(updatedAt, row.createdAt);\n                const threadActivities = activitiesByThread.get(row.threadId) ?? [];\n                threadActivities.push({\n                  id: row.activityId,\n                  tone: row.tone,\n                  kind: row.kind,\n                  summary: row.summary,\n                  payload: row.payload,\n                  turnId: row.turnId,\n                  ...(row.sequence !== null ? { sequence: row.sequence } : {}),\n                  createdAt: row.createdAt,\n                });\n                activitiesByThread.set(row.threadId, threadActivities);\n              }\n\n              for (const row of checkpointRows) {\n                updatedAt = maxIso(updatedAt, row.completedAt);\n                const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];\n                threadCheckpoints.push({\n                  turnId: row.turnId,\n                  checkpointTurnCount: row.checkpointTurnCount,\n                  checkpointRef: row.checkpointRef,\n                  status: row.status,\n                  files: row.files,\n                  assistantMessageId: row.assistantMessageId,\n                  completedAt: row.completedAt,\n                });\n                checkpointsByThread.set(row.threadId, threadCheckpoints);\n              }\n\n              for (const row of latestTurnRows) {\n                updatedAt = maxIso(updatedAt, row.requestedAt);\n                if (row.startedAt !== null) {\n                  updatedAt = maxIso(updatedAt, row.startedAt);\n                }\n                if (row.completedAt !== null) {\n                  updatedAt = maxIso(updatedAt, row.completedAt);\n                }\n                if (latestTurnByThread.has(row.threadId)) {\n                  continue;\n                }\n                latestTurnByThread.set(row.threadId, {\n                  turnId: row.turnId,\n                  state:\n                    row.state === \"error\"\n                      ? \"error\"\n                      : row.state === \"interrupted\"\n                        ? \"interrupted\"\n                        : row.state === \"completed\"\n                          ? \"completed\"\n                          : \"running\",\n                  requestedAt: row.requestedAt,\n                  startedAt: row.startedAt,\n                  completedAt: row.completedAt,\n                  assistantMessageId: row.assistantMessageId,\n                  ...(row.sourceProposedPlanThreadId !== null && row.sourceProposedPlanId !== null\n                    ? {\n                        sourceProposedPlan: {\n                          threadId: row.sourceProposedPlanThreadId,\n                          planId: row.sourceProposedPlanId,\n                        },\n                      }\n                    : {}),\n                });\n              }\n\n              for (const row of sessionRows) {\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n                sessionsByThread.set(row.threadId, {\n                  threadId: row.threadId,\n                  status: row.status,\n                  providerName: row.providerName,\n                  ...(row.providerInstanceId !== null\n                    ? { providerInstanceId: row.providerInstanceId }\n                    : {}),\n                  runtimeMode: row.runtimeMode,\n                  activeTurnId: row.activeTurnId,\n                  lastError: row.lastError,\n                  updatedAt: row.updatedAt,\n                });\n              }\n\n              const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(\n                projectRows,\n                { includeDeleted: true },\n              );\n\n              const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({\n                id: row.projectId,\n                title: row.title,\n                workspaceRoot: row.workspaceRoot,\n                repositoryIdentity: repositoryIdentities.get(row.projectId) ?? null,\n                defaultModelSelection: row.defaultModelSelection,\n                scripts: row.scripts,\n                createdAt: row.createdAt,\n                updatedAt: row.updatedAt,\n                deletedAt: row.deletedAt,\n              }));\n\n              const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({\n                id: row.threadId,\n                projectId: row.projectId,\n                title: row.title,\n                modelSelection: row.modelSelection,\n                runtimeMode: row.runtimeMode,\n                interactionMode: row.interactionMode,\n                branch: row.branch,\n                worktreePath: row.worktreePath,\n                latestTurn: latestTurnByThread.get(row.threadId) ?? null,\n                createdAt: row.createdAt,\n                updatedAt: row.updatedAt,\n                archivedAt: row.archivedAt,\n                settledOverride: row.settledOverride,\n                settledAt: row.settledAt,\n                snoozedUntil: row.snoozedUntil,\n                snoozedAt: row.snoozedAt,\n                pinnedAt: row.pinnedAt,\n                pinOrderKey: row.pinOrderKey ?? null,\n                titleRegeneration: mapTitleRegeneration(row),\n                deletedAt: row.deletedAt,\n                messages: messagesByThread.get(row.threadId) ?? [],\n                proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],\n                activities: activitiesByThread.get(row.threadId) ?? [],\n                checkpoints: checkpointsByThread.get(row.threadId) ?? [],\n                session: sessionsByThread.get(row.threadId) ?? null,\n              }));\n\n              const snapshot = {\n                snapshotSequence: computeSnapshotSequence(stateRows),\n                projects,\n                threads,\n                updatedAt: updatedAt ?? \"1970-01-01T00:00:00.000Z\",\n              };\n\n              return yield* decodeReadModel(snapshot).pipe(\n                Effect.mapError(\n                  toPersistenceDecodeError(\"ProjectionSnapshotQuery.getSnapshot:decodeReadModel\"),\n                ),\n              );\n            }),\n        ),\n        Effect.mapError((error) => {\n          if (isPersistenceError(error)) {\n            return error;\n          }\n          return toPersistenceSqlError(\"ProjectionSnapshotQuery.getSnapshot:query\")(error);\n        }),\n      );\n\n  const getCommandReadModel: ProjectionSnapshotQueryShape[\"getCommandReadModel\"] = () =>\n    sql\n      .withTransaction(\n        Effect.all([\n          listProjectRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listProjects:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listProjects:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreads:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreads:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadProposedPlanRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreadProposedPlans:decodeRows\",\n              ),\n            ),\n          ),\n          listThreadSessionRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listThreadSessions:decodeRows\",\n              ),\n            ),\n          ),\n          listLatestTurnRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listLatestTurns:decodeRows\",\n              ),\n            ),\n          ),\n          listProjectionStateRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:query\",\n                \"ProjectionSnapshotQuery.getCommandReadModel:listProjectionState:decodeRows\",\n              ),\n            ),\n          ),\n        ]),\n      )\n      .pipe(\n        Effect.flatMap(\n          ([projectRows, threadRows, proposedPlanRows, sessionRows, latestTurnRows, stateRows]) =>\n            Effect.sync(() => {\n              let updatedAt: string | null = null;\n              const projects: OrchestrationProject[] = [];\n              const threads: OrchestrationThread[] = [];\n\n              for (let index = 0; index < projectRows.length; index += 1) {\n                const row = projectRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n                projects.push({\n                  id: row.projectId,\n                  title: row.title,\n                  workspaceRoot: row.workspaceRoot,\n                  defaultModelSelection: row.defaultModelSelection,\n                  scripts: row.scripts,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                  deletedAt: row.deletedAt,\n                });\n              }\n              for (let index = 0; index < threadRows.length; index += 1) {\n                const row = threadRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (let index = 0; index < proposedPlanRows.length; index += 1) {\n                const row = proposedPlanRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (let index = 0; index < sessionRows.length; index += 1) {\n                const row = sessionRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n              for (let index = 0; index < latestTurnRows.length; index += 1) {\n                const row = latestTurnRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.requestedAt);\n                if (row.startedAt !== null) {\n                  updatedAt = maxIso(updatedAt, row.startedAt);\n                }\n                if (row.completedAt !== null) {\n                  updatedAt = maxIso(updatedAt, row.completedAt);\n                }\n              }\n              for (let index = 0; index < stateRows.length; index += 1) {\n                const row = stateRows[index];\n                if (!row) {\n                  continue;\n                }\n                updatedAt = maxIso(updatedAt, row.updatedAt);\n              }\n\n              const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();\n              for (let index = 0; index < latestTurnRows.length; index += 1) {\n                const row = latestTurnRows[index];\n                if (!row) {\n                  continue;\n                }\n                latestTurnByThread.set(row.threadId, mapLatestTurn(row));\n              }\n              const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();\n              const sessionByThread = new Map<string, OrchestrationSession>();\n\n              for (let index = 0; index < sessionRows.length; index += 1) {\n                const row = sessionRows[index];\n                if (!row) {\n                  continue;\n                }\n                sessionByThread.set(row.threadId, mapSessionRow(row));\n              }\n\n              for (let index = 0; index < proposedPlanRows.length; index += 1) {\n                const row = proposedPlanRows[index];\n                if (!row) {\n                  continue;\n                }\n                const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];\n                threadProposedPlans.push(mapProposedPlanRow(row));\n                proposedPlansByThread.set(row.threadId, threadProposedPlans);\n              }\n\n              for (let index = 0; index < threadRows.length; index += 1) {\n                const row = threadRows[index];\n                if (!row) {\n                  continue;\n                }\n                threads.push({\n                  id: row.threadId,\n                  projectId: row.projectId,\n                  title: row.title,\n                  modelSelection: row.modelSelection,\n                  runtimeMode: row.runtimeMode,\n                  interactionMode: row.interactionMode,\n                  branch: row.branch,\n                  worktreePath: row.worktreePath,\n                  latestTurn: latestTurnByThread.get(row.threadId) ?? null,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                  archivedAt: row.archivedAt,\n                  settledOverride: row.settledOverride,\n                  settledAt: row.settledAt,\n                  snoozedUntil: row.snoozedUntil,\n                  snoozedAt: row.snoozedAt,\n                  pinnedAt: row.pinnedAt,\n                  pinOrderKey: row.pinOrderKey ?? null,\n                  titleRegeneration: mapTitleRegeneration(row),\n                  deletedAt: row.deletedAt,\n                  messages: [],\n                  proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],\n                  activities: [],\n                  checkpoints: [],\n                  session: sessionByThread.get(row.threadId) ?? null,\n                });\n              }\n\n              return {\n                snapshotSequence: computeSnapshotSequence(stateRows),\n                projects,\n                threads,\n                updatedAt: updatedAt ?? \"1970-01-01T00:00:00.000Z\",\n              } satisfies OrchestrationReadModel;\n            }),\n        ),\n        Effect.mapError((error) => {\n          if (isPersistenceError(error)) {\n            return error;\n          }\n          return toPersistenceSqlError(\"ProjectionSnapshotQuery.getCommandReadModel:query\")(error);\n        }),\n      );\n\n  const getShellSnapshot: ProjectionSnapshotQueryShape[\"getShellSnapshot\"] = () =>\n    sql\n      .withTransaction(\n        Effect.all([\n          listProjectRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listProjects:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listProjects:decodeRows\",\n              ),\n            ),\n          ),\n          listActiveThreadRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listThreads:decodeRows\",\n              ),\n            ),\n          ),\n          listActiveThreadSessionRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:decodeRows\",\n              ),\n            ),\n          ),\n          listActiveLatestTurnRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listLatestTurns:decodeRows\",\n              ),\n            ),\n          ),\n          listProjectionStateRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:query\",\n                \"ProjectionSnapshotQuery.getShellSnapshot:listProjectionState:decodeRows\",\n              ),\n            ),\n          ),\n        ]),\n      )\n      .pipe(\n        Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>\n          Effect.gen(function* () {\n            let updatedAt: string | null = null;\n            for (const row of projectRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of threadRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of sessionRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of latestTurnRows) {\n              updatedAt = maxIso(updatedAt, row.requestedAt);\n              if (row.startedAt !== null) {\n                updatedAt = maxIso(updatedAt, row.startedAt);\n              }\n              if (row.completedAt !== null) {\n                updatedAt = maxIso(updatedAt, row.completedAt);\n              }\n            }\n            for (const row of stateRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n\n            const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(projectRows);\n            const latestTurnByThread = new Map(\n              latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),\n            );\n            const sessionByThread = new Map(\n              sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),\n            );\n\n            const snapshot = {\n              snapshotSequence: computeSnapshotSequence(stateRows),\n              projects: Arr.filterMap(projectRows, (row) =>\n                row.deletedAt === null\n                  ? Result.succeed(\n                      mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),\n                    )\n                  : Result.failVoid,\n              ),\n              threads: Arr.filterMap(threadRows, (row) =>\n                row.deletedAt === null\n                  ? Result.succeed({\n                      id: row.threadId,\n                      projectId: row.projectId,\n                      title: row.title,\n                      modelSelection: row.modelSelection,\n                      runtimeMode: row.runtimeMode,\n                      interactionMode: row.interactionMode,\n                      branch: row.branch,\n                      worktreePath: row.worktreePath,\n                      latestTurn: latestTurnByThread.get(row.threadId) ?? null,\n                      createdAt: row.createdAt,\n                      updatedAt: row.updatedAt,\n                      archivedAt: row.archivedAt,\n                      settledOverride: row.settledOverride,\n                      settledAt: row.settledAt,\n                      snoozedUntil: row.snoozedUntil,\n                      snoozedAt: row.snoozedAt,\n                      pinnedAt: row.pinnedAt,\n                      pinOrderKey: row.pinOrderKey ?? null,\n                      titleRegeneration: mapTitleRegeneration(row),\n                      session: sessionByThread.get(row.threadId) ?? null,\n                      latestUserMessageAt: row.latestUserMessageAt,\n                      hasPendingApprovals: row.pendingApprovalCount > 0,\n                      hasPendingUserInput: row.pendingUserInputCount > 0,\n                      hasActionableProposedPlan: row.hasActionableProposedPlan > 0,\n                      backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(\n                        row.threadId,\n                      ),\n                      planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),\n                    } satisfies OrchestrationThreadShell)\n                  : Result.failVoid,\n              ),\n              updatedAt: updatedAt ?? \"1970-01-01T00:00:00.000Z\",\n            };\n\n            return yield* decodeShellSnapshot(snapshot).pipe(\n              Effect.mapError(\n                toPersistenceDecodeError(\n                  \"ProjectionSnapshotQuery.getShellSnapshot:decodeShellSnapshot\",\n                ),\n              ),\n            );\n          }),\n        ),\n        Effect.mapError((error) => {\n          if (isPersistenceError(error)) {\n            return error;\n          }\n          return toPersistenceSqlError(\"ProjectionSnapshotQuery.getShellSnapshot:query\")(error);\n        }),\n      );\n\n  const getArchivedShellSnapshot: ProjectionSnapshotQueryShape[\"getArchivedShellSnapshot\"] = () =>\n    sql\n      .withTransaction(\n        Effect.all([\n          listProjectRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:decodeRows\",\n              ),\n            ),\n          ),\n          listArchivedThreadRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:decodeRows\",\n              ),\n            ),\n          ),\n          listArchivedThreadSessionRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:decodeRows\",\n              ),\n            ),\n          ),\n          listArchivedLatestTurnRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:decodeRows\",\n              ),\n            ),\n          ),\n          listProjectionStateRows(undefined).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:query\",\n                \"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:decodeRows\",\n              ),\n            ),\n          ),\n        ]),\n      )\n      .pipe(\n        Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>\n          Effect.gen(function* () {\n            let updatedAt: string | null = null;\n            for (const row of projectRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of threadRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of sessionRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n            for (const row of latestTurnRows) {\n              updatedAt = maxIso(updatedAt, row.requestedAt);\n              if (row.startedAt !== null) {\n                updatedAt = maxIso(updatedAt, row.startedAt);\n              }\n              if (row.completedAt !== null) {\n                updatedAt = maxIso(updatedAt, row.completedAt);\n              }\n            }\n            for (const row of stateRows) {\n              updatedAt = maxIso(updatedAt, row.updatedAt);\n            }\n\n            const activeProjectIds = new Set(threadRows.map((row) => row.projectId));\n            const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(\n              projectRows.filter((row) => activeProjectIds.has(row.projectId)),\n            );\n            const latestTurnByThread = new Map(\n              latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),\n            );\n            const sessionByThread = new Map(\n              sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),\n            );\n\n            const snapshot = {\n              snapshotSequence: computeSnapshotSequence(stateRows),\n              projects: Arr.filterMap(projectRows, (row) =>\n                row.deletedAt === null && activeProjectIds.has(row.projectId)\n                  ? Result.succeed(\n                      mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),\n                    )\n                  : Result.failVoid,\n              ),\n              threads: threadRows.map(\n                (row): OrchestrationThreadShell => ({\n                  id: row.threadId,\n                  projectId: row.projectId,\n                  title: row.title,\n                  modelSelection: row.modelSelection,\n                  runtimeMode: row.runtimeMode,\n                  interactionMode: row.interactionMode,\n                  branch: row.branch,\n                  worktreePath: row.worktreePath,\n                  latestTurn: latestTurnByThread.get(row.threadId) ?? null,\n                  createdAt: row.createdAt,\n                  updatedAt: row.updatedAt,\n                  archivedAt: row.archivedAt,\n                  settledOverride: row.settledOverride,\n                  settledAt: row.settledAt,\n                  snoozedUntil: row.snoozedUntil,\n                  snoozedAt: row.snoozedAt,\n                  pinnedAt: row.pinnedAt,\n                  pinOrderKey: row.pinOrderKey ?? null,\n                  titleRegeneration: mapTitleRegeneration(row),\n                  session: sessionByThread.get(row.threadId) ?? null,\n                  latestUserMessageAt: row.latestUserMessageAt,\n                  hasPendingApprovals: row.pendingApprovalCount > 0,\n                  hasPendingUserInput: row.pendingUserInputCount > 0,\n                  hasActionableProposedPlan: row.hasActionableProposedPlan > 0,\n                  backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(\n                    row.threadId,\n                  ),\n                  planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),\n                }),\n              ),\n              updatedAt: updatedAt ?? \"1970-01-01T00:00:00.000Z\",\n            };\n\n            return yield* decodeShellSnapshot(snapshot).pipe(\n              Effect.mapError(\n                toPersistenceDecodeError(\n                  \"ProjectionSnapshotQuery.getArchivedShellSnapshot:decodeShellSnapshot\",\n                ),\n              ),\n            );\n          }),\n        ),\n        Effect.mapError((error) => {\n          if (isPersistenceError(error)) {\n            return error;\n          }\n          return toPersistenceSqlError(\"ProjectionSnapshotQuery.getArchivedShellSnapshot:query\")(\n            error,\n          );\n        }),\n      );\n\n  const getSnapshotSequence: ProjectionSnapshotQueryShape[\"getSnapshotSequence\"] = () =>\n    listProjectionStateRows(undefined).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionSnapshotQuery.getSnapshotSequence:query\",\n          \"ProjectionSnapshotQuery.getSnapshotSequence:decodeRows\",\n        ),\n      ),\n      Effect.map((stateRows) => ({\n        snapshotSequence: computeSnapshotSequence(stateRows),\n      })),\n    );\n\n  const getCounts: ProjectionSnapshotQueryShape[\"getCounts\"] = () =>\n    readProjectionCounts(undefined).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionSnapshotQuery.getCounts:query\",\n          \"ProjectionSnapshotQuery.getCounts:decodeRow\",\n        ),\n      ),\n      Effect.map(\n        (row): ProjectionSnapshotCounts => ({\n          projectCount: row.projectCount,\n          threadCount: row.threadCount,\n        }),\n      ),\n    );\n\n  const searchThreads: ProjectionSnapshotQueryShape[\"searchThreads\"] = Effect.fn(\n    \"ProjectionSnapshotQuery.searchThreads\",\n  )(function* (input) {\n    const escapedQuery = escapeLikePattern(input.query);\n    const rows = yield* searchActiveThreadRows({\n      pattern: `%${escapedQuery}%`,\n      limit: input.limit ?? 50,\n    }).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionSnapshotQuery.searchThreads:query\",\n          \"ProjectionSnapshotQuery.searchThreads:decodeRows\",\n        ),\n      ),\n    );\n    return {\n      matches: rows.map((row) => ({\n        threadId: row.threadId,\n        projectId: row.projectId,\n        source: row.source,\n        snippet: buildSearchSnippet(row.matchText, input.query),\n        messageCreatedAt: row.messageCreatedAt,\n      })),\n    };\n  });\n\n  const getActiveProjectByWorkspaceRoot: ProjectionSnapshotQueryShape[\"getActiveProjectByWorkspaceRoot\"] =\n    (workspaceRoot) =>\n      getActiveProjectRowByWorkspaceRoot({ workspaceRoot }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:query\",\n            \"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow\",\n          ),\n        ),\n        Effect.flatMap((option) =>\n          Option.isNone(option)\n            ? Effect.succeed(Option.none<OrchestrationProject>())\n            : repositoryIdentityResolver.resolve(option.value.workspaceRoot).pipe(\n                Effect.map((repositoryIdentity) =>\n                  Option.some({\n                    id: option.value.projectId,\n                    title: option.value.title,\n                    workspaceRoot: option.value.workspaceRoot,\n                    repositoryIdentity,\n                    defaultModelSelection: option.value.defaultModelSelection,\n                    scripts: option.value.scripts,\n                    createdAt: option.value.createdAt,\n                    updatedAt: option.value.updatedAt,\n                    deletedAt: option.value.deletedAt,\n                  } satisfies OrchestrationProject),\n                ),\n              ),\n        ),\n      );\n\n  const getProjectShellById: ProjectionSnapshotQueryShape[\"getProjectShellById\"] = (projectId) =>\n    getActiveProjectRowById({ projectId }).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProjectionSnapshotQuery.getProjectShellById:query\",\n          \"ProjectionSnapshotQuery.getProjectShellById:decodeRow\",\n        ),\n      ),\n      Effect.flatMap((option) =>\n        Option.isNone(option)\n          ? Effect.succeed(Option.none<OrchestrationProjectShell>())\n          : repositoryIdentityResolver\n              .resolve(option.value.workspaceRoot)\n              .pipe(\n                Effect.map((repositoryIdentity) =>\n                  Option.some(mapProjectShellRow(option.value, repositoryIdentity)),\n                ),\n              ),\n      ),\n    );\n\n  const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape[\"getFirstActiveThreadIdByProjectId\"] =\n    (projectId) =>\n      getFirstActiveThreadIdByProject({ projectId }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:query\",\n            \"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:decodeRow\",\n          ),\n        ),\n        Effect.map(Option.map((row) => row.threadId)),\n      );\n\n  const getThreadCheckpointContext: ProjectionSnapshotQueryShape[\"getThreadCheckpointContext\"] = (\n    threadId,\n  ) =>\n    Effect.gen(function* () {\n      const threadRow = yield* getThreadCheckpointContextThreadRow({ threadId }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:query\",\n            \"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:decodeRow\",\n          ),\n        ),\n      );\n      if (Option.isNone(threadRow)) {\n        return Option.none<ProjectionThreadCheckpointContext>();\n      }\n\n      const checkpointRows = yield* listCheckpointRowsByThread({ threadId }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:query\",\n            \"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:decodeRows\",\n          ),\n        ),\n      );\n\n      return Option.some({\n        threadId: threadRow.value.threadId,\n        projectId: threadRow.value.projectId,\n        workspaceRoot: threadRow.value.workspaceRoot,\n        worktreePath: threadRow.value.worktreePath,\n        checkpoints: checkpointRows.map(\n          (row): OrchestrationCheckpointSummary => ({\n            turnId: row.turnId,\n            checkpointTurnCount: row.checkpointTurnCount,\n            checkpointRef: row.checkpointRef,\n            status: row.status,\n            files: row.files,\n            assistantMessageId: row.assistantMessageId,\n            completedAt: row.completedAt,\n          }),\n        ),\n      });\n    });\n\n  const getFullThreadDiffContext: NonNullable<\n    ProjectionSnapshotQueryShape[\"getFullThreadDiffContext\"]\n  > = (threadId, toTurnCount) =>\n    Effect.gen(function* () {\n      const row = yield* getFullThreadDiffContextRow({\n        threadId,\n        checkpointTurnCount: toTurnCount,\n      }).pipe(\n        Effect.mapError(\n          toPersistenceSqlOrDecodeError(\n            \"ProjectionSnapshotQuery.getFullThreadDiffContext:query\",\n            \"ProjectionSnapshotQuery.getFullThreadDiffContext:decodeRow\",\n          ),\n        ),\n      );\n      if (Option.isNone(row)) {\n        return Option.none<ProjectionFullThreadDiffContext>();\n      }\n\n      return Option.some({\n        threadId: row.value.threadId,\n        projectId: row.value.projectId,\n        workspaceRoot: row.value.workspaceRoot,\n        worktreePath: row.value.worktreePath,\n        latestCheckpointTurnCount: row.value.latestCheckpointTurnCount ?? 0,\n        toCheckpointRef: row.value.toCheckpointRef,\n      });\n    });\n\n  const getThreadShellById: ProjectionSnapshotQueryShape[\"getThreadShellById\"] = (threadId) =>\n    Effect.gen(function* () {\n      const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([\n        getActiveThreadRowById({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadShellById:getThread:query\",\n              \"ProjectionSnapshotQuery.getThreadShellById:getThread:decodeRow\",\n            ),\n          ),\n        ),\n        getLatestTurnRowByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:query\",\n              \"ProjectionSnapshotQuery.getThreadShellById:getLatestTurn:decodeRow\",\n            ),\n          ),\n        ),\n        getThreadSessionRowByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadShellById:getSession:query\",\n              \"ProjectionSnapshotQuery.getThreadShellById:getSession:decodeRow\",\n            ),\n          ),\n        ),\n      ]);\n\n      if (Option.isNone(threadRow)) {\n        return Option.none<OrchestrationThreadShell>();\n      }\n\n      return Option.some({\n        id: threadRow.value.threadId,\n        projectId: threadRow.value.projectId,\n        title: threadRow.value.title,\n        modelSelection: threadRow.value.modelSelection,\n        runtimeMode: threadRow.value.runtimeMode,\n        interactionMode: threadRow.value.interactionMode,\n        branch: threadRow.value.branch,\n        worktreePath: threadRow.value.worktreePath,\n        latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,\n        createdAt: threadRow.value.createdAt,\n        updatedAt: threadRow.value.updatedAt,\n        archivedAt: threadRow.value.archivedAt,\n        settledOverride: threadRow.value.settledOverride,\n        settledAt: threadRow.value.settledAt,\n        snoozedUntil: threadRow.value.snoozedUntil,\n        snoozedAt: threadRow.value.snoozedAt,\n        pinnedAt: threadRow.value.pinnedAt,\n        pinOrderKey: threadRow.value.pinOrderKey ?? null,\n        titleRegeneration: mapTitleRegeneration(threadRow.value),\n        session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,\n        latestUserMessageAt: threadRow.value.latestUserMessageAt,\n        hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,\n        hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,\n        hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,\n        backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(\n          threadRow.value.threadId,\n        ),\n        planProgress: threadPlanProgress.getThreadPlanProgress(threadRow.value.threadId),\n      } satisfies OrchestrationThreadShell);\n    });\n\n  // Contiguous turn range bounding a windowed detail read; undefined loads the\n  // full thread. Resolved from a window request inside the snapshot\n  // transaction (see getThreadDetailSnapshot).\n  interface ThreadDetailBounds {\n    readonly minAnchorAt: string;\n    readonly minTurnKey: string;\n    readonly beforeAnchorAt: string;\n    readonly beforeTurnKey: string;\n  }\n\n  const getThreadDetailByIdBounded = (threadId: ThreadId, bounds: ThreadDetailBounds | undefined) =>\n    Effect.gen(function* () {\n      const [\n        threadRow,\n        messageRows,\n        proposedPlanRows,\n        activityRows,\n        checkpointRows,\n        latestTurnRow,\n        sessionRow,\n      ] = yield* Effect.all([\n        getActiveThreadRowById({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:getThread:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:getThread:decodeRow\",\n            ),\n          ),\n        ),\n        (bounds === undefined\n          ? listThreadMessageRowsByThread({ threadId })\n          : listThreadMessageRowsByThreadWindow({ threadId, ...bounds })\n        ).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:listMessages:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:listMessages:decodeRows\",\n            ),\n          ),\n        ),\n        listThreadProposedPlanRowsByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:listPlans:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:listPlans:decodeRows\",\n            ),\n          ),\n        ),\n        (bounds === undefined\n          ? listThreadActivityRowsByThread({ threadId })\n          : listThreadActivityRowsByThreadWindow({ threadId, ...bounds })\n        ).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:listActivities:decodeRows\",\n            ),\n          ),\n        ),\n        listCheckpointRowsByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:listCheckpoints:decodeRows\",\n            ),\n          ),\n        ),\n        getLatestTurnRowByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:getLatestTurn:decodeRow\",\n            ),\n          ),\n        ),\n        getThreadSessionRowByThread({ threadId }).pipe(\n          Effect.mapError(\n            toPersistenceSqlOrDecodeError(\n              \"ProjectionSnapshotQuery.getThreadDetailById:getSession:query\",\n              \"ProjectionSnapshotQuery.getThreadDetailById:getSession:decodeRow\",\n            ),\n          ),\n        ),\n      ]);\n\n      if (Option.isNone(threadRow)) {\n        return Option.none<OrchestrationThread>();\n      }\n\n      const thread = {\n        id: threadRow.value.threadId,\n        projectId: threadRow.value.projectId,\n        title: threadRow.value.title,\n        modelSelection: threadRow.value.modelSelection,\n        runtimeMode: threadRow.value.runtimeMode,\n        interactionMode: threadRow.value.interactionMode,\n        branch: threadRow.value.branch,\n        worktreePath: threadRow.value.worktreePath,\n        latestTurn: Option.isSome(latestTurnRow) ? mapLatestTurn(latestTurnRow.value) : null,\n        createdAt: threadRow.value.createdAt,\n        updatedAt: threadRow.value.updatedAt,\n        archivedAt: threadRow.value.archivedAt,\n        settledOverride: threadRow.value.settledOverride,\n        settledAt: threadRow.value.settledAt,\n        snoozedUntil: threadRow.value.snoozedUntil,\n        snoozedAt: threadRow.value.snoozedAt,\n        pinnedAt: threadRow.value.pinnedAt,\n        pinOrderKey: threadRow.value.pinOrderKey ?? null,\n        titleRegeneration: mapTitleRegeneration(threadRow.value),\n        deletedAt: null,\n        messages: messageRows.map((row) => {\n          const message = {\n            id: row.messageId,\n            role: row.role,\n            text: row.text,\n            turnId: row.turnId,\n            streaming: row.isStreaming === 1,\n            createdAt: row.createdAt,\n            updatedAt: row.updatedAt,\n          };\n          if (row.attachments !== null) {\n            return Object.assign(message, { attachments: row.attachments });\n          }\n          return message;\n        }),\n        proposedPlans: proposedPlanRows.map(mapProposedPlanRow),\n        activities: activityRows.map((row) => {\n          const activity = {\n            id: row.activityId,\n            tone: row.tone,\n            kind: row.kind,\n            summary: row.summary,\n            payload: row.payload,\n            turnId: row.turnId,\n            createdAt: row.createdAt,\n          };\n          if (row.sequence !== null) {\n            return Object.assign(activity, { sequence: row.sequence });\n          }\n          return activity;\n        }),\n        checkpoints: checkpointRows.map((row) => ({\n          turnId: row.turnId,\n          checkpointTurnCount: row.checkpointTurnCount,\n          checkpointRef: row.checkpointRef,\n          status: row.status,\n          files: row.files,\n          assistantMessageId: row.assistantMessageId,\n          completedAt: row.completedAt,\n        })),\n        session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,\n      };\n\n      return Option.some(\n        yield* decodeThread(thread).pipe(\n          Effect.mapError(\n            toPersistenceDecodeError(\"ProjectionSnapshotQuery.getThreadDetailById:decodeThread\"),\n          ),\n        ),\n      );\n    });\n\n  const getThreadDetailById: ProjectionSnapshotQueryShape[\"getThreadDetailById\"] = (threadId) =>\n    getThreadDetailByIdBounded(threadId, undefined);\n\n  // Bounds pathological fan-out: one user turn that spawned hundreds of\n  // subagent turns still pages in bounded chunks, at the cost of splitting the\n  // fan-out group across pages (the cursor continues the same group). Also\n  // structurally bounds the window scan via the candidates CTE's LIMIT.\n  const THREAD_DETAIL_MAX_RAW_TURNS_PER_PAGE = 150;\n  // Sentinels for unbounded keyset ends; \"~\" sorts after any ISO timestamp.\n  const ANCHOR_UNBOUNDED = \"~\";\n\n  const getThreadDetailSnapshot: ProjectionSnapshotQueryShape[\"getThreadDetailSnapshot\"] = (\n    threadId,\n    window,\n  ) =>\n    // Read the thread detail and the snapshot sequence within a single\n    // transaction so the sequence is consistent with the returned state; a\n    // projector update landing between two separate reads could otherwise return\n    // a sequence ahead of the thread detail, causing the client to resume from\n    // too far and drop events. Window resolution runs inside the same\n    // transaction so the page boundary is consistent with the returned rows.\n    sql\n      .withTransaction(\n        Effect.gen(function* () {\n          if (window?.turnLimit === undefined) {\n            const thread = yield* getThreadDetailById(threadId);\n            if (Option.isNone(thread)) {\n              return Option.none<OrchestrationThreadDetailSnapshot>();\n            }\n            const { snapshotSequence } = yield* getSnapshotSequence();\n            return Option.some({ snapshotSequence, thread: thread.value });\n          }\n\n          // A malformed or foreign-thread cursor falls back to the first page\n          // rather than failing: the client's stale cursor after a revert or\n          // reconnect should degrade to \"reload recent history\", not error.\n          const decodedCursor =\n            window.beforeCursor === undefined\n              ? null\n              : decodeThreadDetailPageCursor(window.beforeCursor);\n          const cursor = decodedCursor?.threadId === threadId ? decodedCursor : null;\n\n          const windowRows = yield* listTurnWindowRows({\n            threadId,\n            beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,\n            beforeTurnKey: cursor?.beforeTurnId ?? \"\",\n            userTurnLimit: window.turnLimit,\n            maxRawTurns: THREAD_DETAIL_MAX_RAW_TURNS_PER_PAGE,\n          }).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getThreadDetailSnapshot:listTurnWindow:query\",\n                \"ProjectionSnapshotQuery.getThreadDetailSnapshot:listTurnWindow:decodeRows\",\n              ),\n            ),\n          );\n\n          const oldest = windowRows[0];\n          // An empty window (no turns before the cursor, or a thread with no\n          // turns at all) still returns thread metadata with empty collections\n          // for turn-linked rows; turnless rows are bounded to the same empty\n          // range. The first page of a turnless thread stays unwindowed so\n          // pre-turn content (e.g. a just-created thread) is not hidden.\n          const bounds: ThreadDetailBounds | undefined =\n            oldest === undefined && cursor === null\n              ? undefined\n              : {\n                  minAnchorAt: oldest?.anchorAt ?? \"\",\n                  minTurnKey: oldest?.turnKey ?? \"\",\n                  beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,\n                  beforeTurnKey: cursor?.beforeTurnId ?? \"\",\n                };\n          // Empty window behind a cursor: nothing older remains.\n          const emptyBounds =\n            oldest === undefined && cursor !== null\n              ? { minAnchorAt: \"\", minTurnKey: \"\", beforeAnchorAt: \"\", beforeTurnKey: \"\" }\n              : undefined;\n\n          const thread = yield* getThreadDetailByIdBounded(threadId, emptyBounds ?? bounds);\n          if (Option.isNone(thread)) {\n            return Option.none<OrchestrationThreadDetailSnapshot>();\n          }\n\n          const hasMore =\n            oldest !== undefined &&\n            (yield* listTurnWindowRows({\n              threadId,\n              beforeAnchorAt: oldest.anchorAt,\n              beforeTurnKey: oldest.turnKey,\n              userTurnLimit: 1,\n              maxRawTurns: 1,\n            }).pipe(\n              Effect.mapError(\n                toPersistenceSqlOrDecodeError(\n                  \"ProjectionSnapshotQuery.getThreadDetailSnapshot:probeOlder:query\",\n                  \"ProjectionSnapshotQuery.getThreadDetailSnapshot:probeOlder:decodeRows\",\n                ),\n              ),\n            )).length > 0;\n\n          const { snapshotSequence } = yield* getSnapshotSequence();\n          const watermarkRow = yield* getThreadEventWatermarkRow({\n            threadId,\n            maxSequence: snapshotSequence,\n          }).pipe(\n            Effect.mapError(\n              toPersistenceSqlOrDecodeError(\n                \"ProjectionSnapshotQuery.getThreadDetailSnapshot:threadWatermark:query\",\n                \"ProjectionSnapshotQuery.getThreadDetailSnapshot:threadWatermark:decodeRow\",\n              ),\n            ),\n          );\n          const threadSequence = Option.match(watermarkRow, {\n            onNone: () => 0,\n            onSome: (row) => row.threadSequence ?? 0,\n          });\n          return Option.some({\n            snapshotSequence,\n            thread: thread.value,\n            page: {\n              beforeCursor:\n                hasMore && oldest !== undefined\n                  ? encodeThreadDetailPageCursor({\n                      threadId,\n                      beforeAnchorAt: oldest.anchorAt,\n                      beforeTurnId: oldest.turnKey,\n                    })\n                  : null,\n              hasMore,\n              snapshotSequence,\n              threadSequence,\n            },\n          });\n        }),\n      )\n      .pipe(\n        Effect.mapError((error) =>\n          isPersistenceError(error)\n            ? error\n            : toPersistenceSqlError(\"ProjectionSnapshotQuery.getThreadDetailSnapshot:transaction\")(\n                error,\n              ),\n        ),\n      );\n\n  return {\n    getCommandReadModel,\n    getSnapshot,\n    getShellSnapshot,\n    getArchivedShellSnapshot,\n    searchThreads,\n    getSnapshotSequence,\n    getCounts,\n    getActiveProjectByWorkspaceRoot,\n    getProjectShellById,\n    getFirstActiveThreadIdByProjectId,\n    getThreadCheckpointContext,\n    getFullThreadDiffContext,\n    getThreadShellById,\n    getThreadDetailById,\n    getThreadDetailSnapshot,\n  } satisfies ProjectionSnapshotQueryShape;\n});\n\nexport const OrchestrationProjectionSnapshotQueryLive = Layer.effect(\n  ProjectionSnapshotQuery,\n  makeProjectionSnapshotQuery,\n);\n","import * as Layer from \"effect/Layer\";\n\nimport { OrchestrationCommandReceiptRepositoryLive } from \"../persistence/Layers/OrchestrationCommandReceipts.ts\";\nimport { OrchestrationEventStoreLive } from \"../persistence/Layers/OrchestrationEventStore.ts\";\nimport { OrchestrationEngineLive } from \"./Layers/OrchestrationEngine.ts\";\nimport { OrchestrationProjectionPipelineLive } from \"./Layers/ProjectionPipeline.ts\";\nimport { OrchestrationProjectionSnapshotQueryLive } from \"./Layers/ProjectionSnapshotQuery.ts\";\nimport * as ThreadBackgroundLiveness from \"./ThreadBackgroundLiveness.ts\";\nimport * as ThreadPlanProgress from \"./ThreadPlanProgress.ts\";\n\nexport const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(\n  OrchestrationEventStoreLive,\n  OrchestrationCommandReceiptRepositoryLive,\n);\n\nexport const OrchestrationProjectionPipelineLayerLive = OrchestrationProjectionPipelineLive.pipe(\n  Layer.provide(OrchestrationEventStoreLive),\n);\n\nexport const OrchestrationInfrastructureLayerLive = Layer.mergeAll(\n  OrchestrationProjectionSnapshotQueryLive,\n  OrchestrationEventInfrastructureLayerLive,\n  OrchestrationProjectionPipelineLayerLive,\n  // Shared background-liveness and plan-progress registries: written by\n  // runtime ingestion, read by the snapshot query. provideMerge feeds the\n  // same instance to the snapshot query here and re-exports it for runtime\n  // ingestion.\n).pipe(\n  Layer.provideMerge(ThreadBackgroundLiveness.layer),\n  Layer.provideMerge(ThreadPlanProgress.layer),\n);\n\nexport const OrchestrationLayerLive = Layer.mergeAll(\n  OrchestrationInfrastructureLayerLive,\n  OrchestrationEngineLive.pipe(Layer.provide(OrchestrationInfrastructureLayerLive)),\n);\n","import {\n  type KeybindingRule,\n  type KeybindingShortcut,\n  type KeybindingWhenNode,\n  MAX_KEYBINDINGS_COUNT,\n  MAX_WHEN_EXPRESSION_DEPTH,\n  MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,\n  type ResolvedKeybindingRule,\n  type ResolvedKeybindingsConfig,\n  THREAD_JUMP_KEYBINDING_COMMANDS,\n} from \"@t3tools/contracts\";\n\ntype WhenToken =\n  | { type: \"identifier\"; value: string }\n  | { type: \"not\" }\n  | { type: \"and\" }\n  | { type: \"or\" }\n  | { type: \"lparen\" }\n  | { type: \"rparen\" };\n\nexport const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [\n  { key: \"mod+b\", command: \"sidebar.toggle\" },\n  { key: \"mod+j\", command: \"terminal.toggle\" },\n  { key: \"mod+alt+b\", command: \"rightPanel.toggle\" },\n  { key: \"mod+d\", command: \"terminal.split\", when: \"terminalFocus\" },\n  { key: \"mod+shift+d\", command: \"terminal.splitVertical\", when: \"terminalFocus\" },\n  { key: \"mod+n\", command: \"terminal.new\", when: \"terminalFocus\" },\n  { key: \"mod+w\", command: \"terminal.close\", when: \"terminalFocus\" },\n  { key: \"mod+d\", command: \"diff.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+j\", command: \"preview.toggle\" },\n  { key: \"mod+r\", command: \"preview.refresh\", when: \"previewFocus\" },\n  { key: \"mod+l\", command: \"preview.focusUrl\", when: \"previewFocus\" },\n  { key: \"mod+=\", command: \"preview.zoomIn\", when: \"previewFocus\" },\n  { key: \"mod++\", command: \"preview.zoomIn\", when: \"previewFocus\" },\n  { key: \"mod+-\", command: \"preview.zoomOut\", when: \"previewFocus\" },\n  { key: \"mod+0\", command: \"preview.resetZoom\", when: \"previewFocus\" },\n  { key: \"mod+k\", command: \"commandPalette.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+p\", command: \"filePicker.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+f\", command: \"projectSearch.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+alt+shift+t\", command: \"themeEditor.toggle\" },\n  { key: \"mod+s\", command: \"composer.stash\", when: \"!terminalFocus\" },\n  { key: \"mod+n\", command: \"chat.new\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+o\", command: \"chat.new\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+n\", command: \"chat.newLocal\", when: \"!terminalFocus\" },\n  { key: \"mod+shift+m\", command: \"modelPicker.toggle\", when: \"!terminalFocus\" },\n  { key: \"mod+o\", command: \"editor.openFavorite\" },\n  { key: \"mod+shift+[\", command: \"thread.previous\" },\n  { key: \"mod+shift+]\", command: \"thread.next\" },\n  ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({\n    key: `mod+${index + 1}`,\n    command,\n  })),\n  ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({\n    key: `mod+${index + 1}`,\n    command,\n    when: \"modelPickerOpen\",\n  })),\n];\n\nfunction normalizeKeyToken(token: string): string {\n  if (token === \"space\") return \" \";\n  if (token === \"esc\") return \"escape\";\n  return token;\n}\n\nexport function parseKeybindingShortcut(value: string): KeybindingShortcut | null {\n  const rawTokens = value\n    .toLowerCase()\n    .split(\"+\")\n    .map((token) => token.trim());\n  const tokens = [...rawTokens];\n  let trailingEmptyCount = 0;\n  while (tokens[tokens.length - 1] === \"\") {\n    trailingEmptyCount += 1;\n    tokens.pop();\n  }\n  if (trailingEmptyCount > 0) {\n    tokens.push(\"+\");\n  }\n  if (tokens.some((token) => token.length === 0)) {\n    return null;\n  }\n  if (tokens.length === 0) return null;\n\n  let key: string | null = null;\n  let metaKey = false;\n  let ctrlKey = false;\n  let shiftKey = false;\n  let altKey = false;\n  let modKey = false;\n\n  for (const token of tokens) {\n    switch (token) {\n      case \"cmd\":\n      case \"meta\":\n        metaKey = true;\n        break;\n      case \"ctrl\":\n      case \"control\":\n        ctrlKey = true;\n        break;\n      case \"shift\":\n        shiftKey = true;\n        break;\n      case \"alt\":\n      case \"option\":\n        altKey = true;\n        break;\n      case \"mod\":\n        modKey = true;\n        break;\n      default: {\n        if (key !== null) return null;\n        key = normalizeKeyToken(token);\n      }\n    }\n  }\n\n  if (key === null) return null;\n  return {\n    key,\n    metaKey,\n    ctrlKey,\n    shiftKey,\n    altKey,\n    modKey,\n  };\n}\n\nfunction tokenizeWhenExpression(expression: string): WhenToken[] | null {\n  const tokens: WhenToken[] = [];\n  let index = 0;\n\n  while (index < expression.length) {\n    const current = expression[index];\n    if (!current) break;\n\n    if (/\\s/.test(current)) {\n      index += 1;\n      continue;\n    }\n    if (expression.startsWith(\"&&\", index)) {\n      tokens.push({ type: \"and\" });\n      index += 2;\n      continue;\n    }\n    if (expression.startsWith(\"||\", index)) {\n      tokens.push({ type: \"or\" });\n      index += 2;\n      continue;\n    }\n    if (current === \"!\") {\n      tokens.push({ type: \"not\" });\n      index += 1;\n      continue;\n    }\n    if (current === \"(\") {\n      tokens.push({ type: \"lparen\" });\n      index += 1;\n      continue;\n    }\n    if (current === \")\") {\n      tokens.push({ type: \"rparen\" });\n      index += 1;\n      continue;\n    }\n\n    const identifier = /^[A-Za-z_][A-Za-z0-9_.-]*/.exec(expression.slice(index));\n    if (!identifier) {\n      return null;\n    }\n    tokens.push({ type: \"identifier\", value: identifier[0] });\n    index += identifier[0].length;\n  }\n\n  return tokens;\n}\n\nexport function parseKeybindingWhenExpression(expression: string): KeybindingWhenNode | null {\n  const tokens = tokenizeWhenExpression(expression);\n  if (!tokens || tokens.length === 0) return null;\n  let index = 0;\n\n  const parsePrimary = (depth: number): KeybindingWhenNode | null => {\n    if (depth > MAX_WHEN_EXPRESSION_DEPTH) {\n      return null;\n    }\n    const token = tokens[index];\n    if (!token) return null;\n\n    if (token.type === \"identifier\") {\n      index += 1;\n      return { type: \"identifier\", name: token.value };\n    }\n\n    if (token.type === \"lparen\") {\n      index += 1;\n      const expressionNode = parseOr(depth + 1);\n      const closeToken = tokens[index];\n      if (!expressionNode || !closeToken || closeToken.type !== \"rparen\") {\n        return null;\n      }\n      index += 1;\n      return expressionNode;\n    }\n\n    return null;\n  };\n\n  const parseUnary = (depth: number): KeybindingWhenNode | null => {\n    let notCount = 0;\n    while (tokens[index]?.type === \"not\") {\n      index += 1;\n      notCount += 1;\n      if (notCount > MAX_WHEN_EXPRESSION_DEPTH) {\n        return null;\n      }\n    }\n\n    let node = parsePrimary(depth);\n    if (!node) return null;\n\n    while (notCount > 0) {\n      node = { type: \"not\", node };\n      notCount -= 1;\n    }\n\n    return node;\n  };\n\n  const parseAnd = (depth: number): KeybindingWhenNode | null => {\n    let left = parseUnary(depth);\n    if (!left) return null;\n\n    while (tokens[index]?.type === \"and\") {\n      index += 1;\n      const right = parseUnary(depth);\n      if (!right) return null;\n      left = { type: \"and\", left, right };\n    }\n\n    return left;\n  };\n\n  const parseOr = (depth: number): KeybindingWhenNode | null => {\n    let left = parseAnd(depth);\n    if (!left) return null;\n\n    while (tokens[index]?.type === \"or\") {\n      index += 1;\n      const right = parseAnd(depth);\n      if (!right) return null;\n      left = { type: \"or\", left, right };\n    }\n\n    return left;\n  };\n\n  const ast = parseOr(0);\n  if (!ast || index !== tokens.length) return null;\n  return ast;\n}\n\nexport function compileResolvedKeybindingRule(rule: KeybindingRule): ResolvedKeybindingRule | null {\n  const shortcut = parseKeybindingShortcut(rule.key);\n  if (!shortcut) return null;\n\n  if (rule.when !== undefined) {\n    const whenAst = parseKeybindingWhenExpression(rule.when);\n    if (!whenAst) return null;\n    return {\n      command: rule.command,\n      shortcut,\n      whenAst,\n    };\n  }\n\n  return {\n    command: rule.command,\n    shortcut,\n  };\n}\n\nexport function compileResolvedKeybindingsConfig(\n  config: ReadonlyArray<KeybindingRule>,\n): ResolvedKeybindingsConfig {\n  const compiled: ResolvedKeybindingRule[] = [];\n  for (const rule of config) {\n    const result = compileResolvedKeybindingRule(rule);\n    if (result) {\n      compiled.push(result);\n    }\n  }\n  return compiled.slice(-MAX_KEYBINDINGS_COUNT);\n}\n\nexport const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);\n","/**\n * Keybindings - Keybinding configuration service definitions.\n *\n * Owns parsing, validation, merge, and persistence of user keybinding\n * configuration consumed by the server runtime.\n *\n * @module Keybindings\n */\nimport {\n  KeybindingRule,\n  KeybindingsConfig,\n  KeybindingsConfigError,\n  KeybindingShortcut,\n  KeybindingWhenNode,\n  MAX_KEYBINDINGS_COUNT,\n  ResolvedKeybindingRule,\n  ResolvedKeybindingsConfig,\n  type ServerRemoveKeybindingInput,\n  type ServerUpsertKeybindingInput,\n  type ServerConfigIssue,\n} from \"@t3tools/contracts\";\nimport * as Array from \"effect/Array\";\nimport * as Cache from \"effect/Cache\";\nimport * as Cause from \"effect/Cause\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Layer from \"effect/Layer\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as SchemaTransformation from \"effect/SchemaTransformation\";\nimport * as Ref from \"effect/Ref\";\nimport * as Context from \"effect/Context\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as ServerConfig from \"./config.ts\";\nimport { writeFileStringAtomically } from \"./atomicWrite.ts\";\nimport { fromJsonStringPretty, fromLenientJson } from \"@t3tools/shared/schemaJson\";\nimport {\n  DEFAULT_KEYBINDINGS,\n  DEFAULT_RESOLVED_KEYBINDINGS,\n  compileResolvedKeybindingRule,\n  compileResolvedKeybindingsConfig,\n  parseKeybindingShortcut,\n} from \"@t3tools/shared/keybindings\";\n\nexport {\n  DEFAULT_KEYBINDINGS,\n  compileResolvedKeybindingRule,\n  compileResolvedKeybindingsConfig,\n  parseKeybindingShortcut,\n};\n\nexport const ResolvedKeybindingFromConfig = KeybindingRule.pipe(\n  Schema.decodeTo(\n    Schema.toType(ResolvedKeybindingRule),\n    SchemaTransformation.transformOrFail({\n      decode: (rule) =>\n        Effect.succeed(compileResolvedKeybindingRule(rule)).pipe(\n          Effect.filterOrFail(\n            Predicate.isNotNull,\n            () =>\n              new SchemaIssue.InvalidValue({\n                message: \"Invalid keybinding rule\",\n              }),\n          ),\n          Effect.map((resolved) => resolved),\n        ),\n\n      encode: (resolved) =>\n        Effect.gen(function* () {\n          const key = encodeShortcut(resolved.shortcut);\n          if (!key) {\n            return yield* Effect.fail(\n              new SchemaIssue.InvalidValue({\n                message: \"Resolved shortcut cannot be encoded to key string\",\n              }),\n            );\n          }\n\n          const when = resolved.whenAst ? encodeWhenAst(resolved.whenAst) : undefined;\n          return {\n            key,\n            command: resolved.command,\n            when,\n          };\n        }),\n    }),\n  ),\n);\n\nexport const ResolvedKeybindingsFromConfig = Schema.Array(ResolvedKeybindingFromConfig).check(\n  Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),\n);\n\nfunction isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean {\n  return (\n    left.command === right.command &&\n    left.key === right.key &&\n    (left.when ?? undefined) === (right.when ?? undefined)\n  );\n}\n\nfunction keybindingShortcutContext(rule: KeybindingRule): string | null {\n  const parsed = parseKeybindingShortcut(rule.key);\n  if (!parsed) return null;\n  const encoded = encodeShortcut(parsed);\n  if (!encoded) return null;\n  return `${encoded}\\u0000${rule.when ?? \"\"}`;\n}\n\nfunction hasSameShortcutContext(left: KeybindingRule, right: KeybindingRule): boolean {\n  const leftContext = keybindingShortcutContext(left);\n  const rightContext = keybindingShortcutContext(right);\n  if (!leftContext || !rightContext) return false;\n  return leftContext === rightContext;\n}\n\nfunction keybindingRuleFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule {\n  return input.when === undefined\n    ? { key: input.key, command: input.command }\n    : { key: input.key, command: input.command, when: input.when };\n}\n\nfunction replaceTargetFromUpsertInput(input: ServerUpsertKeybindingInput): KeybindingRule | null {\n  if (!input.replace) return null;\n  return input.replace.when === undefined\n    ? { key: input.replace.key, command: input.replace.command }\n    : { key: input.replace.key, command: input.replace.command, when: input.replace.when };\n}\n\nfunction keybindingRuleFromRemoveInput(input: ServerRemoveKeybindingInput): KeybindingRule {\n  return input.when === undefined\n    ? { key: input.key, command: input.command }\n    : { key: input.key, command: input.command, when: input.when };\n}\n\nfunction encodeShortcut(shortcut: KeybindingShortcut): string | null {\n  const modifiers: string[] = [];\n  if (shortcut.modKey) modifiers.push(\"mod\");\n  if (shortcut.metaKey) modifiers.push(\"meta\");\n  if (shortcut.ctrlKey) modifiers.push(\"ctrl\");\n  if (shortcut.altKey) modifiers.push(\"alt\");\n  if (shortcut.shiftKey) modifiers.push(\"shift\");\n  if (!shortcut.key) return null;\n  if (shortcut.key !== \"+\" && shortcut.key.includes(\"+\")) return null;\n  const key = shortcut.key === \" \" ? \"space\" : shortcut.key;\n  return [...modifiers, key].join(\"+\");\n}\n\nfunction encodeWhenAst(node: KeybindingWhenNode): string {\n  switch (node.type) {\n    case \"identifier\":\n      return node.name;\n    case \"not\":\n      return `!(${encodeWhenAst(node.node)})`;\n    case \"and\":\n      return `(${encodeWhenAst(node.left)} && ${encodeWhenAst(node.right)})`;\n    case \"or\":\n      return `(${encodeWhenAst(node.left)} || ${encodeWhenAst(node.right)})`;\n  }\n}\n\nconst RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));\nconst KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);\nconst decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);\nconst decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);\nconst decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);\nconst encodeKeybindingsConfigPrettyJson = Schema.encodeEffect(KeybindingsConfigPrettyJson);\n\nexport interface KeybindingsConfigState {\n  readonly keybindings: ResolvedKeybindingsConfig;\n  readonly issues: readonly ServerConfigIssue[];\n}\n\nexport interface KeybindingsChangeEvent {\n  readonly keybindings: ResolvedKeybindingsConfig;\n  readonly issues: readonly ServerConfigIssue[];\n}\n\nfunction trimIssueMessage(message: string): string {\n  const trimmed = message.trim();\n  return trimmed.length > 0 ? trimmed : \"Invalid keybindings configuration.\";\n}\n\nfunction malformedConfigIssue(detail: string): ServerConfigIssue {\n  return {\n    kind: \"keybindings.malformed-config\",\n    message: trimIssueMessage(detail),\n  };\n}\n\nfunction invalidEntryIssue(index: number, detail: string): ServerConfigIssue {\n  return {\n    kind: \"keybindings.invalid-entry\",\n    index,\n    message: trimIssueMessage(detail),\n  };\n}\n\nfunction mergeWithDefaultKeybindings(custom: ResolvedKeybindingsConfig): ResolvedKeybindingsConfig {\n  if (custom.length === 0) {\n    return [...DEFAULT_RESOLVED_KEYBINDINGS];\n  }\n\n  const overriddenCommands = new Set(custom.map((binding) => binding.command));\n  const retainedDefaults = DEFAULT_RESOLVED_KEYBINDINGS.filter(\n    (binding) => !overriddenCommands.has(binding.command),\n  );\n  const merged = [...retainedDefaults, ...custom];\n\n  if (merged.length <= MAX_KEYBINDINGS_COUNT) {\n    return merged;\n  }\n\n  // Keep the latest rules when the config exceeds max size; later rules have higher precedence.\n  return merged.slice(-MAX_KEYBINDINGS_COUNT);\n}\n\n/**\n * Keybindings - Service tag for keybinding configuration operations.\n */\nexport class Keybindings extends Context.Service<\n  Keybindings,\n  {\n    /**\n     * Start the keybindings runtime and attach file watching.\n     *\n     * Safe to call multiple times. The first successful call establishes the\n     * runtime; later calls await the same startup.\n     */\n    readonly start: Effect.Effect<void, KeybindingsConfigError>;\n\n    /**\n     * Await keybindings runtime readiness.\n     *\n     * Readiness means the config directory exists, the watcher is attached, the\n     * startup sync has completed, and the current snapshot has been loaded.\n     */\n    readonly ready: Effect.Effect<void, KeybindingsConfigError>;\n\n    /**\n     * Ensure the on-disk keybindings file exists and includes all default\n     * commands so newly-added defaults are backfilled on startup.\n     */\n    readonly syncDefaultKeybindingsOnStartup: Effect.Effect<void, KeybindingsConfigError>;\n\n    /**\n     * Load runtime keybindings state along with non-fatal configuration issues.\n     */\n    readonly loadConfigState: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;\n\n    /**\n     * Read the latest keybindings snapshot from cache/disk.\n     */\n    readonly getSnapshot: Effect.Effect<KeybindingsConfigState, KeybindingsConfigError>;\n\n    /**\n     * Stream of keybindings config change events.\n     */\n    readonly streamChanges: Stream.Stream<KeybindingsChangeEvent>;\n\n    /**\n     * Upsert a keybinding rule and persist the resulting configuration.\n     *\n     * Writes config atomically and enforces the max rule count by truncating\n     * oldest entries when needed.\n     */\n    readonly upsertKeybindingRule: (\n      input: ServerUpsertKeybindingInput,\n    ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;\n\n    /**\n     * Remove a single persisted keybinding rule by exact key/command/when match.\n     */\n    readonly removeKeybindingRule: (\n      input: ServerRemoveKeybindingInput,\n    ) => Effect.Effect<ResolvedKeybindingsConfig, KeybindingsConfigError>;\n  }\n>()(\"t3/keybindings\") {}\n\nconst make = Effect.gen(function* () {\n  const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const upsertSemaphore = yield* Semaphore.make(1);\n  const resolvedConfigCacheKey = \"resolved\" as const;\n  const changesPubSub = yield* PubSub.unbounded<KeybindingsChangeEvent>();\n  const startedRef = yield* Ref.make(false);\n  const startedDeferred = yield* Deferred.make<void, KeybindingsConfigError>();\n  const watcherScope = yield* Scope.make(\"sequential\");\n  yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));\n  const emitChange = (configState: KeybindingsConfigState) =>\n    PubSub.publish(changesPubSub, configState).pipe(Effect.asVoid);\n\n  const readConfigExists = fs.exists(keybindingsConfigPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new KeybindingsConfigError({\n          configPath: keybindingsConfigPath,\n          detail: \"failed to access keybindings config\",\n          cause,\n        }),\n    ),\n  );\n\n  const readRawConfig = fs.readFileString(keybindingsConfigPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new KeybindingsConfigError({\n          configPath: keybindingsConfigPath,\n          detail: \"failed to read keybindings config\",\n          cause,\n        }),\n    ),\n  );\n\n  const loadWritableCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<\n    readonly KeybindingRule[],\n    KeybindingsConfigError\n  > {\n    if (!(yield* readConfigExists)) {\n      return [];\n    }\n\n    const rawConfig = yield* readRawConfig.pipe(\n      Effect.flatMap(Schema.decodeEffect(RawKeybindingsEntries)),\n      Effect.mapError(\n        (cause) =>\n          new KeybindingsConfigError({\n            configPath: keybindingsConfigPath,\n            detail: \"expected JSON array\",\n            cause,\n          }),\n      ),\n    );\n\n    return yield* Effect.forEach(rawConfig, (entry) =>\n      Effect.gen(function* () {\n        const decodedRule = decodeKeybindingRuleExit(entry);\n        if (decodedRule._tag === \"Failure\") {\n          yield* Effect.logWarning(\"ignoring invalid keybinding entry\", {\n            path: keybindingsConfigPath,\n            entry,\n            error: Cause.pretty(decodedRule.cause),\n          });\n          return null;\n        }\n        const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);\n        if (resolved._tag === \"Failure\") {\n          yield* Effect.logWarning(\"ignoring invalid keybinding entry\", {\n            path: keybindingsConfigPath,\n            entry,\n            error: Cause.pretty(resolved.cause),\n          });\n          return null;\n        }\n        return decodedRule.value;\n      }),\n    ).pipe(Effect.map(Array.filter(Predicate.isNotNull)));\n  });\n\n  const loadRuntimeCustomKeybindingsConfig = Effect.fn(function* (): Effect.fn.Return<\n    {\n      readonly keybindings: readonly KeybindingRule[];\n      readonly issues: readonly ServerConfigIssue[];\n    },\n    KeybindingsConfigError\n  > {\n    if (!(yield* readConfigExists)) {\n      return { keybindings: [], issues: [] };\n    }\n\n    const rawConfig = yield* readRawConfig;\n    const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);\n    if (decodedEntries._tag === \"Failure\") {\n      const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;\n      return {\n        keybindings: [],\n        issues: [malformedConfigIssue(detail)],\n      };\n    }\n\n    const keybindings: KeybindingRule[] = [];\n    const issues: ServerConfigIssue[] = [];\n    for (const [index, entry] of decodedEntries.value.entries()) {\n      const decodedRule = decodeKeybindingRuleExit(entry);\n      if (decodedRule._tag === \"Failure\") {\n        const detail = Cause.pretty(decodedRule.cause);\n        issues.push(invalidEntryIssue(index, detail));\n        yield* Effect.logWarning(\"ignoring invalid keybinding entry\", {\n          path: keybindingsConfigPath,\n          index,\n          entry,\n          error: detail,\n        });\n        continue;\n      }\n\n      const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);\n      if (resolvedRule._tag === \"Failure\") {\n        const detail = Cause.pretty(resolvedRule.cause);\n        issues.push(invalidEntryIssue(index, detail));\n        yield* Effect.logWarning(\"ignoring invalid keybinding entry\", {\n          path: keybindingsConfigPath,\n          index,\n          entry,\n          error: detail,\n        });\n        continue;\n      }\n      keybindings.push(decodedRule.value);\n    }\n\n    return { keybindings, issues };\n  });\n\n  const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {\n    return encodeKeybindingsConfigPrettyJson(rules).pipe(\n      Effect.map((encoded) => `${encoded}\\n`),\n      Effect.flatMap((encoded) =>\n        writeFileStringAtomically({\n          filePath: keybindingsConfigPath,\n          contents: encoded,\n        }).pipe(\n          Effect.provideService(FileSystem.FileSystem, fs),\n          Effect.provideService(Path.Path, path),\n        ),\n      ),\n      Effect.mapError(\n        (cause) =>\n          new KeybindingsConfigError({\n            configPath: keybindingsConfigPath,\n            detail: \"failed to write keybindings config\",\n            cause,\n          }),\n      ),\n    );\n  };\n\n  const loadConfigStateFromDisk = loadRuntimeCustomKeybindingsConfig().pipe(\n    Effect.map(({ keybindings, issues }) => ({\n      keybindings: mergeWithDefaultKeybindings(compileResolvedKeybindingsConfig(keybindings)),\n      issues,\n    })),\n  );\n\n  const resolvedConfigCache = yield* Cache.make<\n    typeof resolvedConfigCacheKey,\n    KeybindingsConfigState,\n    KeybindingsConfigError\n  >({\n    capacity: 1,\n    lookup: () => loadConfigStateFromDisk,\n  });\n\n  const loadConfigStateFromCacheOrDisk = Cache.get(resolvedConfigCache, resolvedConfigCacheKey);\n\n  const revalidateAndEmit = upsertSemaphore.withPermits(1)(\n    Effect.gen(function* () {\n      yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n      const configState = yield* loadConfigStateFromCacheOrDisk;\n      yield* emitChange(configState);\n    }),\n  );\n\n  const syncDefaultKeybindingsOnStartup = upsertSemaphore.withPermits(1)(\n    Effect.gen(function* () {\n      const configExists = yield* readConfigExists;\n      if (!configExists) {\n        yield* writeConfigAtomically(DEFAULT_KEYBINDINGS);\n        yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n        return;\n      }\n\n      const runtimeConfig = yield* loadRuntimeCustomKeybindingsConfig();\n      if (runtimeConfig.issues.length > 0) {\n        yield* Effect.logWarning(\n          \"skipping startup keybindings default sync because config has issues\",\n          {\n            path: keybindingsConfigPath,\n            issues: runtimeConfig.issues,\n          },\n        );\n        yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n        return;\n      }\n      const customConfig = runtimeConfig.keybindings;\n      const existingCommands = new Set(customConfig.map((entry) => entry.command));\n      const missingDefaults: KeybindingRule[] = [];\n      const shortcutConflictWarnings: Array<{\n        defaultCommand: KeybindingRule[\"command\"];\n        conflictingCommand: KeybindingRule[\"command\"];\n        key: string;\n        when: string | null;\n      }> = [];\n      for (const defaultRule of DEFAULT_KEYBINDINGS) {\n        if (existingCommands.has(defaultRule.command)) {\n          continue;\n        }\n        const conflictingEntry = customConfig.find((entry) =>\n          hasSameShortcutContext(entry, defaultRule),\n        );\n        if (conflictingEntry) {\n          shortcutConflictWarnings.push({\n            defaultCommand: defaultRule.command,\n            conflictingCommand: conflictingEntry.command,\n            key: defaultRule.key,\n            when: defaultRule.when ?? null,\n          });\n          continue;\n        }\n        missingDefaults.push(defaultRule);\n      }\n      for (const conflict of shortcutConflictWarnings) {\n        yield* Effect.logWarning(\"skipping default keybinding due to shortcut conflict\", {\n          path: keybindingsConfigPath,\n          defaultCommand: conflict.defaultCommand,\n          conflictingCommand: conflict.conflictingCommand,\n          key: conflict.key,\n          when: conflict.when,\n          reason: \"shortcut context already used by existing rule\",\n        });\n      }\n      if (missingDefaults.length === 0) {\n        yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n        return;\n      }\n\n      const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>\n        customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))\n          ? Result.succeed(defaultRule.command)\n          : Result.failVoid,\n      );\n      if (matchingDefaults.length > 0) {\n        yield* Effect.logWarning(\"default keybinding rule already defined in user config\", {\n          path: keybindingsConfigPath,\n          commands: matchingDefaults,\n        });\n      }\n\n      // Startup backfill must never evict persisted user rules: append only\n      // the defaults that fit and skip the rest.\n      const availableSlots = Math.max(0, MAX_KEYBINDINGS_COUNT - customConfig.length);\n      const defaultsToAppend = missingDefaults.slice(0, availableSlots);\n      const skippedDefaults = missingDefaults.slice(availableSlots);\n      if (skippedDefaults.length > 0) {\n        yield* Effect.logWarning(\"skipping default keybinding backfill at max entries\", {\n          path: keybindingsConfigPath,\n          maxEntries: MAX_KEYBINDINGS_COUNT,\n          commands: skippedDefaults.map((rule) => rule.command),\n        });\n      }\n      if (defaultsToAppend.length === 0) {\n        yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n        return;\n      }\n\n      yield* writeConfigAtomically([...customConfig, ...defaultsToAppend]);\n      yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n    }),\n  );\n\n  const startWatcher = Effect.gen(function* () {\n    const keybindingsConfigDir = path.dirname(keybindingsConfigPath);\n    const keybindingsConfigFile = path.basename(keybindingsConfigPath);\n    const keybindingsConfigPathResolved = path.resolve(keybindingsConfigPath);\n\n    yield* fs.makeDirectory(keybindingsConfigDir, { recursive: true }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new KeybindingsConfigError({\n            configPath: keybindingsConfigPath,\n            detail: \"failed to prepare keybindings config directory\",\n            cause,\n          }),\n      ),\n    );\n\n    const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));\n\n    // Debounce watch events so the file is fully written before we read it.\n    // Editors emit multiple events per save (truncate, write, rename) and\n    // `fs.watch` can fire before the content has been flushed to disk.\n    const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(\n      Stream.filter((event) => {\n        return (\n          event.path === keybindingsConfigFile ||\n          event.path === keybindingsConfigPath ||\n          path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved\n        );\n      }),\n      Stream.debounce(Duration.millis(100)),\n    );\n\n    yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(\n      Effect.ignoreCause({ log: true }),\n      Effect.forkIn(watcherScope),\n      Effect.asVoid,\n    );\n  });\n\n  const start = Effect.gen(function* () {\n    const alreadyStarted = yield* Ref.get(startedRef);\n    if (alreadyStarted) {\n      return yield* Deferred.await(startedDeferred);\n    }\n\n    yield* Ref.set(startedRef, true);\n    const startup = Effect.gen(function* () {\n      yield* startWatcher;\n      yield* syncDefaultKeybindingsOnStartup;\n      yield* Cache.invalidate(resolvedConfigCache, resolvedConfigCacheKey);\n      yield* loadConfigStateFromCacheOrDisk;\n    });\n\n    const startupExit = yield* Effect.exit(startup);\n    if (startupExit._tag === \"Failure\") {\n      yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);\n      return yield* Effect.failCause(startupExit.cause);\n    }\n\n    yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);\n  });\n\n  return {\n    start,\n    ready: Deferred.await(startedDeferred),\n    syncDefaultKeybindingsOnStartup,\n    loadConfigState: loadConfigStateFromCacheOrDisk,\n    getSnapshot: loadConfigStateFromCacheOrDisk,\n    get streamChanges() {\n      return Stream.fromPubSub(changesPubSub);\n    },\n    upsertKeybindingRule: (input) =>\n      upsertSemaphore.withPermits(1)(\n        Effect.gen(function* () {\n          const customConfig = yield* loadWritableCustomKeybindingsConfig();\n          const rule = keybindingRuleFromUpsertInput(input);\n          const replaceTarget = replaceTargetFromUpsertInput(input);\n          const nextConfig = [\n            ...customConfig.filter((entry) => {\n              if (replaceTarget) {\n                return (\n                  !isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)\n                );\n              }\n              return !isSameKeybindingRule(entry, rule);\n            }),\n            rule,\n          ];\n          const cappedConfig =\n            nextConfig.length > MAX_KEYBINDINGS_COUNT\n              ? nextConfig.slice(-MAX_KEYBINDINGS_COUNT)\n              : nextConfig;\n          if (nextConfig.length > MAX_KEYBINDINGS_COUNT) {\n            yield* Effect.logWarning(\"truncating keybindings config to max entries\", {\n              path: keybindingsConfigPath,\n              maxEntries: MAX_KEYBINDINGS_COUNT,\n            });\n          }\n          yield* writeConfigAtomically(cappedConfig);\n          const nextResolved = mergeWithDefaultKeybindings(\n            compileResolvedKeybindingsConfig(cappedConfig),\n          );\n          yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {\n            keybindings: nextResolved,\n            issues: [],\n          });\n          yield* emitChange({\n            keybindings: nextResolved,\n            issues: [],\n          });\n          return nextResolved;\n        }),\n      ),\n    removeKeybindingRule: (input) =>\n      upsertSemaphore.withPermits(1)(\n        Effect.gen(function* () {\n          const customConfig = yield* loadWritableCustomKeybindingsConfig();\n          const target = keybindingRuleFromRemoveInput(input);\n          const nextConfig = customConfig.filter((entry) => !isSameKeybindingRule(entry, target));\n          yield* writeConfigAtomically(nextConfig);\n          const nextResolved = mergeWithDefaultKeybindings(\n            compileResolvedKeybindingsConfig(nextConfig),\n          );\n          yield* Cache.set(resolvedConfigCache, resolvedConfigCacheKey, {\n            keybindings: nextResolved,\n            issues: [],\n          });\n          yield* emitChange({\n            keybindings: nextResolved,\n            issues: [],\n          });\n          return nextResolved;\n        }),\n      ),\n  } satisfies Keybindings[\"Service\"];\n});\n\nexport const layer = Layer.effect(Keybindings, make);\n","/**\n * ExternalLauncher - external application launch service interface.\n *\n * Owns process launch helpers for browser URLs and workspace paths\n * in configured editor integrations.\n *\n * @module ExternalLauncher\n */\nimport {\n  EDITORS,\n  ExternalLauncherError,\n  ExternalLauncherBrowserSpawnError,\n  ExternalLauncherCommandNotFoundError,\n  ExternalLauncherEditorSpawnError,\n  ExternalLauncherUnknownEditorError,\n  ExternalLauncherUnsupportedEditorError,\n  type EditorId,\n  type LaunchEditorInput,\n} from \"@t3tools/contracts\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { isCommandAvailable, resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport * as Clock from \"effect/Clock\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\n\n// ==============================\n// Definitions\n// ==============================\n\nexport {\n  ExternalLauncherError,\n  ExternalLauncherBrowserSpawnError,\n  ExternalLauncherCommandNotFoundError,\n  ExternalLauncherEditorSpawnError,\n  ExternalLauncherUnknownEditorError,\n  ExternalLauncherUnsupportedEditorError,\n  isExternalLauncherError,\n} from \"@t3tools/contracts\";\nexport type { LaunchEditorInput };\ninterface EditorLaunch {\n  readonly editor: EditorId;\n  readonly target: string;\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n}\n\ninterface ProcessLaunch {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly options: ChildProcess.CommandOptions;\n}\n\ninterface TargetPathAndPosition {\n  readonly path: string;\n  readonly line: string;\n  readonly column: Option.Option<string>;\n}\n\nconst TARGET_WITH_POSITION_PATTERN = /^(.*?):(\\d+)(?::(\\d+))?$/;\nconst POWERSHELL_ARGUMENTS_PREFIX = [\n  \"-NoProfile\",\n  \"-NonInteractive\",\n  \"-ExecutionPolicy\",\n  \"Bypass\",\n  \"-EncodedCommand\",\n] as const;\n\nconst DETACHED_IGNORE_STDIO_OPTIONS = {\n  detached: true,\n  stdin: \"ignore\",\n  stdout: \"ignore\",\n  stderr: \"ignore\",\n} as const satisfies ChildProcess.CommandOptions;\n\nconst compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>\n  Object.fromEntries(\n    Object.entries(input).flatMap(([key, value]) =>\n      Option.match(value, {\n        onNone: () => [],\n        onSome: (resolved) => [[key, resolved]],\n      }),\n    ),\n  );\n\nconst BrowserLaunchEnvConfig = Config.all({\n  SYSTEMROOT: Config.string(\"SYSTEMROOT\").pipe(Config.option),\n  windir: Config.string(\"windir\").pipe(Config.option),\n  WSL_DISTRO_NAME: Config.string(\"WSL_DISTRO_NAME\").pipe(Config.option),\n  WSL_INTEROP: Config.string(\"WSL_INTEROP\").pipe(Config.option),\n  SSH_CONNECTION: Config.string(\"SSH_CONNECTION\").pipe(Config.option),\n  SSH_TTY: Config.string(\"SSH_TTY\").pipe(Config.option),\n  container: Config.string(\"container\").pipe(Config.option),\n}).pipe(Config.map(compactEnv));\n\nconst CommandLookupEnvConfig = Config.all({\n  PATH: Config.string(\"PATH\").pipe(Config.option),\n  Path: Config.string(\"Path\").pipe(Config.option),\n  path: Config.string(\"path\").pipe(Config.option),\n  PATHEXT: Config.string(\"PATHEXT\").pipe(Config.option),\n}).pipe(Config.map(compactEnv));\n\nconst readBrowserLaunchEnv = BrowserLaunchEnvConfig.pipe(Effect.orElseSucceed(() => ({})));\nconst readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));\n\nfunction parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {\n  const match = TARGET_WITH_POSITION_PATTERN.exec(target);\n  if (!match?.[1] || !match[2]) {\n    return Option.none();\n  }\n\n  return Option.some({\n    path: match[1],\n    line: match[2],\n    column: Option.fromUndefinedOr(match[3]),\n  });\n}\n\nfunction resolveCommandEditorArgs(\n  editor: (typeof EDITORS)[number],\n  target: string,\n): ReadonlyArray<string> {\n  const parsedTarget = parseTargetPathAndPosition(target);\n\n  switch (editor.launchStyle) {\n    case \"direct-path\":\n      return [target];\n    case \"goto\":\n      return Option.isSome(parsedTarget) ? [\"--goto\", target] : [target];\n    case \"line-column\":\n      return Option.match(parsedTarget, {\n        onNone: () => [target],\n        onSome: ({ path, line, column }) => [\n          \"--line\",\n          line,\n          ...Option.match(column, {\n            onNone: () => [],\n            onSome: (value) => [\"--column\", value],\n          }),\n          path,\n        ],\n      });\n  }\n}\n\nfunction resolveEditorArgs(\n  editor: (typeof EDITORS)[number],\n  target: string,\n): ReadonlyArray<string> {\n  const baseArgs = \"baseArgs\" in editor ? editor.baseArgs : [];\n  return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];\n}\n\nconst resolveAvailableCommand = Effect.fn(\"externalLauncher.resolveAvailableCommand\")(function* (\n  commands: ReadonlyArray<string>,\n  env: NodeJS.ProcessEnv,\n): Effect.fn.Return<Option.Option<string>, never, FileSystem.FileSystem | Path.Path> {\n  for (const command of commands) {\n    if (yield* isCommandAvailable(command, { env })) {\n      return Option.some(command);\n    }\n  }\n  return Option.none();\n});\n\nfunction encodeUtf16LeBase64(input: string): string {\n  const bytes = new Uint8Array(input.length * 2);\n  for (let index = 0; index < input.length; index += 1) {\n    const code = input.charCodeAt(index);\n    bytes[index * 2] = code & 0xff;\n    bytes[index * 2 + 1] = code >>> 8;\n  }\n  return Encoding.encodeBase64(bytes);\n}\n\nfunction escapePowerShellStringLiteral(input: string): string {\n  return `'${input.replaceAll(\"'\", \"''\")}'`;\n}\n\nfunction resolvePowerShellPath(env: NodeJS.ProcessEnv = {}): string {\n  return `${env.SYSTEMROOT || env.windir || String.raw`C:\\Windows`}\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\powershell.exe`;\n}\n\nfunction resolveWslPowerShellPath(): string {\n  return \"/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe\";\n}\n\nfunction shouldUseWindowsBrowserFromWsl(\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv = {},\n): boolean {\n  return (\n    platform === \"linux\" &&\n    (env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&\n    env.SSH_CONNECTION === undefined &&\n    env.SSH_TTY === undefined &&\n    env.container === undefined\n  );\n}\n\nfunction resolveWindowsBrowserLaunch(target: string, command: string): ProcessLaunch {\n  const encodedCommand = encodeUtf16LeBase64(\n    `$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,\n  );\n  return {\n    command,\n    args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],\n    options: {\n      detached: true,\n      shell: false,\n      stdin: \"ignore\",\n      stdout: \"ignore\",\n      stderr: \"ignore\",\n    },\n  };\n}\n\nfunction fileManagerCommandForPlatform(platform: NodeJS.Platform): string {\n  switch (platform) {\n    case \"darwin\":\n      return \"open\";\n    case \"win32\":\n      return \"explorer\";\n    default:\n      return \"xdg-open\";\n  }\n}\n\nfunction buildBrowserLaunch(\n  target: string,\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv = {},\n): ProcessLaunch {\n  if (platform === \"darwin\") {\n    return {\n      command: \"open\",\n      args: [target],\n      options: DETACHED_IGNORE_STDIO_OPTIONS,\n    };\n  }\n\n  if (platform === \"win32\") {\n    return resolveWindowsBrowserLaunch(target, resolvePowerShellPath(env));\n  }\n\n  if (shouldUseWindowsBrowserFromWsl(platform, env)) {\n    return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath());\n  }\n\n  return {\n    command: \"xdg-open\",\n    args: [target],\n    options: DETACHED_IGNORE_STDIO_OPTIONS,\n  };\n}\n\nconst buildAvailableEditors = Effect.fn(\"externalLauncher.buildAvailableEditors\")(function* (\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv,\n): Effect.fn.Return<ReadonlyArray<EditorId>, never, FileSystem.FileSystem | Path.Path> {\n  const available: EditorId[] = [];\n\n  for (const editor of EDITORS) {\n    if (editor.commands === null) {\n      const command = fileManagerCommandForPlatform(platform);\n      if (yield* isCommandAvailable(command, { env })) {\n        available.push(editor.id);\n      }\n      continue;\n    }\n\n    const command = yield* resolveAvailableCommand(editor.commands, env);\n    if (Option.isSome(command)) {\n      available.push(editor.id);\n    }\n  }\n\n  return available;\n});\n\nconst resolveBrowserLaunch = Effect.fn(\"externalLauncher.resolveBrowserLaunch\")(function* (\n  target: string,\n) {\n  const platform = yield* HostProcessPlatform;\n  const env = yield* readBrowserLaunchEnv;\n  return buildBrowserLaunch(target, platform, env);\n});\n\nconst resolveAvailableEditors = Effect.fn(\"externalLauncher.resolveAvailableEditors\")(function* () {\n  const platform = yield* HostProcessPlatform;\n  const env = yield* readCommandLookupEnv;\n  return yield* buildAvailableEditors(platform, env);\n});\n\n// Editor discovery walks PATH for every known editor and runs for every\n// client connect (the server config embeds the available editors). Memoize\n// the discovered set for a bounded window so repeat connects skip even the\n// per-command cache lookups in @t3tools/shared/shell.\n//\n// This deliberately does not use `Effect.cachedWithTTL`: that memoizes the\n// first caller's Exit whatever it is, including an interrupt. Callers run this\n// on the connection fiber under a timeout (`resolveAvailableEditorsForConfig`),\n// so one client disconnecting mid-scan would cache the interrupt and replay it\n// to every later connect for the whole TTL, breaking `server.getConfig`\n// permanently. Storing only on success means an interrupted scan leaves the\n// cache untouched and the next connect simply rescans.\n// Expiry uses the monotonic clock (Clock.currentTimeNanos), matching the\n// command-resolution cache in @t3tools/shared/shell, so a backward wall-clock\n// adjustment cannot keep an expired entry alive.\nconst EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n;\n\ninterface EditorDiscoveryCacheEntry {\n  readonly editors: ReadonlyArray<EditorId>;\n  readonly expiresAtNanos: bigint;\n}\n\n/**\n * ExternalLauncher - Service tag for browser/editor launch operations.\n */\nexport class ExternalLauncher extends Context.Service<\n  ExternalLauncher,\n  {\n    readonly resolveAvailableEditors: () => Effect.Effect<ReadonlyArray<EditorId>>;\n    /** Launch a URL target in the default browser. */\n    readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;\n    /**\n     * Launch a workspace path in a selected editor integration.\n     *\n     * Launches the editor as a detached process so server startup is not blocked.\n     */\n    readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;\n  }\n>()(\"t3/process/externalLauncher\") {}\n\n// ==============================\n// Implementations\n// ==============================\n\nconst resolveEditorLaunch = Effect.fn(\"resolveEditorLaunch\")(function* (\n  input: LaunchEditorInput,\n): Effect.fn.Return<EditorLaunch, ExternalLauncherError, FileSystem.FileSystem | Path.Path> {\n  const platform = yield* HostProcessPlatform;\n  const env = yield* readCommandLookupEnv;\n  yield* Effect.annotateCurrentSpan({\n    \"externalLauncher.editor\": input.editor,\n    \"externalLauncher.cwd\": input.cwd,\n    \"externalLauncher.platform\": platform,\n  });\n  const editorDef = EDITORS.find((editor) => editor.id === input.editor);\n  if (!editorDef) {\n    return yield* new ExternalLauncherUnknownEditorError({ editor: input.editor });\n  }\n\n  if (editorDef.commands) {\n    const command = Option.getOrElse(\n      yield* resolveAvailableCommand(editorDef.commands, env),\n      () => editorDef.commands[0],\n    );\n    return {\n      editor: editorDef.id,\n      target: input.cwd,\n      command,\n      args: resolveEditorArgs(editorDef, input.cwd),\n    };\n  }\n\n  if (editorDef.id !== \"file-manager\") {\n    return yield* new ExternalLauncherUnsupportedEditorError({ editor: input.editor });\n  }\n\n  return {\n    editor: editorDef.id,\n    target: input.cwd,\n    command: fileManagerCommandForPlatform(platform),\n    args: [input.cwd],\n  };\n});\n\nconst launchAndUnref = Effect.fn(\"externalLauncher.launchAndUnref\")(function* (\n  launch: ProcessLaunch,\n  onError: (cause: unknown) => ExternalLauncherError,\n): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const command = ChildProcess.make(launch.command, launch.args, launch.options);\n\n  yield* spawner.spawn(command).pipe(\n    Effect.flatMap((handle) => handle.unref),\n    Effect.asVoid,\n    Effect.scoped,\n    Effect.mapError(onError),\n  );\n});\n\nconst launchBrowser = Effect.fn(\"externalLauncher.launchBrowser\")(function* (\n  target: string,\n): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {\n  const launch = yield* resolveBrowserLaunch(target);\n  return yield* launchAndUnref(\n    launch,\n    (cause) =>\n      new ExternalLauncherBrowserSpawnError({\n        target,\n        command: launch.command,\n        args: launch.args,\n        cause,\n      }),\n  );\n});\n\nconst launchEditorProcess = Effect.fn(\"externalLauncher.launchEditorProcess\")(function* (\n  launch: EditorLaunch,\n): Effect.fn.Return<\n  void,\n  ExternalLauncherError,\n  ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path\n> {\n  const env = yield* readCommandLookupEnv;\n  if (!(yield* isCommandAvailable(launch.command, { env }))) {\n    return yield* new ExternalLauncherCommandNotFoundError({\n      editor: launch.editor,\n      command: launch.command,\n    });\n  }\n\n  const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { env });\n  yield* launchAndUnref(\n    {\n      command: spawnCommand.command,\n      args: spawnCommand.args,\n      options: {\n        detached: true,\n        shell: spawnCommand.shell,\n        stdin: \"ignore\",\n        stdout: \"ignore\",\n        stderr: \"ignore\",\n      },\n    },\n    (cause) =>\n      new ExternalLauncherEditorSpawnError({\n        editor: launch.editor,\n        target: launch.target,\n        command: spawnCommand.command,\n        args: spawnCommand.args,\n        cause,\n      }),\n  );\n});\n\nexport const make = Effect.gen(function* () {\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const provideCommandResolutionServices = <A, E, R>(\n    effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,\n  ) =>\n    effect.pipe(\n      Effect.provideService(FileSystem.FileSystem, fileSystem),\n      Effect.provideService(Path.Path, path),\n    );\n\n  const editorDiscoveryCache = yield* Ref.make<Option.Option<EditorDiscoveryCacheEntry>>(\n    Option.none(),\n  );\n  const cachedAvailableEditors = Effect.gen(function* () {\n    const nowNanos = yield* Clock.currentTimeNanos;\n    const entry = yield* Ref.get(editorDiscoveryCache);\n    if (Option.isSome(entry) && entry.value.expiresAtNanos > nowNanos) {\n      return entry.value.editors;\n    }\n    const editors = yield* provideCommandResolutionServices(resolveAvailableEditors());\n    yield* Ref.set(\n      editorDiscoveryCache,\n      Option.some({\n        editors,\n        expiresAtNanos: nowNanos + EDITOR_DISCOVERY_CACHE_TTL_NANOS,\n      }),\n    );\n    return editors;\n  });\n\n  return ExternalLauncher.of({\n    resolveAvailableEditors: () => cachedAvailableEditors,\n    launchBrowser: (target) =>\n      launchBrowser(target).pipe(\n        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n      ),\n    launchEditor: (input) =>\n      provideCommandResolutionServices(\n        Effect.flatMap(resolveEditorLaunch(input), (launch) =>\n          launchEditorProcess(launch).pipe(\n            Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n          ),\n        ),\n      ),\n  });\n});\n\nexport const layer = Layer.effect(ExternalLauncher, make);\n","/**\n * OrchestrationReactor - Composite orchestration reactor service interface.\n *\n * Coordinates startup of orchestration runtime reactors that translate domain\n * events into downstream side effects.\n *\n * @module OrchestrationReactor\n */\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\n/**\n * OrchestrationReactorShape - Service API for orchestration reactor lifecycle.\n */\nexport interface OrchestrationReactorShape {\n  /**\n   * Start orchestration-side reactors for provider/runtime/checkpoint flows.\n   *\n   * The returned effect must be run in a scope so all worker fibers can be\n   * finalized on shutdown.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n}\n\n/**\n * OrchestrationReactor - Service tag for orchestration reactor coordination.\n */\nexport class OrchestrationReactor extends Context.Service<\n  OrchestrationReactor,\n  OrchestrationReactorShape\n>()(\"t3/orchestration/Services/OrchestrationReactor\") {}\n","import type { ServerLifecycleStreamEvent } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Stream from \"effect/Stream\";\n\ntype LifecycleEventInput =\n  | Omit<Extract<ServerLifecycleStreamEvent, { type: \"welcome\" }>, \"sequence\">\n  | Omit<Extract<ServerLifecycleStreamEvent, { type: \"ready\" }>, \"sequence\">;\n\ninterface SnapshotState {\n  readonly sequence: number;\n  readonly events: ReadonlyArray<ServerLifecycleStreamEvent>;\n}\n\nexport class ServerLifecycleEvents extends Context.Service<\n  ServerLifecycleEvents,\n  {\n    readonly publish: (event: LifecycleEventInput) => Effect.Effect<ServerLifecycleStreamEvent>;\n    readonly snapshot: Effect.Effect<SnapshotState>;\n    readonly stream: Stream.Stream<ServerLifecycleStreamEvent>;\n  }\n>()(\"t3/serverLifecycleEvents\") {}\n\nconst make = Effect.gen(function* () {\n  const pubsub = yield* PubSub.unbounded<ServerLifecycleStreamEvent>();\n  const state = yield* Ref.make<SnapshotState>({\n    sequence: 0,\n    events: [],\n  });\n\n  return {\n    publish: (event) =>\n      Ref.modify(state, (current) => {\n        const nextSequence = current.sequence + 1;\n        const nextEvent = {\n          ...event,\n          sequence: nextSequence,\n        } satisfies ServerLifecycleStreamEvent;\n        const nextEvents =\n          nextEvent.type === \"welcome\"\n            ? [nextEvent, ...current.events.filter((entry) => entry.type !== \"welcome\")]\n            : [nextEvent, ...current.events.filter((entry) => entry.type !== \"ready\")];\n        return [nextEvent, { sequence: nextSequence, events: nextEvents }] as const;\n      }).pipe(Effect.tap((event) => PubSub.publish(pubsub, event))),\n    snapshot: Ref.get(state),\n    get stream() {\n      return Stream.fromPubSub(pubsub);\n    },\n  } satisfies ServerLifecycleEvents[\"Service\"];\n});\n\nexport const layer = Layer.effect(ServerLifecycleEvents, make);\n","/**\n * ServerSettings - Server-authoritative settings service.\n *\n * Owns persistence, validation, and change notification of settings that affect\n * server-side behavior (binary paths, streaming mode, env mode, custom models,\n * text generation model selection).\n *\n * Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub +\n * Semaphore + FileSystem.watch for concurrency and external edit detection.\n *\n * @module ServerSettings\n */\nimport {\n  DEFAULT_TEXT_GENERATION_MODEL,\n  DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,\n  DEFAULT_MODEL_BY_PROVIDER,\n  DEFAULT_SERVER_SETTINGS,\n  type ModelSelection,\n  type ProviderInstanceConfig,\n  type ProviderInstanceEnvironmentVariable,\n  ProviderDriverKind,\n  ProviderInstanceId,\n  ServerSettings,\n  ServerSettingsError,\n  type ServerSettingsPatch,\n} from \"@t3tools/contracts\";\nimport * as Cache from \"effect/Cache\";\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Equal from \"effect/Equal\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { writeFileStringAtomically } from \"./atomicWrite.ts\";\nimport * as ServerConfig from \"./config.ts\";\nimport { type DeepPartial, deepMerge } from \"@t3tools/shared/Struct\";\nimport { fromJsonStringPretty, fromLenientJson } from \"@t3tools/shared/schemaJson\";\nimport {\n  applyServerSettingsPatch,\n  isModelSelectionProviderEnabled,\n} from \"@t3tools/shared/serverSettings\";\nimport * as ServerSecretStore from \"./auth/ServerSecretStore.ts\";\n\nexport { resolveSourceControlWriterModelSelection } from \"@t3tools/shared/serverSettings\";\n\nconst encodeServerSettings = Schema.encodeEffect(ServerSettings);\nconst encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));\nconst decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nconst normalizeServerSettings = (\n  settings: ServerSettings,\n): Effect.Effect<ServerSettings, ServerSettingsError> =>\n  encodeServerSettings(settings).pipe(\n    Effect.flatMap(decodeServerSettings),\n    Effect.mapError(\n      (cause) =>\n        new ServerSettingsError({\n          settingsPath: \"<memory>\",\n          operation: \"normalize\",\n          cause,\n        }),\n    ),\n  );\n\nfunction providerEnvironmentSecretName(input: {\n  readonly instanceId: string;\n  readonly name: string;\n}): string {\n  return `provider-env-${Buffer.from(input.instanceId, \"utf8\").toString(\"base64url\")}-${Buffer.from(input.name, \"utf8\").toString(\"base64url\")}`;\n}\n\nfunction redactProviderEnvironmentVariable(\n  variable: ProviderInstanceEnvironmentVariable,\n): ProviderInstanceEnvironmentVariable {\n  if (!variable.sensitive) {\n    const { valueRedacted: _omit, ...rest } = variable;\n    return rest;\n  }\n  return {\n    ...variable,\n    value: \"\",\n    ...(variable.value.length > 0 || variable.valueRedacted ? { valueRedacted: true } : {}),\n  };\n}\n\nexport function redactServerSettingsForClient(settings: ServerSettings): ServerSettings {\n  const providerInstances = Object.fromEntries(\n    Object.entries(settings.providerInstances).map(([instanceId, instance]) => [\n      instanceId,\n      instance.environment\n        ? {\n            ...instance,\n            environment: instance.environment.map(redactProviderEnvironmentVariable),\n          }\n        : instance,\n    ]),\n  );\n  return { ...settings, providerInstances };\n}\n\nexport class ServerSettingsService extends Context.Service<\n  ServerSettingsService,\n  {\n    /** Start the settings runtime and attach file watching. */\n    readonly start: Effect.Effect<void, ServerSettingsError>;\n\n    /** Await settings runtime readiness. */\n    readonly ready: Effect.Effect<void, ServerSettingsError>;\n\n    /** Read the current settings. */\n    readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;\n\n    /** Patch settings and persist. Returns the new full settings object. */\n    readonly updateSettings: (\n      patch: ServerSettingsPatch,\n    ) => Effect.Effect<ServerSettings, ServerSettingsError>;\n\n    /** Stream of settings change events. */\n    readonly streamChanges: Stream.Stream<ServerSettings>;\n\n    /**\n     * Acquire a settings change subscription synchronously in the current\n     * fiber. Use this before reading a snapshot when changes between the\n     * snapshot and a lazily started stream must not be lost.\n     */\n    readonly subscribeChanges: Effect.Effect<Stream.Stream<ServerSettings>, never, Scope.Scope>;\n  }\n>()(\"t3/serverSettings/ServerSettingsService\") {\n  /** @deprecated Import and use `layerTest` from this module. */\n  static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) => layerTest(overrides);\n}\n\nconst makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>\n  Effect.gen(function* () {\n    const { automaticGitFetchInterval, providerHealthRefreshInterval, ...overridesForMerge } =\n      overrides;\n    const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);\n    const initialSettings = yield* normalizeServerSettings({\n      ...merged,\n      ...(automaticGitFetchInterval !== undefined\n        ? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }\n        : {}),\n      ...(providerHealthRefreshInterval !== undefined\n        ? { providerHealthRefreshInterval: providerHealthRefreshInterval as Duration.Duration }\n        : {}),\n    });\n    const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);\n\n    return {\n      start: Effect.void,\n      ready: Effect.void,\n      getSettings: Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)),\n      updateSettings: (patch) =>\n        Ref.get(currentSettingsRef).pipe(\n          Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),\n          Effect.flatMap(normalizeServerSettings),\n          Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),\n          Effect.map(resolveTextGenerationProvider),\n        ),\n      streamChanges: Stream.empty,\n      subscribeChanges: Effect.succeed(Stream.empty),\n    } satisfies ServerSettingsService[\"Service\"];\n  });\n\nexport const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>\n  Layer.effect(ServerSettingsService, makeTest(overrides));\n\nconst ServerSettingsJson = fromLenientJson(ServerSettings);\nconst decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);\n\nfunction resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {\n  return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection)\n    ? settings\n    : fallbackTextGenerationProvider(settings);\n}\n\nfunction fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {\n  const fallbackEntry = Object.entries(settings.providers).find(([, provider]) => provider.enabled);\n  const fallback = fallbackEntry ? ProviderDriverKind.make(fallbackEntry[0]) : undefined;\n  if (!fallback) {\n    return settings;\n  }\n\n  return {\n    ...settings,\n    textGenerationModelSelection: {\n      instanceId: ProviderInstanceId.make(fallback),\n      model:\n        DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??\n        DEFAULT_MODEL_BY_PROVIDER[fallback] ??\n        DEFAULT_TEXT_GENERATION_MODEL,\n    } satisfies ModelSelection,\n  };\n}\n\n// Values under these keys are compared as a whole — never stripped field-by-field.\nconst ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([\n  \"backgroundActivity\",\n  \"automaticGitFetchInterval\",\n  \"providerHealthRefreshInterval\",\n  \"sourceControlWriterModelSelection\",\n  \"textGenerationModelSelection\",\n]);\n\nfunction stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {\n  if (Array.isArray(current) || Array.isArray(defaults)) {\n    return Equal.equals(current, defaults) ? undefined : current;\n  }\n\n  if (\n    current !== null &&\n    defaults !== null &&\n    typeof current === \"object\" &&\n    typeof defaults === \"object\"\n  ) {\n    const currentRecord = current as Record<string, unknown>;\n    const defaultsRecord = defaults as Record<string, unknown>;\n    const next: Record<string, unknown> = {};\n\n    for (const key of Object.keys(currentRecord)) {\n      if (ATOMIC_SETTINGS_KEYS.has(key)) {\n        if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {\n          next[key] = currentRecord[key];\n        }\n      } else {\n        const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);\n        if (stripped !== undefined) {\n          next[key] = stripped;\n        }\n      }\n    }\n\n    return Object.keys(next).length > 0 ? next : undefined;\n  }\n\n  return Object.is(current, defaults) ? undefined : current;\n}\n\nconst make = Effect.gen(function* () {\n  const { settingsPath } = yield* ServerConfig.ServerConfig;\n  const fs = yield* FileSystem.FileSystem;\n  const pathService = yield* Path.Path;\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const writeSemaphore = yield* Semaphore.make(1);\n  const cacheKey = \"settings\" as const;\n  const changesPubSub = yield* PubSub.unbounded<ServerSettings>();\n  const startedRef = yield* Ref.make(false);\n  const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();\n  const watcherScope = yield* Scope.make(\"sequential\");\n  yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));\n\n  const emitChange = (settings: ServerSettings) =>\n    PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);\n\n  const readConfigExists = fs.exists(settingsPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ServerSettingsError({\n          settingsPath,\n          operation: \"check-exists\",\n          cause,\n        }),\n    ),\n  );\n\n  const readRawConfig = fs.readFileString(settingsPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ServerSettingsError({\n          settingsPath,\n          operation: \"read-file\",\n          cause,\n        }),\n    ),\n  );\n\n  const loadSettingsFromDisk = Effect.gen(function* () {\n    if (!(yield* readConfigExists)) {\n      return DEFAULT_SERVER_SETTINGS;\n    }\n\n    const raw = yield* readRawConfig;\n    const decoded = decodeServerSettingsJsonExit(raw);\n    if (decoded._tag === \"Failure\") {\n      yield* Effect.logWarning(\"failed to parse settings.json, using defaults\", {\n        path: settingsPath,\n        issues: Cause.pretty(decoded.cause),\n        cause: decoded.cause,\n      });\n      return DEFAULT_SERVER_SETTINGS;\n    }\n    return decoded.value;\n  });\n\n  const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({\n    capacity: 1,\n    lookup: () => loadSettingsFromDisk,\n  });\n\n  const getSettingsFromCache = Cache.get(settingsCache, cacheKey);\n\n  const materializeProviderEnvironmentSecrets = (\n    settings: ServerSettings,\n  ): Effect.Effect<ServerSettings, ServerSettingsError> =>\n    Effect.gen(function* () {\n      const providerInstances: Record<string, ProviderInstanceConfig> = {\n        ...settings.providerInstances,\n      };\n      for (const [instanceId, instance] of Object.entries(settings.providerInstances)) {\n        if (!instance.environment) continue;\n        const environment: ProviderInstanceEnvironmentVariable[] = [];\n        for (const variable of instance.environment) {\n          if (!variable.sensitive || !variable.valueRedacted) {\n            environment.push(variable);\n            continue;\n          }\n          const secret = yield* secretStore\n            .get(providerEnvironmentSecretName({ instanceId, name: variable.name }))\n            .pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ServerSettingsError({\n                    settingsPath,\n                    operation: \"read-secret\",\n                    providerInstanceId: instanceId,\n                    environmentVariable: variable.name,\n                    cause,\n                  }),\n              ),\n            );\n          environment.push({\n            ...variable,\n            value: Option.isSome(secret) ? textDecoder.decode(secret.value) : \"\",\n          });\n        }\n        providerInstances[instanceId] = {\n          ...instance,\n          environment,\n        } satisfies ProviderInstanceConfig;\n      }\n      return {\n        ...settings,\n        providerInstances: providerInstances as ServerSettings[\"providerInstances\"],\n      };\n    });\n\n  const materializeChanges = (changes: Stream.Stream<ServerSettings>) =>\n    changes.pipe(\n      Stream.mapEffect((settings) =>\n        materializeProviderEnvironmentSecrets(settings).pipe(\n          Effect.catch((error: ServerSettingsError) =>\n            Effect.logWarning(\"failed to materialize provider environment secrets\", {\n              operation: error.operation,\n              providerInstanceId: error.providerInstanceId,\n              environmentVariable: error.environmentVariable,\n              cause: error.cause,\n            }).pipe(Effect.as(settings)),\n          ),\n        ),\n      ),\n      Stream.map(resolveTextGenerationProvider),\n    );\n\n  const persistProviderEnvironmentSecrets = (\n    current: ServerSettings,\n    next: ServerSettings,\n  ): Effect.Effect<ServerSettings, ServerSettingsError> =>\n    Effect.gen(function* () {\n      const providerInstances: Record<string, ProviderInstanceConfig> = {\n        ...next.providerInstances,\n      };\n\n      const nextSecretKeys = new Set<string>();\n      for (const [instanceId, instance] of Object.entries(next.providerInstances)) {\n        if (!instance.environment) continue;\n        const environment: ProviderInstanceEnvironmentVariable[] = [];\n        for (const variable of instance.environment) {\n          const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });\n          if (!variable.sensitive) {\n            yield* secretStore.remove(secretName).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ServerSettingsError({\n                    settingsPath,\n                    operation: \"remove-secret\",\n                    providerInstanceId: instanceId,\n                    environmentVariable: variable.name,\n                    cause,\n                  }),\n              ),\n            );\n            environment.push(redactProviderEnvironmentVariable(variable));\n            continue;\n          }\n\n          nextSecretKeys.add(secretName);\n          if (!variable.valueRedacted) {\n            if (variable.value.length > 0) {\n              yield* secretStore.set(secretName, textEncoder.encode(variable.value)).pipe(\n                Effect.mapError(\n                  (cause) =>\n                    new ServerSettingsError({\n                      settingsPath,\n                      operation: \"write-secret\",\n                      providerInstanceId: instanceId,\n                      environmentVariable: variable.name,\n                      cause,\n                    }),\n                ),\n              );\n              environment.push({ ...variable, value: \"\", valueRedacted: true });\n            } else {\n              yield* secretStore.remove(secretName).pipe(\n                Effect.mapError(\n                  (cause) =>\n                    new ServerSettingsError({\n                      settingsPath,\n                      operation: \"remove-secret\",\n                      providerInstanceId: instanceId,\n                      environmentVariable: variable.name,\n                      cause,\n                    }),\n                ),\n              );\n              const { valueRedacted: _omit, ...rest } = variable;\n              environment.push(rest);\n            }\n            continue;\n          }\n\n          environment.push(redactProviderEnvironmentVariable(variable));\n        }\n        providerInstances[instanceId] = {\n          ...instance,\n          environment,\n        } satisfies ProviderInstanceConfig;\n      }\n\n      for (const [instanceId, instance] of Object.entries(current.providerInstances)) {\n        for (const variable of instance.environment ?? []) {\n          if (!variable.sensitive) continue;\n          const secretName = providerEnvironmentSecretName({ instanceId, name: variable.name });\n          if (nextSecretKeys.has(secretName)) continue;\n          yield* secretStore.remove(secretName).pipe(\n            Effect.mapError(\n              (cause) =>\n                new ServerSettingsError({\n                  settingsPath,\n                  operation: \"remove-stale-secret\",\n                  providerInstanceId: instanceId,\n                  environmentVariable: variable.name,\n                  cause,\n                }),\n            ),\n          );\n        }\n      }\n\n      return {\n        ...next,\n        providerInstances: providerInstances as ServerSettings[\"providerInstances\"],\n      };\n    });\n\n  const writeSettingsAtomically = Effect.fnUntraced(\n    function* (settings: ServerSettings) {\n      const sparseSettingsJson = yield* encodeServerSettingsJson(\n        stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},\n      );\n\n      return yield* writeFileStringAtomically({\n        filePath: settingsPath,\n        contents: `${sparseSettingsJson}\\n`,\n      }).pipe(\n        Effect.provideService(FileSystem.FileSystem, fs),\n        Effect.provideService(Path.Path, pathService),\n      );\n    },\n    Effect.mapError(\n      (cause) =>\n        new ServerSettingsError({\n          settingsPath,\n          operation: \"write-file\",\n          cause,\n        }),\n    ),\n  );\n\n  const revalidateAndEmit = writeSemaphore.withPermits(1)(\n    Effect.gen(function* () {\n      yield* Cache.invalidate(settingsCache, cacheKey);\n      const settings = yield* getSettingsFromCache;\n      yield* emitChange(settings);\n    }),\n  );\n\n  const startWatcher = Effect.gen(function* () {\n    const settingsDir = pathService.dirname(settingsPath);\n    const settingsFile = pathService.basename(settingsPath);\n    const settingsPathResolved = pathService.resolve(settingsPath);\n\n    yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerSettingsError({\n            settingsPath,\n            operation: \"prepare-directory\",\n            cause,\n          }),\n      ),\n    );\n\n    const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));\n\n    // Debounce watch events so the file is fully written before we read it.\n    // Editors emit multiple events per save (truncate, write, rename) and\n    // `fs.watch` can fire before the content has been flushed to disk.\n    const debouncedSettingsEvents = fs.watch(settingsDir).pipe(\n      Stream.filter((event) => {\n        return (\n          event.path === settingsFile ||\n          event.path === settingsPath ||\n          pathService.resolve(settingsDir, event.path) === settingsPathResolved\n        );\n      }),\n      Stream.debounce(Duration.millis(100)),\n    );\n\n    yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(\n      Effect.ignoreCause({ log: true }),\n      Effect.forkIn(watcherScope),\n      Effect.asVoid,\n    );\n  });\n\n  const start = Effect.gen(function* () {\n    const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);\n    if (!shouldStart) {\n      return yield* Deferred.await(startedDeferred);\n    }\n\n    const startup = Effect.gen(function* () {\n      yield* startWatcher;\n      yield* Cache.invalidate(settingsCache, cacheKey);\n      yield* getSettingsFromCache;\n    });\n\n    const startupExit = yield* Effect.exit(startup);\n    if (startupExit._tag === \"Failure\") {\n      yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);\n      return yield* Effect.failCause(startupExit.cause);\n    }\n\n    yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);\n  });\n\n  return {\n    start,\n    ready: Deferred.await(startedDeferred),\n    getSettings: getSettingsFromCache.pipe(\n      Effect.flatMap(materializeProviderEnvironmentSecrets),\n      Effect.map(resolveTextGenerationProvider),\n    ),\n    updateSettings: (patch) =>\n      writeSemaphore.withPermits(1)(\n        Effect.gen(function* () {\n          const current = yield* getSettingsFromCache;\n          const nextPersisted = yield* persistProviderEnvironmentSecrets(\n            current,\n            applyServerSettingsPatch(current, patch),\n          );\n          const next = yield* normalizeServerSettings(nextPersisted);\n          yield* writeSettingsAtomically(next);\n          yield* Cache.set(settingsCache, cacheKey, next);\n          yield* emitChange(next);\n          const materialized = yield* materializeProviderEnvironmentSecrets(next);\n          return resolveTextGenerationProvider(materialized);\n        }),\n      ),\n    get streamChanges() {\n      return materializeChanges(Stream.fromPubSub(changesPubSub));\n    },\n    get subscribeChanges() {\n      return PubSub.subscribe(changesPubSub).pipe(\n        Effect.map((subscription) => materializeChanges(Stream.fromSubscription(subscription))),\n      );\n    },\n  } satisfies ServerSettingsService[\"Service\"];\n});\n\nexport const layer = Layer.effect(ServerSettingsService, make);\n","import * as NodeOS from \"node:os\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ServerConfig from \"../config.ts\";\n\nconst CodexAuthJsonSchema = Schema.Struct({\n  tokens: Schema.Struct({\n    account_id: Schema.String,\n  }),\n});\n\nconst ClaudeJsonSchema = Schema.Struct({\n  userID: Schema.String,\n});\n\nexport const TelemetryIdentitySource = Schema.Literals([\"codex\", \"claude\", \"anonymous\"]);\nexport type TelemetryIdentitySource = typeof TelemetryIdentitySource.Type;\n\nexport class TelemetryIdentityReadError extends Schema.TaggedErrorClass<TelemetryIdentityReadError>()(\n  \"TelemetryIdentityReadError\",\n  {\n    source: TelemetryIdentitySource,\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to read ${this.source} telemetry identity at '${this.filePath}'.`;\n  }\n}\n\nexport class TelemetryIdentityDecodeError extends Schema.TaggedErrorClass<TelemetryIdentityDecodeError>()(\n  \"TelemetryIdentityDecodeError\",\n  {\n    source: Schema.Literals([\"codex\", \"claude\"]),\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to decode ${this.source} telemetry identity at '${this.filePath}'.`;\n  }\n}\n\nexport class TelemetryAnonymousIdGenerationError extends Schema.TaggedErrorClass<TelemetryAnonymousIdGenerationError>()(\n  \"TelemetryAnonymousIdGenerationError\",\n  {\n    source: Schema.Literal(\"anonymous\"),\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to generate anonymous telemetry identity for '${this.filePath}'.`;\n  }\n}\n\nexport class TelemetryAnonymousIdPersistenceError extends Schema.TaggedErrorClass<TelemetryAnonymousIdPersistenceError>()(\n  \"TelemetryAnonymousIdPersistenceError\",\n  {\n    source: Schema.Literal(\"anonymous\"),\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to persist anonymous telemetry identity at '${this.filePath}'.`;\n  }\n}\n\nexport class TelemetryIdentityHashError extends Schema.TaggedErrorClass<TelemetryIdentityHashError>()(\n  \"TelemetryIdentityHashError\",\n  {\n    source: TelemetryIdentitySource,\n    algorithm: Schema.Literal(\"SHA-256\"),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to hash ${this.source} telemetry identity with ${this.algorithm}.`;\n  }\n}\n\ntype TelemetryIdentityError =\n  | TelemetryIdentityReadError\n  | TelemetryIdentityDecodeError\n  | TelemetryAnonymousIdGenerationError\n  | TelemetryAnonymousIdPersistenceError\n  | TelemetryIdentityHashError;\n\nconst decodeCodexAuthJson = Schema.decodeEffect(Schema.fromJsonString(CodexAuthJsonSchema));\nconst decodeClaudeJson = Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema));\n\nfunction isNotFoundError(error: PlatformError.PlatformError): boolean {\n  return error.reason._tag === \"NotFound\";\n}\n\nconst getTelemetryIdentityCauseAnnotations = (cause: unknown) => {\n  if (cause instanceof PlatformError.PlatformError) {\n    return {\n      causeKind: \"platform\",\n      platformReason: cause.reason._tag,\n    };\n  }\n  if (cause instanceof Schema.SchemaError) {\n    return { causeKind: \"schema\" };\n  }\n  return { causeKind: \"other\" };\n};\n\nconst logTelemetryIdentityError = (error: TelemetryIdentityError) =>\n  Effect.logWarning(error.message).pipe(\n    Effect.annotateLogs({\n      errorTag: error._tag,\n      source: error.source,\n      ...(\"filePath\" in error ? { filePath: error.filePath } : {}),\n      ...getTelemetryIdentityCauseAnnotations(error.cause),\n      ...(error.stack === undefined ? {} : { errorStack: error.stack }),\n    }),\n  );\n\nconst readIdentityFile = (\n  fileSystem: FileSystem.FileSystem,\n  source: TelemetryIdentitySource,\n  filePath: string,\n) =>\n  fileSystem.readFileString(filePath).pipe(\n    Effect.map(Option.some),\n    Effect.catchTags({\n      PlatformError: (cause) =>\n        isNotFoundError(cause)\n          ? Effect.succeed(Option.none<string>())\n          : Effect.fail(\n              new TelemetryIdentityReadError({\n                source,\n                filePath,\n                cause,\n              }),\n            ),\n    }),\n  );\n\nconst hash = (source: TelemetryIdentitySource, value: string) =>\n  Crypto.Crypto.pipe(\n    Effect.flatMap((crypto) => crypto.digest(\"SHA-256\", new TextEncoder().encode(value))),\n    Effect.map(Encoding.encodeHex),\n    Effect.mapError(\n      (cause) =>\n        new TelemetryIdentityHashError({\n          source,\n          algorithm: \"SHA-256\",\n          cause,\n        }),\n    ),\n  );\n\nconst getCodexAccountId = Effect.fn(\"TelemetryIdentity.getCodexAccountId\")(function* (\n  homeDirectory: string,\n) {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const authJsonPath = path.join(homeDirectory, \".codex\", \"auth.json\");\n  const encoded = yield* readIdentityFile(fileSystem, \"codex\", authJsonPath);\n  if (Option.isNone(encoded)) {\n    return Option.none<string>();\n  }\n  const authJson = yield* decodeCodexAuthJson(encoded.value).pipe(\n    Effect.mapError(\n      (cause) =>\n        new TelemetryIdentityDecodeError({\n          source: \"codex\",\n          filePath: authJsonPath,\n          cause,\n        }),\n    ),\n  );\n\n  return Option.some(authJson.tokens.account_id);\n});\n\nconst getClaudeUserId = Effect.fn(\"TelemetryIdentity.getClaudeUserId\")(function* (\n  homeDirectory: string,\n) {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const claudeJsonPath = path.join(homeDirectory, \".claude.json\");\n  const encoded = yield* readIdentityFile(fileSystem, \"claude\", claudeJsonPath);\n  if (Option.isNone(encoded)) {\n    return Option.none<string>();\n  }\n  const claudeJson = yield* decodeClaudeJson(encoded.value).pipe(\n    Effect.mapError(\n      (cause) =>\n        new TelemetryIdentityDecodeError({\n          source: \"claude\",\n          filePath: claudeJsonPath,\n          cause,\n        }),\n    ),\n  );\n\n  return Option.some(claudeJson.userID);\n});\n\nconst upsertAnonymousId = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const { anonymousIdPath } = yield* ServerConfig.ServerConfig;\n\n  const existing = yield* readIdentityFile(fileSystem, \"anonymous\", anonymousIdPath);\n  if (Option.isSome(existing)) {\n    return existing.value;\n  }\n\n  const anonymousId = yield* Crypto.Crypto.pipe(\n    Effect.flatMap((crypto) => crypto.randomUUIDv4),\n    Effect.mapError(\n      (cause) =>\n        new TelemetryAnonymousIdGenerationError({\n          source: \"anonymous\",\n          filePath: anonymousIdPath,\n          cause,\n        }),\n    ),\n  );\n  yield* fileSystem.writeFileString(anonymousIdPath, anonymousId).pipe(\n    Effect.mapError(\n      (cause) =>\n        new TelemetryAnonymousIdPersistenceError({\n          source: \"anonymous\",\n          filePath: anonymousIdPath,\n          cause,\n        }),\n    ),\n  );\n\n  return anonymousId;\n});\n\n/**\n * getTelemetryIdentifier - Users are \"identified\" by finding the first match of the following, then hashing the value.\n * 1. ~/.codex/auth.json tokens.account_id\n * 2. ~/.claude.json userID\n * 3. ~/.synaptic/telemetry/anonymous-id\n */\nexport const getTelemetryIdentifierForHome = Effect.fn(\"getTelemetryIdentifierForHome\")(\n  function* (homeDirectory: string) {\n    const codexAccountId = yield* getCodexAccountId(homeDirectory).pipe(\n      Effect.catchTags({\n        TelemetryIdentityReadError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n        TelemetryIdentityDecodeError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n      }),\n    );\n    if (Option.isSome(codexAccountId)) {\n      return yield* hash(\"codex\", codexAccountId.value);\n    }\n\n    const claudeUserId = yield* getClaudeUserId(homeDirectory).pipe(\n      Effect.catchTags({\n        TelemetryIdentityReadError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n        TelemetryIdentityDecodeError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n      }),\n    );\n    if (Option.isSome(claudeUserId)) {\n      return yield* hash(\"claude\", claudeUserId.value);\n    }\n\n    const anonymousId = yield* upsertAnonymousId.pipe(\n      Effect.map(Option.some),\n      Effect.catchTags({\n        TelemetryIdentityReadError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n        TelemetryAnonymousIdGenerationError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n        TelemetryAnonymousIdPersistenceError: (error) =>\n          logTelemetryIdentityError(error).pipe(Effect.as(Option.none<string>())),\n      }),\n    );\n    if (Option.isSome(anonymousId)) {\n      return yield* hash(\"anonymous\", anonymousId.value);\n    }\n\n    return null;\n  },\n  Effect.tapError(logTelemetryIdentityError),\n  Effect.orElseSucceed(() => null),\n);\n\nexport const getTelemetryIdentifier = Effect.suspend(() =>\n  getTelemetryIdentifierForHome(NodeOS.homedir()),\n);\n","/**\n * Anonymous PostHog telemetry service.\n *\n * Persists an installation-scoped anonymous identifier, buffers events in\n * memory, and flushes batches over Effect's HTTP client.\n *\n * @module AnalyticsService\n */\nimport { HostProcessArchitecture, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as HttpClient from \"effect/unstable/http/HttpClient\";\nimport * as HttpClientRequest from \"effect/unstable/http/HttpClientRequest\";\nimport * as HttpClientResponse from \"effect/unstable/http/HttpClientResponse\";\n\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport * as ServerConfig from \"../config.ts\";\nimport { getTelemetryIdentifier } from \"./Identify.ts\";\n\ninterface BufferedAnalyticsEvent {\n  readonly event: string;\n  readonly properties?: Readonly<Record<string, unknown>>;\n  readonly capturedAt: string;\n}\n\nconst TelemetryEnvConfig = Config.all({\n  posthogKey: Config.string(\"SYNAPTIC_POSTHOG_KEY\").pipe(\n    Config.withDefault(\"phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m\"),\n  ),\n  posthogHost: Config.string(\"SYNAPTIC_POSTHOG_HOST\").pipe(\n    Config.withDefault(\"https://us.i.posthog.com\"),\n  ),\n  enabled: Config.boolean(\"SYNAPTIC_TELEMETRY_ENABLED\").pipe(Config.withDefault(true)),\n  flushBatchSize: Config.number(\"SYNAPTIC_TELEMETRY_FLUSH_BATCH_SIZE\").pipe(Config.withDefault(20)),\n  maxBufferedEvents: Config.number(\"SYNAPTIC_TELEMETRY_MAX_BUFFERED_EVENTS\").pipe(\n    Config.withDefault(1_000),\n  ),\n  wslDistroName: Config.string(\"WSL_DISTRO_NAME\").pipe(Config.option),\n});\n\nexport class AnalyticsService extends Context.Service<\n  AnalyticsService,\n  {\n    /** Record an anonymous event for best-effort buffered delivery. */\n    readonly record: (\n      event: string,\n      properties?: Readonly<Record<string, unknown>>,\n    ) => Effect.Effect<void>;\n\n    /** Flush all currently queued telemetry events. */\n    readonly flush: Effect.Effect<void>;\n  }\n>()(\"t3/telemetry/AnalyticsService\") {\n  /** No-op layer for callers that intentionally disable telemetry. */\n  static readonly layerTest = Layer.succeed(\n    AnalyticsService,\n    AnalyticsService.of({\n      record: () => Effect.void,\n      flush: Effect.void,\n    }),\n  );\n}\n\nexport const make = Effect.gen(function* () {\n  const telemetryConfig = yield* TelemetryEnvConfig;\n  const httpClient = yield* HttpClient.HttpClient;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const identifier = yield* getTelemetryIdentifier;\n  const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);\n  const clientType = serverConfig.mode === \"desktop\" ? \"desktop-app\" : \"cli-web-client\";\n  const hostPlatform = yield* HostProcessPlatform;\n  const hostArchitecture = yield* HostProcessArchitecture;\n\n  const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>\n    Effect.flatMap(DateTime.now, (now) =>\n      Ref.modify(bufferRef, (current) => {\n        const appended = [\n          ...current,\n          {\n            event,\n            ...(properties ? { properties } : {}),\n            capturedAt: DateTime.formatIso(now),\n          } satisfies BufferedAnalyticsEvent,\n        ];\n\n        const next =\n          appended.length > telemetryConfig.maxBufferedEvents\n            ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)\n            : appended;\n\n        return [\n          {\n            size: next.length,\n            dropped: next.length !== appended.length,\n          } as const,\n          next,\n        ] as const;\n      }),\n    );\n\n  const sendBatch = Effect.fn(\"AnalyticsService.sendBatch\")(function* (\n    events: ReadonlyArray<BufferedAnalyticsEvent>,\n  ) {\n    if (!telemetryConfig.enabled || !identifier) return;\n\n    const payload = {\n      api_key: telemetryConfig.posthogKey,\n      batch: events.map((event) => ({\n        event: event.event,\n        distinct_id: identifier,\n        properties: {\n          ...event.properties,\n          $process_person_profile: false,\n          platform: hostPlatform,\n          wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),\n          arch: hostArchitecture,\n          t3CodeVersion: packageJson.version,\n          clientType,\n        },\n        timestamp: event.capturedAt,\n      })),\n    };\n\n    yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(\n      HttpClientRequest.bodyJson(payload),\n      Effect.flatMap(httpClient.execute),\n      Effect.flatMap(HttpClientResponse.filterStatusOk),\n    );\n  });\n\n  const flush: AnalyticsService[\"Service\"][\"flush\"] = Effect.gen(function* () {\n    while (true) {\n      const batch = yield* Ref.modify(bufferRef, (current) => {\n        if (current.length === 0) {\n          return [[] as ReadonlyArray<BufferedAnalyticsEvent>, current] as const;\n        }\n        const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);\n        const remaining = current.slice(nextBatch.length);\n        return [nextBatch, remaining] as const;\n      });\n\n      if (batch.length === 0) {\n        return;\n      }\n\n      yield* sendBatch(batch).pipe(\n        Effect.catch((error) =>\n          Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(\n            Effect.flatMap(() => Effect.fail(error)),\n          ),\n        ),\n      );\n    }\n  }).pipe(Effect.catch((cause) => Effect.logError(\"Failed to flush telemetry\", { cause })));\n\n  const record: AnalyticsService[\"Service\"][\"record\"] = Effect.fn(\"AnalyticsService.record\")(\n    function* (event, properties) {\n      if (!telemetryConfig.enabled || !identifier) return;\n\n      const enqueueResult = yield* enqueueBufferedEvent(event, properties);\n      if (enqueueResult.dropped) {\n        yield* Effect.logDebug(\"analytics buffer full; dropping oldest event\", {\n          size: enqueueResult.size,\n          event,\n        });\n      }\n    },\n  );\n\n  yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {\n    disableYield: true,\n  }).pipe(Effect.forkScoped);\n\n  yield* Effect.addFinalizer(() => flush);\n\n  return AnalyticsService.of({ record, flush });\n});\n\nexport const layer = Layer.effect(AnalyticsService, make);\n\nexport const layerTest = AnalyticsService.layerTest;\n","import * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as Option from \"effect/Option\";\nimport * as Semaphore from \"effect/Semaphore\";\n\nimport * as ProcessRunner from \"../processRunner.ts\";\n\n/**\n * A pinned runtime is an exact `@dmccore/code@<version>` npm-installed into\n * <baseDir>/runtime/versions/<version>. The boot service points its systemd\n * unit here, and server self-update installs the target version here before\n * switching over, never `npx @dmccore/code`, whose cache is ephemeral and\n * whose registry fetch at boot would make startup depend on the network.\n */\n\nconst PINNED_RUNTIME_DIR = \"runtime\";\nconst PINNED_RUNTIME_INSTALL_TIMEOUT = Duration.minutes(10);\n// Boot-service setup and remote update can construct separate layers. Serialize\n// the complete install transaction across every caller in this process.\nconst pinnedRuntimeInstallLock = Semaphore.makeUnsafe(1);\n\nexport interface PinnedRuntimePaths {\n  readonly versionDir: string;\n  readonly entryPath: string;\n  readonly sentinelPath: string;\n}\n\nexport function pinnedRuntimePaths(\n  path: Path.Path,\n  baseDir: string,\n  version: string,\n): PinnedRuntimePaths {\n  const versionDir = path.join(baseDir, PINNED_RUNTIME_DIR, \"versions\", version);\n  return {\n    versionDir,\n    entryPath: path.join(versionDir, \"node_modules\", \"@dmccore\", \"code\", \"dist\", \"bin.mjs\"),\n    sentinelPath: path.join(versionDir, \".install-complete\"),\n  };\n}\n\nexport class PinnedRuntimeInstallError extends Schema.TaggedErrorClass<PinnedRuntimeInstallError>()(\n  \"PinnedRuntimeInstallError\",\n  {\n    step: Schema.String,\n    exitCode: Schema.optional(Schema.Number),\n    stdoutLength: Schema.optional(Schema.Number),\n    stderrLength: Schema.optional(Schema.Number),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return this.exitCode === undefined\n      ? `Pinned runtime install failed while ${this.step}.`\n      : `Pinned runtime install failed while ${this.step} (exit code ${this.exitCode}).`;\n  }\n}\n\nexport class PinnedRuntimePreflightBlockedError extends Schema.TaggedErrorClass<PinnedRuntimePreflightBlockedError>()(\n  \"PinnedRuntimePreflightBlockedError\",\n  {\n    version: Schema.String,\n    reason: Schema.String,\n  },\n) {\n  override get message(): string {\n    return this.reason;\n  }\n}\n\n/**\n * Installs `@dmccore/code@<version>` into the pinned runtime directory unless a complete\n * install is already there, and returns its paths. The sentinel is written\n * only after npm exits 0; checking the entry file alone is not enough. npm\n * extracts files before running native builds (node-pty), so a killed\n * install leaves a plausible-looking but broken tree behind.\n */\ninterface PinnedRuntimeInstallInput {\n  readonly baseDir: string;\n  readonly version: string;\n  readonly fs: FileSystem.FileSystem;\n  readonly path: Path.Path;\n  readonly runner: ProcessRunner.ProcessRunner[\"Service\"];\n  readonly validate: (\n    paths: PinnedRuntimePaths,\n  ) => Effect.Effect<void, PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError>;\n}\n\nconst installPinnedRuntime = Effect.fn(\"cloud.pinned_runtime.ensure_installed\")(function* (\n  input: PinnedRuntimeInstallInput,\n) {\n  const { fs, runner } = input;\n  const paths = pinnedRuntimePaths(input.path, input.baseDir, input.version);\n  const [versionDirExists, entryExists, sentinel] = yield* Effect.all([\n    fs.exists(paths.versionDir),\n    fs.exists(paths.entryPath),\n    fs.readFileString(paths.sentinelPath).pipe(Effect.option),\n  ]).pipe(\n    Effect.mapError(\n      (cause) => new PinnedRuntimeInstallError({ step: \"checking the pinned runtime\", cause }),\n    ),\n  );\n  const alreadyPinned =\n    entryExists && Option.isSome(sentinel) && sentinel.value.trim() === input.version;\n  if (alreadyPinned) {\n    yield* input.validate(paths);\n    return paths;\n  }\n  if (versionDirExists) {\n    yield* fs.remove(paths.versionDir, { recursive: true, force: true }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new PinnedRuntimeInstallError({\n            step: \"removing an incomplete pinned runtime\",\n            cause,\n          }),\n      ),\n    );\n  }\n\n  const versionsDir = input.path.dirname(paths.versionDir);\n  yield* fs.makeDirectory(versionsDir, { recursive: true }).pipe(\n    Effect.mapError(\n      (cause) =>\n        new PinnedRuntimeInstallError({\n          step: \"preparing the pinned runtime directory\",\n          cause,\n        }),\n    ),\n  );\n  const stagingDir = yield* fs\n    .makeTempDirectory({\n      directory: versionsDir,\n      prefix: \".staging-\",\n    })\n    .pipe(\n      Effect.mapError(\n        (cause) =>\n          new PinnedRuntimeInstallError({\n            step: \"preparing the pinned runtime directory\",\n            cause,\n          }),\n      ),\n    );\n  const stagingPaths: PinnedRuntimePaths = {\n    versionDir: stagingDir,\n    entryPath: input.path.join(stagingDir, \"node_modules\", \"@dmccore\", \"code\", \"dist\", \"bin.mjs\"),\n    sentinelPath: input.path.join(stagingDir, \".install-complete\"),\n  };\n\n  return yield* Effect.gen(function* () {\n    const installStep = \"installing the pinned server runtime (this can take a few minutes)\";\n    yield* runner\n      .run({\n        command: \"npm\",\n        args: [\n          \"install\",\n          \"--prefix\",\n          stagingDir,\n          \"--no-fund\",\n          \"--no-audit\",\n          `@dmccore/code@${input.version}`,\n        ],\n        // Native dependencies may compile from source on slower machines.\n        timeout: PINNED_RUNTIME_INSTALL_TIMEOUT,\n      })\n      .pipe(\n        Effect.mapError((cause) => new PinnedRuntimeInstallError({ step: installStep, cause })),\n        Effect.filterOrFail(\n          (result) => result.code === 0,\n          (result) =>\n            new PinnedRuntimeInstallError({\n              step: installStep,\n              exitCode: Number(result.code),\n              stdoutLength: result.stdout.length,\n              stderrLength: result.stderr.length,\n            }),\n        ),\n      );\n\n    yield* input.validate(stagingPaths);\n    yield* fs\n      .writeFileString(stagingPaths.sentinelPath, `${input.version}\\n`)\n      .pipe(\n        Effect.mapError(\n          (cause) =>\n            new PinnedRuntimeInstallError({ step: \"recording the completed install\", cause }),\n        ),\n      );\n    const published = yield* fs.rename(stagingDir, paths.versionDir).pipe(\n      Effect.as(true),\n      Effect.catch((cause) =>\n        Effect.all([\n          fs.exists(paths.entryPath),\n          fs.readFileString(paths.sentinelPath).pipe(Effect.option),\n        ]).pipe(\n          Effect.mapError(\n            (checkCause) =>\n              new PinnedRuntimeInstallError({\n                step: \"checking a concurrently published pinned runtime\",\n                cause: checkCause,\n              }),\n          ),\n          Effect.flatMap(([publishedEntryExists, publishedSentinel]) =>\n            publishedEntryExists &&\n            Option.isSome(publishedSentinel) &&\n            publishedSentinel.value.trim() === input.version\n              ? Effect.succeed(false)\n              : Effect.fail(\n                  new PinnedRuntimeInstallError({\n                    step: \"publishing the pinned runtime\",\n                    cause,\n                  }),\n                ),\n          ),\n        ),\n      ),\n    );\n    if (!published) yield* input.validate(paths);\n    return paths;\n  }).pipe(\n    Effect.ensuring(fs.remove(stagingDir, { recursive: true, force: true }).pipe(Effect.ignore)),\n  );\n});\n\nexport const ensurePinnedRuntimeInstalled = (input: PinnedRuntimeInstallInput) =>\n  pinnedRuntimeInstallLock.withPermit(installPinnedRuntime(input));\n","import type { ServerSelfUpdateOutcome } from \"@t3tools/contracts\";\n\n/** Protocol 2 snapshots SQLite before trials so migrations can be rolled back safely. */\nexport const SERVICE_LAUNCHER_PROTOCOL = 2 as const;\nexport const SERVICE_LAUNCHER_CONTEXT_ENV = \"SYNAPTIC_SERVICE_LAUNCHER_CONTEXT\";\nexport const SERVICE_LAUNCHER_FILE = \"service-launcher.mjs\";\nexport const SERVICE_STATE_FILE = \"service-state.json\";\n/** Written by the launcher just before an explicit stop kills its child, so\n    the child can tell \"the service is going away\" from \"the launcher is about\n    to start my replacement\" while a pending update is recorded. */\nexport const SERVICE_STOP_MARKER_FILE = \".service-stopping\";\n\nexport interface PendingServiceUpdate {\n  readonly id: string;\n  readonly fromVersion: string;\n  readonly targetVersion: string;\n  readonly dbPath: string;\n  readonly status: \"pending\";\n}\n\nexport type ServiceUpdateRecord = PendingServiceUpdate | ServerSelfUpdateOutcome;\n\nexport interface ServiceState {\n  readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;\n  readonly activeVersion: string;\n  readonly update?: ServiceUpdateRecord;\n}\n\n/** Context is copied from launcher-owned state when a child is spawned. */\nexport interface ServiceLauncherContext {\n  readonly protocol: typeof SERVICE_LAUNCHER_PROTOCOL;\n  readonly childVersion: string;\n  readonly update?: ServiceUpdateRecord;\n}\n\nexport type ServiceLauncherChildMessage =\n  | {\n      readonly type: \"request-update\";\n      readonly targetVersion: string;\n      readonly dbPath: string;\n    }\n  | {\n      readonly type: \"prepared\";\n      readonly updateId: string;\n    };\n\nexport type ServiceLauncherParentMessage =\n  | {\n      readonly type: \"update-accepted\";\n      readonly updateId: string;\n    }\n  | {\n      readonly type: \"update-rejected\";\n      readonly reason: string;\n    }\n  | {\n      readonly type: \"committed\";\n      readonly updateId: string;\n    };\n\nconst SEMVER_NUMBER = \"(?:0|[1-9]\\\\d*)\";\nconst SEMVER_PRERELEASE = `(?:${SEMVER_NUMBER}|[0-9]*[A-Za-z-][0-9A-Za-z-]*)`;\nconst EXACT_SERVICE_VERSION = new RegExp(\n  `^${SEMVER_NUMBER}\\\\.${SEMVER_NUMBER}\\\\.${SEMVER_NUMBER}(?:-${SEMVER_PRERELEASE}(?:\\\\.${SEMVER_PRERELEASE})*)?(?:\\\\+[0-9A-Za-z-]+(?:\\\\.[0-9A-Za-z-]+)*)?$`,\n);\n\n/** Accepts exact SemVer only: never dist-tags or ranges passed to npm or filesystem paths. */\nexport const isExactServiceVersion = (version: string): boolean =>\n  EXACT_SERVICE_VERSION.test(version);\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n  typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport function decodeServiceUpdate(value: unknown): ServiceUpdateRecord | undefined {\n  if (!isRecord(value)) return undefined;\n  const { id, fromVersion, targetVersion, status } = value;\n  if (\n    typeof id !== \"string\" ||\n    id.trim() === \"\" ||\n    typeof fromVersion !== \"string\" ||\n    !isExactServiceVersion(fromVersion) ||\n    typeof targetVersion !== \"string\" ||\n    !isExactServiceVersion(targetVersion)\n  ) {\n    return undefined;\n  }\n  if (status === \"pending\") {\n    return typeof value.dbPath === \"string\" && value.dbPath.trim() !== \"\"\n      ? { id, fromVersion, targetVersion, dbPath: value.dbPath, status }\n      : undefined;\n  }\n  if (\n    (status === \"committed\" || status === \"rolled-back\" || status === \"failed\") &&\n    (value.reason === undefined || (typeof value.reason === \"string\" && value.reason.trim() !== \"\"))\n  ) {\n    return {\n      id,\n      fromVersion,\n      targetVersion,\n      status,\n      ...(typeof value.reason === \"string\" ? { reason: value.reason } : {}),\n    };\n  }\n  return undefined;\n}\n\n/** SemVer precedence for exact versions. Build metadata is ignored. */\nexport function compareExactServiceVersions(left: string, right: string): number {\n  const parse = (version: string) => {\n    const withoutBuild = version.split(\"+\", 1)[0] ?? version;\n    const separator = withoutBuild.indexOf(\"-\");\n    const core = separator === -1 ? withoutBuild : withoutBuild.slice(0, separator);\n    const prerelease = separator === -1 ? undefined : withoutBuild.slice(separator + 1);\n    const [major = \"0\", minor = \"0\", patch = \"0\"] = core.split(\".\");\n    return {\n      core: [BigInt(major), BigInt(minor), BigInt(patch)] as const,\n      prerelease: prerelease?.split(\".\") ?? [],\n    };\n  };\n  const a = parse(left);\n  const b = parse(right);\n  for (let index = 0; index < 3; index += 1) {\n    const x = a.core[index] ?? 0n;\n    const y = b.core[index] ?? 0n;\n    if (x !== y) return x < y ? -1 : 1;\n  }\n  if (a.prerelease.length === 0 || b.prerelease.length === 0) {\n    return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;\n  }\n  const count = Math.max(a.prerelease.length, b.prerelease.length);\n  for (let index = 0; index < count; index += 1) {\n    const x = a.prerelease[index];\n    const y = b.prerelease[index];\n    if (x === undefined || y === undefined) return x === undefined ? -1 : 1;\n    if (x === y) continue;\n    const xNumeric = /^\\d+$/.test(x);\n    const yNumeric = /^\\d+$/.test(y);\n    if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;\n    if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;\n    return x < y ? -1 : 1;\n  }\n  return 0;\n}\n\nexport function decodeServiceState(value: unknown): ServiceState | undefined {\n  if (!isRecord(value)) return undefined;\n  const update = value.update === undefined ? undefined : decodeServiceUpdate(value.update);\n  if (\n    value.protocol !== SERVICE_LAUNCHER_PROTOCOL ||\n    typeof value.activeVersion !== \"string\" ||\n    !isExactServiceVersion(value.activeVersion) ||\n    (value.update !== undefined && update === undefined) ||\n    (update !== undefined &&\n      compareExactServiceVersions(update.targetVersion, update.fromVersion) <= 0) ||\n    (update?.status === \"pending\" && update.fromVersion !== value.activeVersion) ||\n    (update?.status === \"committed\" && update.targetVersion !== value.activeVersion) ||\n    ((update?.status === \"rolled-back\" || update?.status === \"failed\") &&\n      update.fromVersion !== value.activeVersion)\n  ) {\n    return undefined;\n  }\n  return {\n    protocol: SERVICE_LAUNCHER_PROTOCOL,\n    activeVersion: value.activeVersion,\n    ...(update === undefined ? {} : { update }),\n  };\n}\n\nexport function parseServiceState(value: string): ServiceState | undefined {\n  try {\n    return decodeServiceState(JSON.parse(value) as unknown);\n  } catch {\n    return undefined;\n  }\n}\n\n/** Detects an in-flight update across launcher protocol versions before replacing its state. */\nexport function serviceStateHasPendingUpdate(value: string): boolean {\n  try {\n    const parsed: unknown = JSON.parse(value);\n    return isRecord(parsed) && isRecord(parsed.update) && parsed.update.status === \"pending\";\n  } catch {\n    return false;\n  }\n}\n\nexport function decodeServiceLauncherContext(value: string): ServiceLauncherContext | undefined {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(value) as unknown;\n  } catch {\n    return undefined;\n  }\n  if (\n    !isRecord(parsed) ||\n    parsed.protocol !== SERVICE_LAUNCHER_PROTOCOL ||\n    typeof parsed.childVersion !== \"string\" ||\n    !isExactServiceVersion(parsed.childVersion)\n  ) {\n    return undefined;\n  }\n  const update = parsed.update === undefined ? undefined : decodeServiceUpdate(parsed.update);\n  if (parsed.update !== undefined && update === undefined) return undefined;\n  const selectedVersion =\n    update?.status === \"pending\" || update?.status === \"committed\"\n      ? update.targetVersion\n      : update === undefined\n        ? parsed.childVersion\n        : update.fromVersion;\n  if (parsed.childVersion !== selectedVersion) {\n    return undefined;\n  }\n  return {\n    protocol: SERVICE_LAUNCHER_PROTOCOL,\n    childVersion: parsed.childVersion,\n    ...(update === undefined ? {} : { update }),\n  };\n}\n\nexport function decodeServiceLauncherChildMessage(\n  value: unknown,\n): ServiceLauncherChildMessage | undefined {\n  if (!isRecord(value)) return undefined;\n  if (\n    value.type === \"request-update\" &&\n    typeof value.targetVersion === \"string\" &&\n    typeof value.dbPath === \"string\"\n  ) {\n    return { type: value.type, targetVersion: value.targetVersion, dbPath: value.dbPath };\n  }\n  return value.type === \"prepared\" && typeof value.updateId === \"string\"\n    ? { type: value.type, updateId: value.updateId }\n    : undefined;\n}\n\nexport function decodeServiceLauncherParentMessage(\n  value: unknown,\n): ServiceLauncherParentMessage | undefined {\n  if (!isRecord(value)) return undefined;\n  if (value.type === \"update-rejected\" && typeof value.reason === \"string\") {\n    return { type: value.type, reason: value.reason };\n  }\n  if (value.type === \"update-accepted\" && typeof value.updateId === \"string\") {\n    return { type: value.type, updateId: value.updateId };\n  }\n  return value.type === \"committed\" && typeof value.updateId === \"string\"\n    ? { type: value.type, updateId: value.updateId }\n    : undefined;\n}\n","import packageJson from \"../../package.json\" with { type: \"json\" };\nimport { SERVICE_LAUNCHER_PROTOCOL } from \"./serviceProtocol.ts\";\n\nexport type ServicePreflightResult =\n  | {\n      readonly status: \"ready\";\n      readonly version: string;\n      readonly launcherProtocol: typeof SERVICE_LAUNCHER_PROTOCOL;\n    }\n  | {\n      readonly status: \"blocked\";\n      readonly version: string;\n      readonly reason: string;\n    };\n\nexport function runServicePreflight(input: {\n  /** Older servers always pass this flag when invoking a staged preflight. */\n  readonly databasePath: string;\n  readonly launcherProtocol: number;\n  readonly version?: string;\n}): ServicePreflightResult {\n  const version = input.version ?? packageJson.version;\n  if (input.launcherProtocol !== SERVICE_LAUNCHER_PROTOCOL) {\n    return {\n      status: \"blocked\",\n      version,\n      reason:\n        \"This release requires a newer Synaptic Code service launcher. Update it on the server machine.\",\n    };\n  }\n\n  return { status: \"ready\", version, launcherProtocol: SERVICE_LAUNCHER_PROTOCOL };\n}\n\nexport function decodeServicePreflightResult(value: unknown): ServicePreflightResult | undefined {\n  if (typeof value !== \"object\" || value === null) {\n    return undefined;\n  }\n  const record = value as Record<string, unknown>;\n  if (\n    record.status === \"ready\" &&\n    record.launcherProtocol === SERVICE_LAUNCHER_PROTOCOL &&\n    typeof record.version === \"string\"\n  ) {\n    return {\n      status: \"ready\",\n      version: record.version,\n      launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,\n    };\n  }\n  if (\n    record.status === \"blocked\" &&\n    typeof record.version === \"string\" &&\n    typeof record.reason === \"string\"\n  ) {\n    return { status: \"blocked\", version: record.version, reason: record.reason };\n  }\n  return undefined;\n}\n","import type { ServerSelfUpdateOutcome } from \"@t3tools/contracts\";\nimport { HostProcessEnvironment } from \"@t3tools/shared/hostProcess\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\n\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport {\n  decodeServiceLauncherContext,\n  decodeServiceLauncherParentMessage,\n  SERVICE_LAUNCHER_CONTEXT_ENV,\n  type ServiceLauncherChildMessage,\n  type ServiceLauncherParentMessage,\n} from \"./serviceProtocol.ts\";\n\nexport class ServiceLauncherClientError extends Schema.TaggedErrorClass<ServiceLauncherClientError>()(\n  \"ServiceLauncherClientError\",\n  {\n    operation: Schema.Literals([\n      \"decode-context\",\n      \"version-mismatch\",\n      \"ipc-unavailable\",\n      \"unmanaged\",\n      \"send\",\n      \"disconnect\",\n      \"timeout\",\n    ]),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    switch (this.operation) {\n      case \"decode-context\":\n        return \"The service launcher supplied invalid startup context.\";\n      case \"version-mismatch\":\n        return \"The service launcher started a different @dmccore/code version.\";\n      case \"ipc-unavailable\":\n        return \"The service launcher IPC channel is unavailable.\";\n      case \"unmanaged\":\n        return \"This server is not managed by the launcher.\";\n      case \"send\":\n        return \"Could not send a request to the service launcher.\";\n      case \"disconnect\":\n        return \"The service launcher disconnected before acknowledging the request.\";\n      case \"timeout\":\n        return \"The service launcher did not respond within 30 seconds.\";\n    }\n  }\n}\n\nexport class ServiceLauncherRejectedError extends Schema.TaggedErrorClass<ServiceLauncherRejectedError>()(\n  \"ServiceLauncherRejectedError\",\n  {\n    targetVersion: Schema.String,\n    reason: Schema.String,\n  },\n) {\n  override get message(): string {\n    return this.reason;\n  }\n}\n\ninterface ServiceLauncherProcess {\n  readonly connected: boolean;\n  readonly send: (\n    message: ServiceLauncherChildMessage,\n    callback?: (error: Error | null) => void,\n  ) => boolean;\n  readonly on: (\n    event: \"message\" | \"disconnect\",\n    listener: (...args: ReadonlyArray<unknown>) => void,\n  ) => void;\n  readonly off: (\n    event: \"message\" | \"disconnect\",\n    listener: (...args: ReadonlyArray<unknown>) => void,\n  ) => void;\n}\n\nexport const ServiceLauncherHostProcess = Context.Reference<ServiceLauncherProcess>(\n  \"t3/cloud/serviceLauncherHostProcess\",\n  {\n    defaultValue: () => ({\n      connected: process.connected && process.send !== undefined,\n      send: (message, callback) => {\n        if (process.send === undefined) return false;\n        return callback === undefined ? process.send(message) : process.send(message, callback);\n      },\n      on: (event, listener) => {\n        process.on(event, listener);\n      },\n      off: (event, listener) => {\n        process.off(event, listener);\n      },\n    }),\n  },\n);\n\nexport class ServiceLauncherClient extends Context.Service<\n  ServiceLauncherClient,\n  {\n    readonly managed: boolean;\n    readonly requestUpdate: (input: {\n      readonly targetVersion: string;\n      readonly dbPath: string;\n    }) => Effect.Effect<string, ServiceLauncherClientError | ServiceLauncherRejectedError>;\n    readonly prepareTrial: Effect.Effect<\n      ServerSelfUpdateOutcome | undefined,\n      ServiceLauncherClientError\n    >;\n  }\n>()(\"t3/cloud/serviceLauncherClient\") {}\n\nconst resolveStartup = Effect.fn(\"cloud.service_launcher_client.resolve_startup\")(\n  function* (options?: { readonly currentVersion?: string }) {\n    const host = yield* ServiceLauncherHostProcess;\n    const environment = yield* HostProcessEnvironment;\n    const currentVersion = options?.currentVersion ?? packageJson.version;\n    const rawContext = environment[SERVICE_LAUNCHER_CONTEXT_ENV];\n    const context = rawContext === undefined ? undefined : decodeServiceLauncherContext(rawContext);\n\n    if (rawContext !== undefined && context === undefined) {\n      return yield* new ServiceLauncherClientError({ operation: \"decode-context\" });\n    }\n    if (context !== undefined && context.childVersion !== currentVersion) {\n      return yield* new ServiceLauncherClientError({ operation: \"version-mismatch\" });\n    }\n\n    const managed = context !== undefined && host.connected;\n    if (context !== undefined && !managed) {\n      return yield* new ServiceLauncherClientError({ operation: \"ipc-unavailable\" });\n    }\n\n    return { host, context, managed };\n  },\n);\n\nexport const resolveServiceLauncherMode = Effect.fn(\"cloud.service_launcher_client.resolve_mode\")(\n  function* () {\n    const { managed } = yield* resolveStartup();\n    return { managed };\n  },\n);\n\nexport const make = Effect.fn(\"cloud.service_launcher_client.make\")(function* (options?: {\n  readonly currentVersion?: string;\n}) {\n  const { host, context, managed } = yield* resolveStartup(options);\n\n  const exchange = (\n    message: ServiceLauncherChildMessage,\n    accept: (reply: ServiceLauncherParentMessage) => boolean,\n  ) =>\n    Effect.callback<ServiceLauncherParentMessage, ServiceLauncherClientError>((resume) => {\n      if (!managed) {\n        resume(Effect.fail(new ServiceLauncherClientError({ operation: \"unmanaged\" })));\n        return;\n      }\n\n      let settled = false;\n      const cleanup = () => {\n        host.off(\"message\", onMessage);\n        host.off(\"disconnect\", onDisconnect);\n      };\n      const settle = (\n        effect: Effect.Effect<ServiceLauncherParentMessage, ServiceLauncherClientError>,\n      ) => {\n        if (settled) return;\n        settled = true;\n        cleanup();\n        resume(effect);\n      };\n      const onMessage = (...args: ReadonlyArray<unknown>) => {\n        const reply = decodeServiceLauncherParentMessage(args[0]);\n        if (reply !== undefined && accept(reply)) settle(Effect.succeed(reply));\n      };\n      const onDisconnect = () =>\n        settle(Effect.fail(new ServiceLauncherClientError({ operation: \"disconnect\" })));\n\n      host.on(\"message\", onMessage);\n      host.on(\"disconnect\", onDisconnect);\n      try {\n        host.send(message, (error) => {\n          if (error !== null) {\n            settle(\n              Effect.fail(new ServiceLauncherClientError({ operation: \"send\", cause: error })),\n            );\n          }\n        });\n      } catch (cause) {\n        settle(Effect.fail(new ServiceLauncherClientError({ operation: \"send\", cause })));\n      }\n\n      return Effect.sync(cleanup);\n    }).pipe(\n      Effect.timeoutOrElse({\n        duration: \"30 seconds\",\n        orElse: () => Effect.fail(new ServiceLauncherClientError({ operation: \"timeout\" })),\n      }),\n    );\n\n  const requestUpdate = (input: { readonly targetVersion: string; readonly dbPath: string }) =>\n    exchange(\n      { type: \"request-update\", ...input },\n      (reply) => reply.type === \"update-accepted\" || reply.type === \"update-rejected\",\n    ).pipe(\n      Effect.flatMap((reply) =>\n        reply.type === \"update-accepted\"\n          ? Effect.succeed(reply.updateId)\n          : reply.type === \"update-rejected\"\n            ? Effect.fail(\n                new ServiceLauncherRejectedError({\n                  targetVersion: input.targetVersion,\n                  reason: reply.reason,\n                }),\n              )\n            : Effect.die(\"service launcher returned an impossible update response\"),\n      ),\n    );\n\n  const pending = context?.update?.status === \"pending\" ? context.update : undefined;\n  const outcome =\n    context?.update === undefined || context.update.status === \"pending\"\n      ? undefined\n      : context.update;\n  const prepareTrial =\n    pending !== undefined\n      ? exchange(\n          { type: \"prepared\", updateId: pending.id },\n          (reply) => reply.type === \"committed\" && reply.updateId === pending.id,\n        ).pipe(\n          Effect.flatMap((reply) => {\n            if (reply.type !== \"committed\") {\n              return Effect.die(\"service launcher returned an impossible prepared response\");\n            }\n            return Effect.succeed({\n              id: pending.id,\n              fromVersion: pending.fromVersion,\n              targetVersion: pending.targetVersion,\n              status: \"committed\" as const,\n            });\n          }),\n        )\n      : Effect.succeed(outcome);\n\n  return ServiceLauncherClient.of({\n    managed,\n    requestUpdate,\n    prepareTrial,\n  });\n});\n\nexport const layer = Layer.effect(ServiceLauncherClient, make());\n","import {\n  ServerSelfUpdateError,\n  type ServerSelfUpdateCapability,\n  type ServerSelfUpdateInput,\n  type ServerSelfUpdateProgressStage,\n  type ServerSelfUpdateResult,\n} from \"@t3tools/contracts\";\nimport { HostProcessExecutablePath } from \"@t3tools/shared/hostProcess\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport * as ProcessRunner from \"../processRunner.ts\";\nimport {\n  ensurePinnedRuntimeInstalled,\n  PinnedRuntimeInstallError,\n  PinnedRuntimePreflightBlockedError,\n} from \"./pinnedRuntime.ts\";\nimport { decodeServicePreflightResult } from \"./servicePreflight.ts\";\nimport * as ServiceLauncherClient from \"./serviceLauncherClient.ts\";\nimport { isExactServiceVersion, SERVICE_LAUNCHER_PROTOCOL } from \"./serviceProtocol.ts\";\n\nconst PREFLIGHT_TIMEOUT = Duration.seconds(30);\n\nexport function resolveServerSelfUpdateCapability(input: {\n  readonly desktopManaged: boolean;\n  readonly launcherManaged: boolean;\n}): ServerSelfUpdateCapability | null {\n  if (input.desktopManaged) return \"desktop-managed\" as const;\n  return input.launcherManaged ? (\"boot-service\" as const) : null;\n}\n\nexport class ServerSelfUpdate extends Context.Service<\n  ServerSelfUpdate,\n  {\n    readonly update: (\n      input: ServerSelfUpdateInput,\n      reportProgress?: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,\n    ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;\n  }\n>()(\"t3/cloud/selfUpdate/ServerSelfUpdate\") {}\n\nexport const make = Effect.fn(\"cloud.server_self_update.make\")(function* () {\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;\n  const runner = yield* ProcessRunner.ProcessRunner;\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const execPath = yield* HostProcessExecutablePath;\n  const inFlight = yield* Ref.make(false);\n\n  const capability: ServerSelfUpdateCapability | null =\n    serverConfig.mode === \"desktop\" ? \"desktop-managed\" : launcher.managed ? \"boot-service\" : null;\n  const failWith = (reason: string, cause?: unknown) =>\n    cause === undefined\n      ? new ServerSelfUpdateError({ reason })\n      : new ServerSelfUpdateError({ reason, cause });\n\n  const update: ServerSelfUpdate[\"Service\"][\"update\"] = Effect.fn(\n    \"cloud.server_self_update.update\",\n  )(function* (input, reportProgress = () => Effect.void) {\n    if (capability === \"desktop-managed\") {\n      return yield* failWith(\n        \"This server is managed by the Synaptic Code desktop app on its machine; update the desktop app to update it.\",\n      );\n    }\n    if (capability === null) {\n      return yield* failWith(\n        \"Remote updates require the Synaptic Code background service. Run `synaptic-code service install` on the server machine.\",\n      );\n    }\n\n    const targetVersion = input.targetVersion.trim();\n    if (!isExactServiceVersion(targetVersion)) {\n      return yield* failWith(`'${targetVersion}' is not an exact @dmccore/code version.`);\n    }\n    if (yield* Ref.getAndSet(inFlight, true)) {\n      return yield* failWith(\"A server update is already in progress.\");\n    }\n\n    return yield* Effect.gen(function* () {\n      yield* reportProgress(\"downloading\");\n      const paths = yield* ensurePinnedRuntimeInstalled({\n        baseDir: serverConfig.baseDir,\n        version: targetVersion,\n        fs,\n        path,\n        runner,\n        validate: (runtime) =>\n          runner\n            .run({\n              command: execPath,\n              args: [\n                runtime.entryPath,\n                \"__service-preflight\",\n                \"--database-path\",\n                serverConfig.dbPath,\n                \"--launcher-protocol\",\n                String(SERVICE_LAUNCHER_PROTOCOL),\n              ],\n              timeout: PREFLIGHT_TIMEOUT,\n            })\n            .pipe(\n              Effect.mapError(\n                (cause) =>\n                  new PinnedRuntimeInstallError({\n                    step: \"running the staged service preflight\",\n                    cause,\n                  }),\n              ),\n              Effect.flatMap(\n                (\n                  result,\n                ): Effect.Effect<\n                  void,\n                  PinnedRuntimeInstallError | PinnedRuntimePreflightBlockedError\n                > => {\n                  if (result.code !== 0) {\n                    return Effect.fail(\n                      new PinnedRuntimeInstallError({\n                        step: \"running the staged service preflight\",\n                        exitCode: Number(result.code),\n                        stdoutLength: result.stdout.length,\n                        stderrLength: result.stderr.length,\n                      }),\n                    );\n                  }\n                  let parsed: unknown;\n                  try {\n                    parsed = JSON.parse(result.stdout.trim());\n                  } catch (cause) {\n                    return Effect.fail(\n                      new PinnedRuntimeInstallError({\n                        step: \"decoding the staged service preflight\",\n                        cause,\n                      }),\n                    );\n                  }\n                  const preflight = decodeServicePreflightResult(parsed);\n                  if (preflight === undefined || preflight.version !== targetVersion) {\n                    return Effect.fail(\n                      new PinnedRuntimeInstallError({\n                        step: \"verifying the staged service preflight\",\n                      }),\n                    );\n                  }\n                  return preflight.status === \"ready\"\n                    ? Effect.void\n                    : Effect.fail(\n                        new PinnedRuntimePreflightBlockedError({\n                          version: targetVersion,\n                          reason: preflight.reason,\n                        }),\n                      );\n                },\n              ),\n            ),\n      }).pipe(\n        Effect.mapError((error) =>\n          error._tag === \"PinnedRuntimePreflightBlockedError\"\n            ? failWith(error.reason, error)\n            : failWith(`Could not prepare @dmccore/code@${targetVersion}.`, error),\n        ),\n      );\n\n      yield* reportProgress(\"installing\");\n      const updateId = yield* launcher\n        .requestUpdate({ targetVersion, dbPath: serverConfig.dbPath })\n        .pipe(\n          Effect.mapError((error) =>\n            failWith(\n              error._tag === \"ServiceLauncherRejectedError\"\n                ? error.reason\n                : \"Could not ask the service launcher to activate the prepared update.\",\n              error,\n            ),\n          ),\n        );\n\n      yield* Effect.logInfo(\"Server update prepared; handing off to the service launcher.\", {\n        updateId,\n        targetVersion,\n        runtimePath: paths.entryPath,\n      });\n      return { targetVersion, method: \"boot-service\" as const, updateId };\n    }).pipe(Effect.onError(() => Ref.set(inFlight, false)));\n  });\n\n  return ServerSelfUpdate.of({ update });\n});\n\nexport const layer = Layer.effect(ServerSelfUpdate, make()).pipe(\n  Layer.provide(ProcessRunner.layer),\n);\n","import { HostProcessHostname, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ProcessRunner from \"../processRunner.ts\";\n\ninterface ResolveServerEnvironmentLabelInput {\n  readonly cwdBaseName: string;\n}\n\nconst ServerEnvironmentLabelCommandProbe = Schema.Literals([\n  \"macos-computer-name\",\n  \"linux-pretty-hostname\",\n]);\ntype ServerEnvironmentLabelCommandProbe = typeof ServerEnvironmentLabelCommandProbe.Type;\n\nexport class ServerEnvironmentLabelFileError extends Schema.TaggedErrorClass<ServerEnvironmentLabelFileError>()(\n  \"ServerEnvironmentLabelFileError\",\n  {\n    operation: Schema.Literals([\"inspect\", \"read\"]),\n    path: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to ${this.operation} environment-label file at ${this.path}.`;\n  }\n}\n\nexport class ServerEnvironmentLabelCommandError extends Schema.TaggedErrorClass<ServerEnvironmentLabelCommandError>()(\n  \"ServerEnvironmentLabelCommandError\",\n  {\n    probe: ServerEnvironmentLabelCommandProbe,\n    executable: Schema.String,\n    argumentCount: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to run environment-label probe '${this.probe}' with ${this.executable}.`;\n  }\n}\n\nfunction normalizeLabel(value: string | null | undefined): string | null {\n  const trimmed = value?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : null;\n}\n\nfunction parseMachineInfoValue(raw: string, key: string): string | null {\n  for (const line of raw.split(/\\r?\\n/g)) {\n    const trimmed = line.trim();\n    if (trimmed.length === 0 || trimmed.startsWith(\"#\") || !trimmed.startsWith(`${key}=`)) {\n      continue;\n    }\n    const value = trimmed.slice(key.length + 1).trim();\n    if (\n      (value.startsWith('\"') && value.endsWith('\"')) ||\n      (value.startsWith(\"'\") && value.endsWith(\"'\"))\n    ) {\n      return normalizeLabel(value.slice(1, -1));\n    }\n    return normalizeLabel(value);\n  }\n  return null;\n}\n\nconst readLinuxMachineInfo = Effect.fn(\"readLinuxMachineInfo\")(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const machineInfoPath = \"/etc/machine-info\";\n  return yield* fileSystem.exists(machineInfoPath).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ServerEnvironmentLabelFileError({\n          operation: \"inspect\",\n          path: machineInfoPath,\n          cause,\n        }),\n    ),\n    Effect.flatMap((exists) =>\n      exists\n        ? fileSystem.readFileString(machineInfoPath).pipe(\n            Effect.mapError(\n              (cause) =>\n                new ServerEnvironmentLabelFileError({\n                  operation: \"read\",\n                  path: machineInfoPath,\n                  cause,\n                }),\n            ),\n          )\n        : Effect.succeed(null),\n    ),\n    Effect.catchTags({\n      ServerEnvironmentLabelFileError: (error) =>\n        Effect.logDebug(error.message).pipe(\n          Effect.annotateLogs({\n            operation: error.operation,\n            path: error.path,\n            cause: error,\n          }),\n          Effect.as(null),\n        ),\n    }),\n  );\n});\n\nconst runFriendlyLabelCommand = Effect.fn(\"runFriendlyLabelCommand\")(function* (input: {\n  readonly probe: ServerEnvironmentLabelCommandProbe;\n  readonly command: string;\n  readonly args: readonly string[];\n}) {\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n  const result = yield* processRunner\n    .run({\n      command: input.command,\n      args: input.args,\n      timeoutBehavior: \"timedOutResult\",\n    })\n    .pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerEnvironmentLabelCommandError({\n            probe: input.probe,\n            executable: input.command,\n            argumentCount: input.args.length,\n            cause,\n          }),\n      ),\n      Effect.map(Option.some),\n      Effect.catchTags({\n        ServerEnvironmentLabelCommandError: (error) =>\n          Effect.logDebug(error.message).pipe(\n            Effect.annotateLogs({\n              probe: error.probe,\n              executable: error.executable,\n              argumentCount: error.argumentCount,\n              cause: error,\n            }),\n            Effect.as(Option.none()),\n          ),\n      }),\n    );\n\n  if (Option.isNone(result) || result.value.code !== 0) {\n    return null;\n  }\n\n  return normalizeLabel(result.value.stdout);\n});\n\nconst resolveFriendlyHostLabel = Effect.fn(\"resolveFriendlyHostLabel\")(function* () {\n  const platform = yield* HostProcessPlatform;\n  if (platform === \"darwin\") {\n    return yield* runFriendlyLabelCommand({\n      probe: \"macos-computer-name\",\n      command: \"scutil\",\n      args: [\"--get\", \"ComputerName\"],\n    });\n  }\n\n  if (platform === \"linux\") {\n    const machineInfo = normalizeLabel(yield* readLinuxMachineInfo());\n    if (machineInfo) {\n      const prettyHostname = parseMachineInfoValue(machineInfo, \"PRETTY_HOSTNAME\");\n      if (prettyHostname) {\n        return prettyHostname;\n      }\n    }\n\n    return yield* runFriendlyLabelCommand({\n      probe: \"linux-pretty-hostname\",\n      command: \"hostnamectl\",\n      args: [\"--pretty\"],\n    });\n  }\n\n  return null;\n});\n\nexport const resolveServerEnvironmentLabel = Effect.fn(\"resolveServerEnvironmentLabel\")(function* (\n  input: ResolveServerEnvironmentLabelInput,\n) {\n  const friendlyHostLabel = yield* resolveFriendlyHostLabel();\n  if (friendlyHostLabel) {\n    return friendlyHostLabel;\n  }\n\n  const hostname = normalizeLabel(yield* HostProcessHostname);\n  if (hostname) {\n    return hostname;\n  }\n\n  return normalizeLabel(input.cwdBaseName) ?? \"Synaptic Code environment\";\n});\n","import { EnvironmentId, type ExecutionEnvironmentDescriptor } from \"@t3tools/contracts\";\nimport { HostProcessArchitecture, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport { resolveServerSelfUpdateCapability } from \"../cloud/selfUpdate.ts\";\nimport { resolveServiceLauncherMode } from \"../cloud/serviceLauncherClient.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport * as ProcessRunner from \"../processRunner.ts\";\nimport { resolveServerEnvironmentLabel } from \"./ServerEnvironmentLabel.ts\";\n\nexport class ServerEnvironmentIdPersistenceError extends Schema.TaggedErrorClass<ServerEnvironmentIdPersistenceError>()(\n  \"ServerEnvironmentIdPersistenceError\",\n  {\n    operation: Schema.Literals([\"check\", \"read\", \"write\"]),\n    environmentIdPath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Server environment ID ${this.operation} failed at '${this.environmentIdPath}'.`;\n  }\n}\n\nexport class ServerEnvironment extends Context.Service<\n  ServerEnvironment,\n  {\n    readonly getEnvironmentId: Effect.Effect<EnvironmentId>;\n    readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;\n  }\n>()(\"t3/environment/ServerEnvironment\") {}\n\nfunction platformOs(platform: NodeJS.Platform): ExecutionEnvironmentDescriptor[\"platform\"][\"os\"] {\n  switch (platform) {\n    case \"darwin\":\n      return \"darwin\";\n    case \"linux\":\n      return \"linux\";\n    case \"win32\":\n      return \"windows\";\n    default:\n      return \"unknown\";\n  }\n}\n\nfunction platformArch(\n  architecture: NodeJS.Architecture,\n): ExecutionEnvironmentDescriptor[\"platform\"][\"arch\"] {\n  switch (architecture) {\n    case \"arm64\":\n      return \"arm64\";\n    case \"x64\":\n      return \"x64\";\n    default:\n      return \"other\";\n  }\n}\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const crypto = yield* Crypto.Crypto;\n  const hostPlatform = yield* HostProcessPlatform;\n  const hostArchitecture = yield* HostProcessArchitecture;\n\n  const readPersistedEnvironmentId = Effect.gen(function* () {\n    const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerEnvironmentIdPersistenceError({\n            operation: \"check\",\n            environmentIdPath: serverConfig.environmentIdPath,\n            cause,\n          }),\n      ),\n    );\n    if (!exists) {\n      return null;\n    }\n\n    const raw = yield* fileSystem.readFileString(serverConfig.environmentIdPath).pipe(\n      Effect.map((value) => value.trim()),\n      Effect.mapError(\n        (cause) =>\n          new ServerEnvironmentIdPersistenceError({\n            operation: \"read\",\n            environmentIdPath: serverConfig.environmentIdPath,\n            cause,\n          }),\n      ),\n    );\n\n    return raw.length > 0 ? raw : null;\n  });\n\n  const persistEnvironmentId = (value: string) =>\n    fileSystem.writeFileString(serverConfig.environmentIdPath, `${value}\\n`).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ServerEnvironmentIdPersistenceError({\n            operation: \"write\",\n            environmentIdPath: serverConfig.environmentIdPath,\n            cause,\n          }),\n      ),\n    );\n\n  const environmentIdRaw = yield* Effect.gen(function* () {\n    const persisted = yield* readPersistedEnvironmentId;\n    if (persisted) {\n      return persisted;\n    }\n\n    const generated = yield* crypto.randomUUIDv4;\n    yield* persistEnvironmentId(generated);\n    return generated;\n  });\n\n  const environmentId = EnvironmentId.make(environmentIdRaw);\n  const cwdBaseName = path.basename(serverConfig.cwd).trim();\n  const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });\n  const launcher = yield* resolveServiceLauncherMode();\n  const serverSelfUpdate = resolveServerSelfUpdateCapability({\n    desktopManaged: serverConfig.mode === \"desktop\",\n    launcherManaged: launcher.managed,\n  });\n\n  const descriptor: ExecutionEnvironmentDescriptor = {\n    environmentId,\n    label,\n    platform: {\n      os: platformOs(hostPlatform),\n      arch: platformArch(hostArchitecture),\n    },\n    serverVersion: packageJson.version,\n    capabilities: {\n      repositoryIdentity: true,\n      connectionProbe: true,\n      threadSettlement: true,\n      threadSnooze: true,\n      threadPinning: true,\n      threadPinReorder: true,\n      threadTitleRegeneration: true,\n      ...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),\n      ...(serverSelfUpdate === \"boot-service\" ? { serverSelfUpdateProgress: true } : {}),\n    },\n  };\n\n  return ServerEnvironment.of({\n    getEnvironmentId: Effect.succeed(environmentId),\n    getDescriptor: Effect.succeed(descriptor),\n  });\n});\n\n/**\n * ServerEnvironment is acquired from persisted filesystem and host-process\n * state. It intentionally has no fallback Layer.succeed value: callers must\n * provide the external platform services and a ServerConfig.\n */\nexport const layer = Layer.effect(ServerEnvironment, make).pipe(Layer.provide(ProcessRunner.layer));\n","import * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\nexport interface ProviderSessionReaperShape {\n  /**\n   * Start the background provider session reaper within the provided scope.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n}\n\nexport class ProviderSessionReaper extends Context.Service<\n  ProviderSessionReaper,\n  ProviderSessionReaperShape\n>()(\"t3/provider/Services/ProviderSessionReaper\") {}\n","import * as Context from \"effect/Context\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\nexport class ServerActivation extends Context.Reference<Effect.Effect<void> | undefined>(\n  \"t3/serverActivation\",\n  { defaultValue: () => undefined },\n) {}\n\n/** Forks a long-running root before commit and proves it is parked at the activation boundary. */\nexport const forkParked = <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n): Effect.Effect<void, never, Scope.Scope | R> =>\n  Effect.gen(function* () {\n    const activation = yield* ServerActivation;\n    if (activation === undefined) {\n      yield* Effect.forkScoped(effect);\n      return;\n    }\n    const parked = yield* Deferred.make<void>();\n    yield* Effect.forkScoped(\n      Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),\n    );\n    yield* Deferred.await(parked);\n  });\n","import {\n  CommandId,\n  DEFAULT_MODEL,\n  DEFAULT_PROVIDER_INTERACTION_MODE,\n  type ModelSelection,\n  ProjectId,\n  ProviderInstanceId,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Console from \"effect/Console\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\n\nimport * as ServerConfig from \"./config.ts\";\nimport * as Keybindings from \"./keybindings.ts\";\nimport * as ExternalLauncher from \"./process/externalLauncher.ts\";\nimport * as OrchestrationEngine from \"./orchestration/Services/OrchestrationEngine.ts\";\nimport * as ProjectionSnapshotQuery from \"./orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport * as OrchestrationReactor from \"./orchestration/Services/OrchestrationReactor.ts\";\nimport * as ServerLifecycleEvents from \"./serverLifecycleEvents.ts\";\nimport * as ServerSettings from \"./serverSettings.ts\";\nimport * as AnalyticsService from \"./telemetry/AnalyticsService.ts\";\nimport * as ServerEnvironment from \"./environment/ServerEnvironment.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\nimport * as ProviderSessionReaper from \"./provider/Services/ProviderSessionReaper.ts\";\nimport { forkParked } from \"./serverActivation.ts\";\nimport * as ServiceLauncherClient from \"./cloud/serviceLauncherClient.ts\";\nimport {\n  formatHeadlessServeOutput,\n  formatHostForUrl,\n  isWildcardHost,\n  issueHeadlessServeAccessInfo,\n} from \"./startupAccess.ts\";\n\nexport class ServerRuntimeStartupError extends Schema.TaggedErrorClass<ServerRuntimeStartupError>()(\n  \"ServerRuntimeStartupError\",\n  {\n    mode: ServerConfig.RuntimeMode,\n    host: Schema.NullOr(Schema.String),\n    port: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Server runtime startup failed before command readiness.\";\n  }\n}\n\nexport class ServerRuntimeStartup extends Context.Service<\n  ServerRuntimeStartup,\n  {\n    readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;\n    readonly markHttpListening: Effect.Effect<void>;\n    readonly enqueueCommand: <A, E>(\n      effect: Effect.Effect<A, E>,\n    ) => Effect.Effect<A, E | ServerRuntimeStartupError>;\n  }\n>()(\"t3/serverRuntimeStartup\") {}\n\ninterface QueuedCommand {\n  readonly run: Effect.Effect<void, never>;\n}\n\ntype CommandReadinessState = \"pending\" | \"ready\" | ServerRuntimeStartupError;\n\ninterface CommandGate {\n  readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;\n  readonly signalCommandReady: Effect.Effect<void>;\n  readonly failCommandReady: (error: ServerRuntimeStartupError) => Effect.Effect<void>;\n  readonly enqueueCommand: <A, E>(\n    effect: Effect.Effect<A, E>,\n  ) => Effect.Effect<A, E | ServerRuntimeStartupError>;\n}\n\nconst settleQueuedCommand = <A, E>(deferred: Deferred.Deferred<A, E>, exit: Exit.Exit<A, E>) =>\n  Exit.isSuccess(exit)\n    ? Deferred.succeed(deferred, exit.value)\n    : Deferred.failCause(deferred, exit.cause);\n\nexport const makeCommandGate = Effect.gen(function* () {\n  const commandReady = yield* Deferred.make<void, ServerRuntimeStartupError>();\n  const commandQueue = yield* Queue.unbounded<QueuedCommand>();\n  const commandReadinessState = yield* Ref.make<CommandReadinessState>(\"pending\");\n\n  const commandWorker = Effect.forever(\n    Queue.take(commandQueue).pipe(Effect.flatMap((command) => command.run)),\n  );\n  yield* Effect.forkScoped(commandWorker);\n\n  return {\n    awaitCommandReady: Deferred.await(commandReady),\n    signalCommandReady: Effect.gen(function* () {\n      yield* Ref.set(commandReadinessState, \"ready\");\n      yield* Deferred.succeed(commandReady, undefined).pipe(Effect.orDie);\n    }),\n    failCommandReady: (error) =>\n      Effect.gen(function* () {\n        yield* Ref.set(commandReadinessState, error);\n        yield* Deferred.fail(commandReady, error).pipe(Effect.orDie);\n      }),\n    enqueueCommand: <A, E>(effect: Effect.Effect<A, E>) =>\n      Effect.gen(function* () {\n        const readinessState = yield* Ref.get(commandReadinessState);\n        if (readinessState === \"ready\") {\n          return yield* effect;\n        }\n        if (readinessState !== \"pending\") {\n          return yield* readinessState;\n        }\n\n        const result = yield* Deferred.make<A, E | ServerRuntimeStartupError>();\n        yield* Queue.offer(commandQueue, {\n          run: Deferred.await(commandReady).pipe(\n            Effect.flatMap(() => effect),\n            Effect.exit,\n            Effect.flatMap((exit) => settleQueuedCommand(result, exit)),\n          ),\n        });\n        return yield* Deferred.await(result);\n      }),\n  } satisfies CommandGate;\n});\n\nexport const recordStartupHeartbeat = Effect.gen(function* () {\n  const analytics = yield* AnalyticsService.AnalyticsService;\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n\n  const { threadCount, projectCount } = yield* projectionSnapshotQuery.getCounts().pipe(\n    Effect.catch((cause) =>\n      Effect.logWarning(\"failed to gather startup projection counts for telemetry\", {\n        cause,\n      }).pipe(\n        Effect.as({\n          threadCount: 0,\n          projectCount: 0,\n        }),\n      ),\n    ),\n  );\n\n  yield* analytics.record(\"server.boot.heartbeat\", {\n    threadCount,\n    projectCount,\n  });\n});\n\nexport const launchStartupHeartbeat = recordStartupHeartbeat.pipe(\n  Effect.annotateSpans({ \"startup.phase\": \"heartbeat.record\" }),\n  Effect.withSpan(\"server.startup.heartbeat.record\"),\n  Effect.ignoreCause({ log: true }),\n  Effect.forkScoped,\n  Effect.asVoid,\n);\n\nexport const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({\n  instanceId: ProviderInstanceId.make(\"codex\"),\n  model: DEFAULT_MODEL,\n});\n\nexport const resolveWelcomeBase = Effect.gen(function* () {\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const segments = serverConfig.cwd.split(/[/\\\\]/).filter(Boolean);\n  const projectName = segments[segments.length - 1] ?? \"project\";\n\n  return {\n    cwd: serverConfig.cwd,\n    projectName,\n  } as const;\n});\n\nexport const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const randomUUID = crypto.randomUUIDv4;\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const projectionReadModelQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n  const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;\n  const path = yield* Path.Path;\n\n  let bootstrapProjectId: ProjectId | undefined;\n  let bootstrapThreadId: ThreadId | undefined;\n\n  if (serverConfig.autoBootstrapProjectFromCwd) {\n    yield* Effect.gen(function* () {\n      const existingProject = yield* projectionReadModelQuery.getActiveProjectByWorkspaceRoot(\n        serverConfig.cwd,\n      );\n      let nextProjectId: ProjectId;\n      let nextProjectDefaultModelSelection: ModelSelection;\n\n      if (Option.isNone(existingProject)) {\n        const createdAt = DateTime.formatIso(yield* DateTime.now);\n        nextProjectId = ProjectId.make(yield* randomUUID);\n        const bootstrapProjectTitle = path.basename(serverConfig.cwd) || \"project\";\n        nextProjectDefaultModelSelection = getAutoBootstrapDefaultModelSelection();\n        yield* orchestrationEngine.dispatch({\n          type: \"project.create\",\n          commandId: CommandId.make(yield* randomUUID),\n          projectId: nextProjectId,\n          title: bootstrapProjectTitle,\n          workspaceRoot: serverConfig.cwd,\n          defaultModelSelection: nextProjectDefaultModelSelection,\n          createdAt,\n        });\n      } else {\n        nextProjectId = existingProject.value.id;\n        nextProjectDefaultModelSelection =\n          existingProject.value.defaultModelSelection ?? getAutoBootstrapDefaultModelSelection();\n      }\n\n      const existingThreadId =\n        yield* projectionReadModelQuery.getFirstActiveThreadIdByProjectId(nextProjectId);\n      if (Option.isNone(existingThreadId)) {\n        const createdAt = DateTime.formatIso(yield* DateTime.now);\n        const createdThreadId = ThreadId.make(yield* randomUUID);\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.create\",\n          commandId: CommandId.make(yield* randomUUID),\n          threadId: createdThreadId,\n          projectId: nextProjectId,\n          title: \"New thread\",\n          modelSelection: nextProjectDefaultModelSelection,\n          interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,\n          runtimeMode: \"full-access\",\n          branch: null,\n          worktreePath: null,\n          createdAt,\n        });\n        bootstrapProjectId = nextProjectId;\n        bootstrapThreadId = createdThreadId;\n      } else {\n        bootstrapProjectId = nextProjectId;\n        bootstrapThreadId = existingThreadId.value;\n      }\n    });\n  }\n\n  return {\n    ...(bootstrapProjectId ? { bootstrapProjectId } : {}),\n    ...(bootstrapThreadId ? { bootstrapThreadId } : {}),\n  } as const;\n});\n\nconst resolveStartupBrowserTarget = Effect.gen(function* () {\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n  const localUrl = `http://localhost:${serverConfig.port}`;\n  const bindUrl =\n    serverConfig.host && !isWildcardHost(serverConfig.host)\n      ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}`\n      : localUrl;\n  const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl;\n  return yield* Effect.succeed(serverConfig.mode === \"desktop\" ? baseTarget : undefined).pipe(\n    Effect.flatMap((target) =>\n      target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget),\n    ),\n  );\n});\n\nconst maybeOpenBrowser = (target: string) =>\n  Effect.gen(function* () {\n    const serverConfig = yield* ServerConfig.ServerConfig;\n    if (serverConfig.noBrowser) {\n      return;\n    }\n    const externalLauncher = yield* ExternalLauncher.ExternalLauncher;\n\n    yield* externalLauncher.launchBrowser(target).pipe(\n      Effect.catch(() =>\n        Effect.logInfo(\"browser auto-open unavailable\", {\n          hint: `Open ${target} in your browser.`,\n        }),\n      ),\n    );\n  });\n\nconst runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>) =>\n  effect.pipe(\n    Effect.annotateSpans({ \"startup.phase\": phase }),\n    Effect.withSpan(`server.startup.${phase}`),\n  );\n\ninterface StartupOptions {\n  readonly activate?: Effect.Effect<void>;\n  readonly awaitAuxiliaryParked?: Effect.Effect<void>;\n  readonly abort?: (error: ServerRuntimeStartupError) => Effect.Effect<void>;\n}\n\nexport const make = (options?: StartupOptions) =>\n  Effect.gen(function* () {\n    const serverConfig = yield* ServerConfig.ServerConfig;\n    const keybindings = yield* Keybindings.Keybindings;\n    const orchestrationReactor = yield* OrchestrationReactor.OrchestrationReactor;\n    const providerSessionReaper = yield* ProviderSessionReaper.ProviderSessionReaper;\n    const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;\n    const serverSettings = yield* ServerSettings.ServerSettingsService;\n    const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;\n    const crypto = yield* Crypto.Crypto;\n    const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;\n\n    const commandGate = yield* makeCommandGate;\n    const httpListening = yield* Deferred.make<void>();\n    const reactorScope = yield* Scope.make(\"sequential\");\n\n    yield* Effect.addFinalizer(() => Scope.close(reactorScope, Exit.void));\n\n    const startup = Effect.gen(function* () {\n      yield* Effect.logDebug(\"startup phase: starting keybindings runtime\");\n      yield* runStartupPhase(\n        \"keybindings.start\",\n        keybindings.start.pipe(\n          Effect.catch((error) =>\n            Effect.logWarning(\"failed to start keybindings runtime\", {\n              path: error.configPath,\n              detail: error.detail,\n              cause: error.cause,\n            }),\n          ),\n        ),\n      );\n\n      yield* Effect.logDebug(\"startup phase: starting server settings runtime\");\n      yield* runStartupPhase(\n        \"settings.start\",\n        serverSettings.start.pipe(\n          Effect.catch((error) =>\n            Effect.logWarning(\"failed to start server settings runtime\", {\n              path: error.settingsPath,\n              operation: error.operation,\n              providerInstanceId: error.providerInstanceId,\n              environmentVariable: error.environmentVariable,\n              cause: error.cause,\n            }),\n          ),\n        ),\n      );\n\n      yield* Effect.logDebug(\"startup phase: parking orchestration roots at activation\");\n      yield* runStartupPhase(\n        \"reactors.start\",\n        Effect.gen(function* () {\n          yield* orchestrationReactor.start().pipe(Scope.provide(reactorScope));\n          yield* providerSessionReaper.start().pipe(Scope.provide(reactorScope));\n        }),\n      );\n\n      const welcomeBase = yield* resolveWelcomeBase;\n      const environment = yield* serverEnvironment.getDescriptor;\n      yield* Effect.logDebug(\"startup phase: preparing welcome payload\");\n\n      if (serverConfig.autoBootstrapProjectFromCwd) {\n        yield* forkParked(\n          runStartupPhase(\n            \"welcome.autobootstrap\",\n            Effect.gen(function* () {\n              const bootstrapTargets = yield* resolveAutoBootstrapWelcomeTargets.pipe(\n                Effect.provideService(Crypto.Crypto, crypto),\n              );\n              if (!bootstrapTargets.bootstrapProjectId && !bootstrapTargets.bootstrapThreadId) {\n                return;\n              }\n\n              yield* Effect.logDebug(\"startup phase: publishing bootstrapped welcome event\", {\n                environmentId: environment.environmentId,\n                cwd: welcomeBase.cwd,\n                projectName: welcomeBase.projectName,\n                bootstrapProjectId: bootstrapTargets.bootstrapProjectId,\n                bootstrapThreadId: bootstrapTargets.bootstrapThreadId,\n              });\n              yield* lifecycleEvents.publish({\n                version: 1,\n                type: \"welcome\",\n                payload: {\n                  environment,\n                  ...welcomeBase,\n                  ...bootstrapTargets,\n                },\n              });\n            }).pipe(\n              Effect.catch((cause) =>\n                Effect.logWarning(\"startup auto-bootstrap welcome failed\", {\n                  cause,\n                }),\n              ),\n            ),\n          ),\n        );\n      }\n\n      yield* forkParked(\n        Effect.gen(function* () {\n          yield* Effect.logDebug(\"startup phase: recording startup heartbeat\");\n          yield* recordStartupHeartbeat.pipe(\n            Effect.annotateSpans({ \"startup.phase\": \"heartbeat.record\" }),\n            Effect.withSpan(\"server.startup.heartbeat.record\"),\n            Effect.ignoreCause({ log: true }),\n          );\n          if (serverConfig.startupPresentation === \"headless\") {\n            const accessInfo = yield* issueHeadlessServeAccessInfo();\n            yield* runStartupPhase(\n              \"headless.output\",\n              Console.log(formatHeadlessServeOutput(accessInfo)),\n            );\n          } else {\n            const startupBrowserTarget = yield* resolveStartupBrowserTarget;\n            if (serverConfig.mode !== \"desktop\") {\n              yield* Effect.logInfo(\n                \"Authentication required. Open Synaptic Code using the pairing URL.\",\n              ).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));\n            }\n            yield* runStartupPhase(\"browser.open\", maybeOpenBrowser(startupBrowserTarget));\n          }\n        }),\n      );\n\n      yield* Effect.logDebug(\"startup phase: waiting for http listener\");\n      yield* runStartupPhase(\"http.wait\", Deferred.await(httpListening));\n      yield* runStartupPhase(\n        \"auxiliary-roots.parked\",\n        options?.awaitAuxiliaryParked ?? Effect.void,\n      );\n\n      // This is the prepared boundary. Every dependency has been acquired and\n      // every runtime root has confirmed that it is parked before this request.\n      const updateOutcome = yield* launcher.prepareTrial;\n      yield* runStartupPhase(\n        \"welcome.publish\",\n        lifecycleEvents.publish({\n          version: 1,\n          type: \"welcome\",\n          payload: { environment, ...welcomeBase },\n        }),\n      );\n      yield* options?.activate ?? Effect.void;\n\n      yield* Effect.logDebug(\"Accepting commands\");\n      yield* commandGate.signalCommandReady;\n      yield* runStartupPhase(\n        \"ready.publish\",\n        lifecycleEvents.publish({\n          version: 1,\n          type: \"ready\",\n          payload: {\n            at: DateTime.formatIso(yield* DateTime.now),\n            environment,\n            ...(updateOutcome === undefined ? {} : { updateOutcome }),\n          },\n        }),\n      );\n      yield* Effect.logDebug(\"startup phase: complete\");\n    }).pipe(\n      Effect.annotateSpans({\n        \"server.mode\": serverConfig.mode,\n        \"server.port\": serverConfig.port,\n        \"server.host\": serverConfig.host ?? \"default\",\n      }),\n      Effect.withSpan(\"server.startup\", { kind: \"server\", root: true }),\n    );\n\n    yield* Effect.forkScoped(\n      Effect.exit(startup).pipe(\n        Effect.flatMap((startupExit) => {\n          if (Exit.isSuccess(startupExit)) return Effect.void;\n          const error = new ServerRuntimeStartupError({\n            mode: serverConfig.mode,\n            host: serverConfig.host ?? null,\n            port: serverConfig.port,\n            cause: startupExit.cause,\n          });\n          return Effect.logError(\"server runtime startup failed\", {\n            cause: startupExit.cause,\n          }).pipe(\n            Effect.andThen(commandGate.failCommandReady(error)),\n            Effect.andThen(options?.abort?.(error) ?? Effect.void),\n          );\n        }),\n      ),\n    );\n\n    return {\n      awaitCommandReady: commandGate.awaitCommandReady,\n      markHttpListening: Deferred.succeed(httpListening, undefined),\n      enqueueCommand: commandGate.enqueueCommand,\n    } satisfies ServerRuntimeStartup[\"Service\"];\n  });\n\nexport const layerWithOptions = (options?: StartupOptions) =>\n  Layer.effect(ServerRuntimeStartup, make(options));\n\nexport const layer = layerWithOptions();\n","/**\n * WorkspacePaths - Effect service contract for workspace path handling.\n *\n * Owns normalization and validation of workspace roots plus safe resolution of\n * workspace-root-relative paths.\n *\n * @module WorkspacePaths\n */\nimport * as NodeOS from \"node:os\";\n\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nexport class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass<WorkspaceRootNotExistsError>()(\n  \"WorkspaceRootNotExistsError\",\n  {\n    workspaceRoot: Schema.String,\n    normalizedWorkspaceRoot: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace root does not exist: ${this.normalizedWorkspaceRoot}`;\n  }\n}\n\nexport class WorkspaceRootCreateFailedError extends Schema.TaggedErrorClass<WorkspaceRootCreateFailedError>()(\n  \"WorkspaceRootCreateFailedError\",\n  {\n    workspaceRoot: Schema.String,\n    normalizedWorkspaceRoot: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to create workspace root: ${this.normalizedWorkspaceRoot}`;\n  }\n}\n\nexport class WorkspaceRootStatFailedError extends Schema.TaggedErrorClass<WorkspaceRootStatFailedError>()(\n  \"WorkspaceRootStatFailedError\",\n  {\n    workspaceRoot: Schema.String,\n    normalizedWorkspaceRoot: Schema.String,\n    phase: Schema.Literals([\"validate-existing\", \"verify-created\"]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to stat workspace root '${this.normalizedWorkspaceRoot}' during '${this.phase}'.`;\n  }\n}\n\nexport class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass<WorkspaceRootNotDirectoryError>()(\n  \"WorkspaceRootNotDirectoryError\",\n  {\n    workspaceRoot: Schema.String,\n    normalizedWorkspaceRoot: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace root is not a directory: ${this.normalizedWorkspaceRoot}`;\n  }\n}\n\nexport class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass<WorkspacePathOutsideRootError>()(\n  \"WorkspacePathOutsideRootError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace file path must be relative to the project root: ${this.relativePath}`;\n  }\n}\n\nexport const WorkspacePathsError = Schema.Union([\n  WorkspaceRootNotExistsError,\n  WorkspaceRootCreateFailedError,\n  WorkspaceRootStatFailedError,\n  WorkspaceRootNotDirectoryError,\n  WorkspacePathOutsideRootError,\n]);\nexport type WorkspacePathsError = typeof WorkspacePathsError.Type;\n\n/** Service tag for workspace path normalization and resolution. */\nexport class WorkspacePaths extends Context.Service<\n  WorkspacePaths,\n  {\n    /** Normalize a user-provided workspace root and verify it exists as a directory. */\n    readonly normalizeWorkspaceRoot: (\n      workspaceRoot: string,\n      options?: { readonly createIfMissing?: boolean },\n    ) => Effect.Effect<\n      string,\n      | WorkspaceRootNotExistsError\n      | WorkspaceRootCreateFailedError\n      | WorkspaceRootStatFailedError\n      | WorkspaceRootNotDirectoryError\n    >;\n    /**\n     * Resolve a relative path within a validated workspace root.\n     *\n     * Rejects absolute paths and traversal attempts outside the workspace root.\n     */\n    readonly resolveRelativePathWithinRoot: (input: {\n      workspaceRoot: string;\n      relativePath: string;\n    }) => Effect.Effect<\n      { absolutePath: string; relativePath: string },\n      WorkspacePathOutsideRootError\n    >;\n  }\n>()(\"t3/workspace/WorkspacePaths\") {}\n\nfunction toPosixRelativePath(input: string): string {\n  return input.replaceAll(\"\\\\\", \"/\");\n}\n\nfunction expandHomePath(input: string, path: Path.Path): string {\n  if (input === \"~\") {\n    return NodeOS.homedir();\n  }\n  if (input.startsWith(\"~/\") || input.startsWith(\"~\\\\\")) {\n    return path.join(NodeOS.homedir(), input.slice(2));\n  }\n  return input;\n}\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const statWorkspaceRoot = Effect.fn(\"WorkspacePaths.statWorkspaceRoot\")(function* (\n    workspaceRoot: string,\n    normalizedWorkspaceRoot: string,\n    phase: WorkspaceRootStatFailedError[\"phase\"],\n  ) {\n    return yield* fileSystem.stat(normalizedWorkspaceRoot).pipe(\n      Effect.matchEffect({\n        onFailure: (cause) =>\n          cause.reason._tag === \"NotFound\"\n            ? Effect.succeed(null)\n            : Effect.fail(\n                new WorkspaceRootStatFailedError({\n                  workspaceRoot,\n                  normalizedWorkspaceRoot,\n                  phase,\n                  cause,\n                }),\n              ),\n        onSuccess: Effect.succeed,\n      }),\n    );\n  });\n\n  const normalizeWorkspaceRoot: WorkspacePaths[\"Service\"][\"normalizeWorkspaceRoot\"] = Effect.fn(\n    \"WorkspacePaths.normalizeWorkspaceRoot\",\n  )(function* (workspaceRoot, options) {\n    const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));\n    let workspaceStat = yield* statWorkspaceRoot(\n      workspaceRoot,\n      normalizedWorkspaceRoot,\n      \"validate-existing\",\n    );\n    if (!workspaceStat && options?.createIfMissing) {\n      yield* fileSystem.makeDirectory(normalizedWorkspaceRoot, { recursive: true }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new WorkspaceRootCreateFailedError({\n              workspaceRoot,\n              normalizedWorkspaceRoot,\n              cause,\n            }),\n        ),\n      );\n      workspaceStat = yield* statWorkspaceRoot(\n        workspaceRoot,\n        normalizedWorkspaceRoot,\n        \"verify-created\",\n      );\n    }\n    if (!workspaceStat) {\n      return yield* new WorkspaceRootNotExistsError({\n        workspaceRoot,\n        normalizedWorkspaceRoot,\n      });\n    }\n    if (workspaceStat.type !== \"Directory\") {\n      return yield* new WorkspaceRootNotDirectoryError({\n        workspaceRoot,\n        normalizedWorkspaceRoot,\n      });\n    }\n    return normalizedWorkspaceRoot;\n  });\n\n  const resolveRelativePathWithinRoot: WorkspacePaths[\"Service\"][\"resolveRelativePathWithinRoot\"] =\n    Effect.fn(\"WorkspacePaths.resolveRelativePathWithinRoot\")(function* (input) {\n      const normalizedInputPath = input.relativePath.trim();\n      if (path.isAbsolute(normalizedInputPath)) {\n        return yield* new WorkspacePathOutsideRootError({\n          workspaceRoot: input.workspaceRoot,\n          relativePath: input.relativePath,\n        });\n      }\n\n      const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath);\n      const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath));\n      if (\n        relativeToRoot.length === 0 ||\n        relativeToRoot === \".\" ||\n        relativeToRoot.startsWith(\"../\") ||\n        relativeToRoot === \"..\" ||\n        path.isAbsolute(relativeToRoot)\n      ) {\n        return yield* new WorkspacePathOutsideRootError({\n          workspaceRoot: input.workspaceRoot,\n          relativePath: input.relativePath,\n        });\n      }\n\n      return {\n        absolutePath,\n        relativePath: relativeToRoot,\n      };\n    });\n\n  return WorkspacePaths.of({ normalizeWorkspaceRoot, resolveRelativePathWithinRoot });\n});\n\nexport const layer = Layer.effect(WorkspacePaths, make);\n","import {\n  CommandId,\n  AuthAdministrativeScopes,\n  EnvironmentHttpApi,\n  EnvironmentHttpCommonError,\n  type OrchestrationReadModel,\n  ProjectId,\n  type ClientOrchestrationCommand,\n} from \"@t3tools/contracts\";\nimport * as Console from \"effect/Console\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as References from \"effect/References\";\nimport * as Schema from \"effect/Schema\";\nimport { Argument, Command, Flag, GlobalFlag } from \"effect/unstable/cli\";\nimport { FetchHttpClient, HttpClient, HttpClientError } from \"effect/unstable/http\";\nimport * as HttpApiClient from \"effect/unstable/httpapi/HttpApiClient\";\n\nimport * as EnvironmentAuth from \"../auth/EnvironmentAuth.ts\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport * as OrchestrationEngine from \"../orchestration/Services/OrchestrationEngine.ts\";\nimport * as ProjectionSnapshotQuery from \"../orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport { OrchestrationLayerLive } from \"../orchestration/runtimeLayer.ts\";\nimport { layerConfig as SqlitePersistenceLayerLive } from \"../persistence/Layers/Sqlite.ts\";\nimport * as RepositoryIdentityResolver from \"../project/RepositoryIdentityResolver.ts\";\nimport * as ServerRuntimeStartup from \"../serverRuntimeStartup.ts\";\nimport {\n  clearPersistedServerRuntimeState,\n  readPersistedServerRuntimeState,\n} from \"../serverRuntimeState.ts\";\nimport * as WorkspacePaths from \"../workspace/WorkspacePaths.ts\";\nimport { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from \"./config.ts\";\n\ntype ProjectMutationTarget = {\n  readonly id: ProjectId;\n  readonly title: string;\n  readonly workspaceRoot: string;\n};\n\ntype ProjectCommandExecutionMode = \"live\" | \"offline\";\ntype ProjectCliDispatchCommand = Extract<\n  ClientOrchestrationCommand,\n  { type: \"project.create\" | \"project.meta.update\" | \"project.delete\" }\n>;\n\nconst isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);\n\nexport class ProjectCommandIdGenerationError extends Schema.TaggedErrorClass<ProjectCommandIdGenerationError>()(\n  \"ProjectCommandIdGenerationError\",\n  {\n    operation: Schema.Literal(\"generateProjectCommandId\"),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to generate a project command identifier.\";\n  }\n}\n\nexport class ProjectLiveServerDeclaredResponseError extends Schema.TaggedErrorClass<ProjectLiveServerDeclaredResponseError>()(\n  \"ProjectLiveServerDeclaredResponseError\",\n  {\n    operation: Schema.Literal(\"callLiveServer\"),\n    code: Schema.String,\n    traceId: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Server request failed (${this.code}, trace ${this.traceId}).`;\n  }\n}\n\nexport class ProjectLiveServerUndeclaredStatusError extends Schema.TaggedErrorClass<ProjectLiveServerUndeclaredStatusError>()(\n  \"ProjectLiveServerUndeclaredStatusError\",\n  {\n    operation: Schema.Literal(\"callLiveServer\"),\n    status: Schema.Int,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Server request failed with undeclared status ${this.status}.`;\n  }\n}\n\nexport class ProjectLiveServerRequestError extends Schema.TaggedErrorClass<ProjectLiveServerRequestError>()(\n  \"ProjectLiveServerRequestError\",\n  {\n    operation: Schema.Literal(\"callLiveServer\"),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to call the running server.\";\n  }\n}\n\nexport class ProjectTitleEmptyError extends Schema.TaggedErrorClass<ProjectTitleEmptyError>()(\n  \"ProjectTitleEmptyError\",\n  {\n    operation: Schema.Literal(\"validateProjectTitle\"),\n    title: Schema.String,\n  },\n) {\n  override get message(): string {\n    return \"Project title cannot be empty.\";\n  }\n}\n\nexport class ProjectIdentifierEmptyError extends Schema.TaggedErrorClass<ProjectIdentifierEmptyError>()(\n  \"ProjectIdentifierEmptyError\",\n  {\n    operation: Schema.Literal(\"resolveProjectTarget\"),\n    identifier: Schema.String,\n  },\n) {\n  override get message(): string {\n    return \"Project identifier cannot be empty.\";\n  }\n}\n\nexport class ProjectNotFoundError extends Schema.TaggedErrorClass<ProjectNotFoundError>()(\n  \"ProjectNotFoundError\",\n  {\n    operation: Schema.Literal(\"resolveProjectTarget\"),\n    identifier: Schema.String,\n    normalizedWorkspaceRoot: Schema.optional(Schema.String),\n    activeProjectCount: Schema.Number,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `No active project found for '${this.identifier}'.`;\n  }\n}\n\nexport class ProjectAlreadyExistsError extends Schema.TaggedErrorClass<ProjectAlreadyExistsError>()(\n  \"ProjectAlreadyExistsError\",\n  {\n    operation: Schema.Literal(\"addProject\"),\n    projectId: ProjectId,\n    workspaceRoot: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `An active project already exists for '${this.workspaceRoot}'.`;\n  }\n}\n\nexport const ProjectCommandError = Schema.Union([\n  ProjectCommandIdGenerationError,\n  ProjectLiveServerDeclaredResponseError,\n  ProjectLiveServerUndeclaredStatusError,\n  ProjectLiveServerRequestError,\n  ProjectTitleEmptyError,\n  ProjectIdentifierEmptyError,\n  ProjectNotFoundError,\n  ProjectAlreadyExistsError,\n]);\nexport type ProjectCommandError = typeof ProjectCommandError.Type;\n\nexport function projectCommandErrorFromLiveServerRequest(cause: unknown): ProjectCommandError {\n  if (isEnvironmentHttpCommonError(cause)) {\n    return new ProjectLiveServerDeclaredResponseError({\n      operation: \"callLiveServer\",\n      code: cause.code,\n      traceId: cause.traceId,\n      cause,\n    });\n  }\n  if (HttpClientError.isHttpClientError(cause) && cause.response !== undefined) {\n    return new ProjectLiveServerUndeclaredStatusError({\n      operation: \"callLiveServer\",\n      status: cause.response.status,\n      cause,\n    });\n  }\n\n  return new ProjectLiveServerRequestError({ operation: \"callLiveServer\", cause });\n}\n\nconst projectCommandUuid = Crypto.Crypto.pipe(\n  Effect.flatMap((crypto) => crypto.randomUUIDv4),\n  Effect.mapError(\n    (cause) =>\n      new ProjectCommandIdGenerationError({\n        operation: \"generateProjectCommandId\",\n        cause,\n      }),\n  ),\n);\n\nconst ProjectCliRuntimeLive = Layer.mergeAll(\n  WorkspacePaths.layer,\n  OrchestrationLayerLive.pipe(\n    Layer.provideMerge(RepositoryIdentityResolver.layer),\n    Layer.provideMerge(SqlitePersistenceLayerLive),\n  ),\n);\n\nconst PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);\nconst withProjectCliSessionToken = <A, E, R>(\n  environmentAuth: EnvironmentAuth.EnvironmentAuth[\"Service\"],\n  run: (token: string) => Effect.Effect<A, E, R>,\n) =>\n  Effect.acquireUseRelease(\n    environmentAuth.issueSession({\n      scopes: AuthAdministrativeScopes,\n      label: \"synaptic-code project cli\",\n    }),\n    (issued) => run(issued.token),\n    (issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),\n  );\n\nconst withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n  effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));\n\nconst makeLiveServerClient = (origin: string) =>\n  HttpApiClient.make(EnvironmentHttpApi, {\n    baseUrl: origin,\n  });\n\nconst normalizeWorkspaceRootForProjectCommand = Effect.fn(\n  \"normalizeWorkspaceRootForProjectCommand\",\n)(function* (workspaceRoot: string) {\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);\n});\n\nconst resolveProjectTitle = Effect.fn(\"resolveProjectTitle\")(function* (\n  workspaceRoot: string,\n  explicitTitle?: string,\n) {\n  if (explicitTitle !== undefined) {\n    const trimmed = explicitTitle.trim();\n    if (trimmed.length > 0) {\n      return trimmed;\n    }\n    return yield* new ProjectTitleEmptyError({\n      operation: \"validateProjectTitle\",\n      title: explicitTitle,\n    });\n  }\n\n  const path = yield* Path.Path;\n  const basename = path.basename(workspaceRoot).trim();\n  return basename.length > 0 ? basename : \"project\";\n});\n\nconst findActiveProjectTarget = Effect.fn(\"findActiveProjectTarget\")(function* (input: {\n  readonly snapshot: OrchestrationReadModel;\n  readonly identifier: string;\n}) {\n  const trimmedIdentifier = input.identifier.trim();\n  if (trimmedIdentifier.length === 0) {\n    return yield* new ProjectIdentifierEmptyError({\n      operation: \"resolveProjectTarget\",\n      identifier: input.identifier,\n    });\n  }\n\n  const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);\n  const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);\n  if (exactIdMatch) {\n    return {\n      id: exactIdMatch.id,\n      title: exactIdMatch.title,\n      workspaceRoot: exactIdMatch.workspaceRoot,\n    } satisfies ProjectMutationTarget;\n  }\n\n  const normalizedWorkspaceRootResult = yield* Effect.result(\n    normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),\n  );\n  const normalizedWorkspaceRoot =\n    normalizedWorkspaceRootResult._tag === \"Success\" ? normalizedWorkspaceRootResult.success : null;\n\n  const exactWorkspaceMatch =\n    normalizedWorkspaceRoot === null\n      ? undefined\n      : activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);\n\n  const resolved = exactWorkspaceMatch;\n  if (!resolved) {\n    return yield* new ProjectNotFoundError({\n      operation: \"resolveProjectTarget\",\n      identifier: trimmedIdentifier,\n      activeProjectCount: activeProjects.length,\n      ...(normalizedWorkspaceRoot === null ? {} : { normalizedWorkspaceRoot }),\n      ...(normalizedWorkspaceRootResult._tag === \"Failure\"\n        ? { cause: normalizedWorkspaceRootResult.failure }\n        : {}),\n    });\n  }\n\n  return {\n    id: resolved.id,\n    title: resolved.title,\n    workspaceRoot: resolved.workspaceRoot,\n  } satisfies ProjectMutationTarget;\n});\n\nconst fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>\n  Effect.gen(function* () {\n    const client = yield* makeLiveServerClient(origin);\n    return yield* client.orchestration.snapshot({\n      headers: { authorization: `Bearer ${bearerToken}` },\n    });\n  }).pipe(\n    withProjectCliLiveServerTimeout,\n    Effect.mapError(projectCommandErrorFromLiveServerRequest),\n  );\n\nconst dispatchLiveOrchestrationCommand = (\n  origin: string,\n  bearerToken: string,\n  command: ProjectCliDispatchCommand,\n) =>\n  Effect.gen(function* () {\n    const client = yield* makeLiveServerClient(origin);\n    yield* client.orchestration.dispatch({\n      headers: { authorization: `Bearer ${bearerToken}` },\n      payload: command,\n    } as Parameters<typeof client.orchestration.dispatch>[0]);\n  }).pipe(\n    withProjectCliLiveServerTimeout,\n    Effect.mapError(projectCommandErrorFromLiveServerRequest),\n  );\n\nconst getOfflineSnapshot = Effect.fn(\"getOfflineSnapshot\")(function* () {\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n  // Project commands only read the project list, so use the lightweight\n  // command read model instead of hydrating every thread body in the database.\n  return yield* projectionSnapshotQuery.getCommandReadModel();\n});\n\nconst tryResolveLiveProjectExecutionMode = Effect.fn(\"tryResolveLiveProjectExecutionMode\")(\n  function* (\n    environmentAuth: EnvironmentAuth.EnvironmentAuth[\"Service\"],\n    config: ServerConfig.ServerConfig[\"Service\"],\n  ) {\n    const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);\n    if (Option.isNone(runtimeState)) {\n      return Option.none<{ readonly origin: string }>();\n    }\n\n    const attempt = withProjectCliSessionToken(environmentAuth, (token) =>\n      fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(\n        Effect.as({\n          origin: runtimeState.value.origin,\n        }),\n      ),\n    );\n\n    const attempted = yield* Effect.result(attempt);\n    if (attempted._tag === \"Success\") {\n      return Option.some(attempted.success);\n    }\n\n    yield* Effect.logDebug(\"Failed to connect to the persisted project CLI server.\", {\n      origin: runtimeState.value.origin,\n      cause: attempted.failure,\n    });\n    yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);\n    return Option.none<{ readonly origin: string }>();\n  },\n);\n\nconst runProjectMutation = Effect.fn(\"runProjectMutation\")(function* (\n  flags: CliAuthLocationFlags,\n  run: (input: {\n    readonly snapshot: OrchestrationReadModel;\n    readonly dispatch: (\n      command: ProjectCliDispatchCommand,\n    ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;\n    readonly mode: ProjectCommandExecutionMode;\n  }) => Effect.Effect<\n    string,\n    Error,\n    | Crypto.Crypto\n    | FileSystem.FileSystem\n    | HttpClient.HttpClient\n    | Path.Path\n    | WorkspacePaths.WorkspacePaths\n  >,\n) {\n  const logLevel = yield* GlobalFlag.LogLevel;\n  const config = yield* resolveCliAuthConfig(flags, logLevel);\n  const minimumLogLevel = config.logLevel;\n\n  return yield* Effect.gen(function* () {\n    const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    const liveMode = yield* tryResolveLiveProjectExecutionMode(environmentAuth, config);\n\n    if (Option.isSome(liveMode)) {\n      return yield* withProjectCliSessionToken(environmentAuth, (token) =>\n        Effect.gen(function* () {\n          const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);\n          const output = yield* run({\n            snapshot,\n            dispatch: (command) =>\n              dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),\n            mode: \"live\",\n          });\n          yield* Console.log(output);\n        }),\n      );\n    }\n\n    const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(\n      Layer.provide(ServerConfig.layer(config)),\n      Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),\n    );\n\n    return yield* Effect.gen(function* () {\n      const snapshot = yield* getOfflineSnapshot();\n      const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;\n      const output = yield* run({\n        snapshot,\n        dispatch: (command) => orchestrationEngine.dispatch(command),\n        mode: \"offline\",\n      });\n      yield* Console.log(output);\n    }).pipe(Effect.provide(offlineRuntimeLayer));\n  }).pipe(\n    Effect.provide(\n      Layer.mergeAll(EnvironmentAuth.runtimeLayer, WorkspacePaths.layer).pipe(\n        Layer.provideMerge(FetchHttpClient.layer),\n        Layer.provide(ServerConfig.layer(config)),\n        Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),\n      ),\n    ),\n  );\n});\n\nconst projectAddCommand = Command.make(\"add\", {\n  ...projectLocationFlags,\n  workspaceRoot: Argument.string(\"path\").pipe(\n    Argument.withDescription(\"Workspace root to add as a project.\"),\n  ),\n  title: Flag.string(\"title\").pipe(Flag.withDescription(\"Optional project title.\"), Flag.optional),\n}).pipe(\n  Command.withDescription(\"Add a project.\"),\n  Command.withHandler((flags) =>\n    runProjectMutation(\n      flags,\n      Effect.fn(\"projectAddMutation\")(function* ({\n        snapshot,\n        dispatch,\n      }: {\n        readonly snapshot: OrchestrationReadModel;\n        readonly dispatch: (\n          command: ProjectCliDispatchCommand,\n        ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;\n      }) {\n        const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);\n        const existingProject = snapshot.projects.find(\n          (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,\n        );\n        if (existingProject) {\n          return yield* new ProjectAlreadyExistsError({\n            operation: \"addProject\",\n            projectId: existingProject.id,\n            workspaceRoot,\n          });\n        }\n\n        const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));\n        const projectId = ProjectId.make(yield* projectCommandUuid);\n        yield* dispatch({\n          type: \"project.create\",\n          commandId: CommandId.make(yield* projectCommandUuid),\n          projectId,\n          title,\n          workspaceRoot,\n          defaultModelSelection: ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(),\n          createdAt: DateTime.formatIso(yield* DateTime.now),\n        });\n        return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;\n      }),\n    ),\n  ),\n);\n\nconst projectRemoveCommand = Command.make(\"remove\", {\n  ...projectLocationFlags,\n  project: Argument.string(\"project\").pipe(\n    Argument.withDescription(\"Project id or workspace root to remove.\"),\n  ),\n  force: Flag.boolean(\"force\").pipe(\n    Flag.withDescription(\"Delete the project and all of its threads.\"),\n    Flag.withDefault(false),\n  ),\n}).pipe(\n  Command.withDescription(\"Remove a project.\"),\n  Command.withHandler((flags) =>\n    runProjectMutation(\n      flags,\n      Effect.fn(\"projectRemoveMutation\")(function* ({\n        snapshot,\n        dispatch,\n      }: {\n        readonly snapshot: OrchestrationReadModel;\n        readonly dispatch: (\n          command: ProjectCliDispatchCommand,\n        ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;\n      }) {\n        const project = yield* findActiveProjectTarget({\n          snapshot,\n          identifier: flags.project,\n        });\n        yield* dispatch({\n          type: \"project.delete\",\n          commandId: CommandId.make(yield* projectCommandUuid),\n          projectId: project.id,\n          force: flags.force,\n        });\n        return `Removed project ${project.id} (${project.title}).`;\n      }),\n    ),\n  ),\n);\n\nconst projectRenameCommand = Command.make(\"rename\", {\n  ...projectLocationFlags,\n  project: Argument.string(\"project\").pipe(\n    Argument.withDescription(\"Project id or workspace root to rename.\"),\n  ),\n  title: Argument.string(\"title\").pipe(Argument.withDescription(\"New project title.\")),\n}).pipe(\n  Command.withDescription(\"Rename a project.\"),\n  Command.withHandler((flags) =>\n    runProjectMutation(\n      flags,\n      Effect.fn(\"projectRenameMutation\")(function* ({\n        snapshot,\n        dispatch,\n      }: {\n        readonly snapshot: OrchestrationReadModel;\n        readonly dispatch: (\n          command: ProjectCliDispatchCommand,\n        ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;\n      }) {\n        const project = yield* findActiveProjectTarget({\n          snapshot,\n          identifier: flags.project,\n        });\n        const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);\n        if (nextTitle === project.title) {\n          return `Project ${project.id} is already named ${nextTitle}.`;\n        }\n\n        yield* dispatch({\n          type: \"project.meta.update\",\n          commandId: CommandId.make(yield* projectCommandUuid),\n          projectId: project.id,\n          title: nextTitle,\n        });\n        return `Renamed project ${project.id} to ${nextTitle}.`;\n      }),\n    ),\n  ),\n);\n\nexport const projectCommand = Command.make(\"project\").pipe(\n  Command.withDescription(\"Manage projects.\"),\n  Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),\n);\n","import * as Effect from \"effect/Effect\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\n\nexport interface SnapshotSubscription<A> {\n  readonly latest: A;\n  readonly changes: Stream.Stream<A>;\n}\n\nexport const subscribeBeforeSnapshot = Effect.fn(\"subscribeBeforeSnapshot\")(function* <A, E, R>(\n  changes: PubSub.PubSub<A>,\n  snapshot: Effect.Effect<A, E, R>,\n  mutex: Semaphore.Semaphore,\n) {\n  return yield* mutex.withPermits(1)(\n    Effect.gen(function* () {\n      const latest = yield* snapshot;\n      const subscription = yield* PubSub.subscribe(changes);\n      return {\n        latest,\n        changes: Stream.fromSubscription(subscription),\n      } satisfies SnapshotSubscription<A>;\n    }),\n  );\n});\n\nexport const subscribeBeforeSnapshotWithoutMutex = Effect.fn(\"subscribeBeforeSnapshotWithoutMutex\")(\n  function* <A, E, R>(changes: PubSub.PubSub<A>, snapshot: Effect.Effect<A, E, R>) {\n    const subscription = yield* PubSub.subscribe(changes);\n    const latest = yield* snapshot;\n    return {\n      latest,\n      changes: Stream.fromSubscription(subscription),\n    } satisfies SnapshotSubscription<A>;\n  },\n);\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFS from \"node:fs\";\n\nimport * as NodeStream from \"@effect/platform-node/NodeStream\";\nimport {\n  DesktopHostTelemetryMessage,\n  type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue,\n  type DesktopHostTelemetrySnapshot,\n  DesktopTelemetryControlMessage,\n  type ResourceTelemetrySourceStatus,\n} from \"@t3tools/contracts\";\nimport { resolveServerBackgroundActivitySettings } from \"@t3tools/shared/backgroundActivitySettings\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Ndjson from \"effect/unstable/encoding/Ndjson\";\n\nimport { ServerConfig } from \"../config.ts\";\nimport { ServerSettingsService } from \"../serverSettings.ts\";\nimport { subscribeBeforeSnapshotWithoutMutex } from \"../utils/subscribeBeforeSnapshot.ts\";\n\nconst INITIAL_SAMPLE_DEADLINE_MS = 90_000;\nconst MIN_SNAPSHOT_STALE_AFTER_MS = 90_000;\nconst STALE_GRACE_MS = 30_000;\nconst DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS = 30_000;\nconst DEFAULT_HOST_POWER_IDLE_INTERVAL_MS = 120_000;\nconst STALE_CHECK_INTERVAL = Duration.seconds(30);\n\nexport class DesktopTelemetryDescriptorUnavailable extends Schema.TaggedErrorClass<DesktopTelemetryDescriptorUnavailable>()(\n  \"DesktopTelemetryDescriptorUnavailable\",\n  {\n    mode: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry descriptor is unavailable in '${this.mode}' mode.`;\n  }\n}\n\nexport class DesktopTelemetryProtocolMismatch extends Schema.TaggedErrorClass<DesktopTelemetryProtocolMismatch>()(\n  \"DesktopTelemetryProtocolMismatch\",\n  {\n    expectedVersion: Schema.Number,\n    receivedVersion: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry protocol ${this.receivedVersion} is incompatible with expected protocol ${this.expectedVersion}.`;\n  }\n}\n\nexport class DesktopTelemetryDecodeFailed extends Schema.TaggedErrorClass<DesktopTelemetryDecodeFailed>()(\n  \"DesktopTelemetryDecodeFailed\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to decode desktop telemetry.\";\n  }\n}\n\nexport class DesktopTelemetryStreamFailed extends Schema.TaggedErrorClass<DesktopTelemetryStreamFailed>()(\n  \"DesktopTelemetryStreamFailed\",\n  {\n    fd: Schema.Number,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry stream on fd ${this.fd} failed.`;\n  }\n}\n\nexport class DesktopTelemetryStreamClosed extends Schema.TaggedErrorClass<DesktopTelemetryStreamClosed>()(\n  \"DesktopTelemetryStreamClosed\",\n  {\n    fd: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry stream on fd ${this.fd} closed.`;\n  }\n}\n\nexport class DesktopTelemetryStale extends Schema.TaggedErrorClass<DesktopTelemetryStale>()(\n  \"DesktopTelemetryStale\",\n  {\n    fd: Schema.Number,\n    staleAfterMs: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry on fd ${this.fd} has not updated for ${this.staleAfterMs}ms.`;\n  }\n}\n\nexport type DesktopTelemetryReceiverError =\n  | DesktopTelemetryDescriptorUnavailable\n  | DesktopTelemetryProtocolMismatch\n  | DesktopTelemetryDecodeFailed\n  | DesktopTelemetryStreamFailed\n  | DesktopTelemetryStreamClosed;\n\nexport class DesktopTelemetryControlFailed extends Schema.TaggedErrorClass<DesktopTelemetryControlFailed>()(\n  \"DesktopTelemetryControlFailed\",\n  {\n    fd: Schema.Number,\n    operation: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry control '${this.operation}' failed on fd ${this.fd}.`;\n  }\n}\n\nexport class DesktopTelemetryControlStalled extends Schema.TaggedErrorClass<DesktopTelemetryControlStalled>()(\n  \"DesktopTelemetryControlStalled\",\n  {\n    fd: Schema.Number,\n    remainingBytes: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Desktop telemetry control stalled on fd ${this.fd} with ${this.remainingBytes} bytes remaining.`;\n  }\n}\n\nexport type DesktopTelemetryControlError =\n  | DesktopTelemetryControlFailed\n  | DesktopTelemetryControlStalled;\n\nexport interface DesktopTelemetryReceiverHealth {\n  readonly status: ResourceTelemetrySourceStatus;\n  readonly lastSampleAt: Option.Option<DateTime.Utc>;\n  readonly lastError: Option.Option<string>;\n}\n\nexport class DesktopTelemetryReceiver extends Context.Service<\n  DesktopTelemetryReceiver,\n  {\n    readonly latest: Effect.Effect<Option.Option<DesktopHostTelemetrySnapshot>>;\n    readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;\n    readonly subscribe: Effect.Effect<\n      {\n        readonly latest: Option.Option<DesktopHostTelemetrySnapshot>;\n        readonly changes: Stream.Stream<DesktopHostTelemetrySnapshot>;\n      },\n      never,\n      Scope.Scope\n    >;\n    readonly health: Effect.Effect<DesktopTelemetryReceiverHealth>;\n    readonly subscribeHealth: Effect.Effect<\n      {\n        readonly latest: DesktopTelemetryReceiverHealth;\n        readonly changes: Stream.Stream<DesktopTelemetryReceiverHealth>;\n      },\n      never,\n      Scope.Scope\n    >;\n    readonly setDiagnosticsDemand: (\n      enabled: boolean,\n    ) => Effect.Effect<void, DesktopTelemetryControlError>;\n  }\n>()(\"t3/resourceTelemetry/DesktopTelemetryReceiver\") {}\n\nconst decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage);\nconst encodeControlMessage = Schema.encodeEffect(\n  Schema.fromJsonString(DesktopTelemetryControlMessage),\n);\nconst isDescriptorUnavailable = Schema.is(DesktopTelemetryDescriptorUnavailable);\nconst isProtocolMismatch = Schema.is(DesktopTelemetryProtocolMismatch);\nconst isDecodeFailed = Schema.is(DesktopTelemetryDecodeFailed);\nconst isStreamFailed = Schema.is(DesktopTelemetryStreamFailed);\n\nexport function isDesktopTelemetryContactStale(\n  lastContactAtMs: Option.Option<number>,\n  nowMs: number,\n): boolean {\n  return Option.exists(\n    lastContactAtMs,\n    (lastContact) => nowMs - lastContact >= INITIAL_SAMPLE_DEADLINE_MS,\n  );\n}\n\nexport function resolveDesktopTelemetrySnapshotStaleAfterMs(\n  activeIntervalMs: number,\n  idleIntervalMs: number,\n): number {\n  return Math.max(\n    MIN_SNAPSHOT_STALE_AFTER_MS,\n    Math.max(activeIntervalMs, idleIntervalMs) + STALE_GRACE_MS,\n  );\n}\n\nexport function initialDesktopTelemetryContactAt(\n  desktopTelemetryFd: number | undefined,\n  nowMs: number,\n): Option.Option<number> {\n  return desktopTelemetryFd === undefined ? Option.none() : Option.some(nowMs);\n}\n\nexport const recordDesktopTelemetrySampleHealth = Effect.fn(\n  \"resourceTelemetry.desktopTelemetryReceiver.recordSampleHealth\",\n)(function* (\n  health: Ref.Ref<DesktopTelemetryReceiverHealth>,\n  healthChanges: PubSub.PubSub<DesktopTelemetryReceiverHealth>,\n  sampledAt: DateTime.Utc,\n) {\n  const next: DesktopTelemetryReceiverHealth = {\n    status: \"healthy\",\n    lastSampleAt: Option.some(sampledAt),\n    lastError: Option.none(),\n  };\n  yield* Ref.set(health, next);\n  yield* PubSub.publish(healthChanges, next);\n});\n\nfunction normalizeReceiverError(error: unknown): DesktopTelemetryReceiverError {\n  if (\n    isDescriptorUnavailable(error) ||\n    isProtocolMismatch(error) ||\n    isDecodeFailed(error) ||\n    isStreamFailed(error)\n  ) {\n    return error;\n  }\n  return new DesktopTelemetryDecodeFailed({ cause: error });\n}\n\nfunction messageVersion(value: unknown): number | undefined {\n  if (typeof value !== \"object\" || value === null) return undefined;\n  const version = Reflect.get(value, \"version\");\n  return typeof version === \"number\" ? version : undefined;\n}\n\nexport const writeAllToFileDescriptor = Effect.fn(\n  \"resourceTelemetry.desktopTelemetryReceiver.writeAllToFileDescriptor\",\n)(function* (fd: number, payload: Buffer) {\n  let offset = 0;\n  while (offset < payload.byteLength) {\n    const written = yield* Effect.callback<number, DesktopTelemetryControlFailed>(\n      (resume, signal) => {\n        if (signal.aborted) return;\n        try {\n          NodeFS.write(\n            fd,\n            payload,\n            offset,\n            payload.byteLength - offset,\n            null,\n            (error, bytesWritten) => {\n              if (error) {\n                resume(\n                  Effect.fail(\n                    new DesktopTelemetryControlFailed({\n                      fd,\n                      operation: \"write\",\n                      cause: error,\n                    }),\n                  ),\n                );\n                return;\n              }\n              resume(Effect.succeed(bytesWritten));\n            },\n          );\n        } catch (cause) {\n          resume(\n            Effect.fail(\n              new DesktopTelemetryControlFailed({\n                fd,\n                operation: \"write\",\n                cause,\n              }),\n            ),\n          );\n        }\n      },\n    );\n    yield* requireDesktopTelemetryWriteProgress(fd, payload.byteLength - offset, written);\n    offset += written;\n  }\n});\n\nexport function requireDesktopTelemetryWriteProgress(\n  fd: number,\n  remainingBytes: number,\n  written: number,\n): Effect.Effect<void, DesktopTelemetryControlStalled> {\n  return written > 0\n    ? Effect.void\n    : Effect.fail(new DesktopTelemetryControlStalled({ fd, remainingBytes }));\n}\n\nexport const make = Effect.fn(\"resourceTelemetry.desktopTelemetryReceiver.make\")(function* () {\n  const config = yield* ServerConfig;\n  const serverSettings = yield* ServerSettingsService;\n  const latest = yield* Ref.make(Option.none<DesktopHostTelemetrySnapshot>());\n  const receiverStartedAt = yield* DateTime.now;\n  const lastContactAtMs = yield* Ref.make(\n    initialDesktopTelemetryContactAt(\n      config.desktopTelemetryFd,\n      DateTime.toEpochMillis(receiverStartedAt),\n    ),\n  );\n  const snapshotStaleAfterMs = yield* Ref.make(\n    resolveDesktopTelemetrySnapshotStaleAfterMs(\n      DEFAULT_HOST_POWER_ACTIVE_INTERVAL_MS,\n      DEFAULT_HOST_POWER_IDLE_INTERVAL_MS,\n    ),\n  );\n  const changes = yield* PubSub.sliding<DesktopHostTelemetrySnapshot>(8);\n  const healthChanges = yield* PubSub.sliding<DesktopTelemetryReceiverHealth>(4);\n  const controlMutex = yield* Semaphore.make(1);\n  const snapshotMutex = yield* Semaphore.make(1);\n  const health = yield* Ref.make<DesktopTelemetryReceiverHealth>({\n    status: config.desktopTelemetryFd === undefined ? \"unavailable\" : \"starting\",\n    lastSampleAt: Option.none(),\n    lastError:\n      config.desktopTelemetryFd === undefined\n        ? Option.some(\n            new DesktopTelemetryDescriptorUnavailable({\n              mode: config.mode,\n            }).message,\n          )\n        : Option.none(),\n  });\n  const updateHealth = (\n    update: (current: DesktopTelemetryReceiverHealth) => DesktopTelemetryReceiverHealth,\n  ) =>\n    Ref.modify(health, (current) => {\n      const next = update(current);\n      return [next, next];\n    }).pipe(\n      Effect.flatMap((next) => PubSub.publish(healthChanges, next)),\n      Effect.asVoid,\n    );\n  const updateSampleHealth = (sampledAt: DateTime.Utc) =>\n    recordDesktopTelemetrySampleHealth(health, healthChanges, sampledAt);\n\n  const sendControlMessage = (message: DesktopTelemetryControlMessage) =>\n    controlMutex.withPermits(1)(\n      Effect.gen(function* () {\n        const fd = config.desktopTelemetryControlFd;\n        if (fd === undefined) return;\n        const encoded = yield* encodeControlMessage(message).pipe(\n          Effect.mapError(\n            (cause) =>\n              new DesktopTelemetryControlFailed({\n                fd,\n                operation: \"encode\",\n                cause,\n              }),\n          ),\n        );\n        yield* writeAllToFileDescriptor(fd, Buffer.from(`${encoded}\\n`)).pipe(\n          Effect.tapError((error) =>\n            updateHealth((current) => ({\n              ...current,\n              status: \"degraded\",\n              lastError: Option.some(error.message),\n            })),\n          ),\n        );\n      }),\n    );\n  const setDiagnosticsDemand: DesktopTelemetryReceiver[\"Service\"][\"setDiagnosticsDemand\"] = (\n    enabled,\n  ) =>\n    sendControlMessage({\n      version: 1,\n      type: \"setDiagnosticsDemand\",\n      enabled,\n    });\n\n  const sendHostPowerIntervals = (\n    settings: Parameters<typeof resolveServerBackgroundActivitySettings>[0],\n  ) => {\n    const resolved = resolveServerBackgroundActivitySettings(settings);\n    const activeIntervalMs = Math.max(\n      1,\n      Math.round(Duration.toMillis(resolved.hostPowerMonitorActiveInterval)),\n    );\n    const idleIntervalMs = Math.max(\n      1,\n      Math.round(Duration.toMillis(resolved.hostPowerMonitorIdleInterval)),\n    );\n    return sendControlMessage({\n      version: 1,\n      type: \"setHostPowerIntervals\",\n      activeIntervalMs,\n      idleIntervalMs,\n    }).pipe(\n      Effect.andThen(\n        Ref.set(\n          snapshotStaleAfterMs,\n          resolveDesktopTelemetrySnapshotStaleAfterMs(activeIntervalMs, idleIntervalMs),\n        ),\n      ),\n    );\n  };\n  if (config.desktopTelemetryControlFd !== undefined) {\n    const settingsChanges = yield* serverSettings.subscribeChanges;\n    const settings = yield* serverSettings.getSettings;\n    yield* sendHostPowerIntervals(settings).pipe(\n      Effect.catchCause((cause) =>\n        Effect.logWarning(\"Failed to configure desktop host-power intervals\", {\n          cause: String(cause),\n        }),\n      ),\n    );\n    yield* settingsChanges.pipe(\n      Stream.runForEach((settings) =>\n        sendHostPowerIntervals(settings).pipe(\n          Effect.catchCause((cause) =>\n            Effect.logWarning(\"Failed to update desktop host-power intervals\", {\n              cause: String(cause),\n            }),\n          ),\n        ),\n      ),\n      Effect.forkScoped,\n    );\n  }\n\n  if (config.desktopTelemetryFd !== undefined) {\n    const fd = config.desktopTelemetryFd;\n    const readable = yield* Effect.acquireRelease(\n      Effect.try({\n        try: () =>\n          NodeFS.createReadStream(\"\", {\n            fd,\n            autoClose: true,\n          }),\n        catch: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),\n      }),\n      (stream) =>\n        Effect.sync(() => {\n          stream.destroy();\n        }),\n    );\n\n    const messages: Stream.Stream<DesktopHostTelemetryMessageValue, DesktopTelemetryReceiverError> =\n      NodeStream.fromReadable<Uint8Array, DesktopTelemetryStreamFailed>({\n        evaluate: () => readable,\n        closeOnDone: true,\n        onError: (cause) => new DesktopTelemetryStreamFailed({ fd, cause }),\n      }).pipe(\n        Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),\n        Stream.mapEffect(\n          (\n            value,\n          ): Effect.Effect<\n            DesktopHostTelemetryMessageValue,\n            DesktopTelemetryProtocolMismatch | DesktopTelemetryDecodeFailed\n          > => {\n            const version = messageVersion(value);\n            if (version !== undefined && version !== 1) {\n              return Effect.fail(\n                new DesktopTelemetryProtocolMismatch({\n                  expectedVersion: 1,\n                  receivedVersion: version,\n                }),\n              );\n            }\n            return decodeMessage(value).pipe(\n              Effect.mapError((cause) => new DesktopTelemetryDecodeFailed({ cause })),\n            );\n          },\n        ),\n        Stream.mapError(normalizeReceiverError),\n      );\n\n    yield* messages.pipe(\n      Stream.runForEach((message) => {\n        const recordContact = DateTime.now.pipe(\n          Effect.flatMap((now) =>\n            Ref.set(lastContactAtMs, Option.some(DateTime.toEpochMillis(now))),\n          ),\n        );\n        if (message.type === \"desktopTelemetryHello\") {\n          return recordContact.pipe(\n            Effect.andThen(\n              updateHealth(\n                (current): DesktopTelemetryReceiverHealth => ({\n                  ...current,\n                  status: \"healthy\",\n                  lastError: Option.none(),\n                }),\n              ),\n            ),\n          );\n        }\n\n        const sampledAt = DateTime.makeUnsafe(message.sampledAtUnixMs);\n        return snapshotMutex.withPermits(1)(\n          recordContact.pipe(\n            Effect.andThen(Ref.set(latest, Option.some(message))),\n            Effect.andThen(updateSampleHealth(sampledAt)),\n            Effect.andThen(PubSub.publish(changes, message)),\n            Effect.asVoid,\n          ),\n        );\n      }),\n      Effect.andThen(\n        updateHealth(\n          (current): DesktopTelemetryReceiverHealth => ({\n            ...current,\n            status: \"stopped\",\n            lastError: Option.some(new DesktopTelemetryStreamClosed({ fd }).message),\n          }),\n        ),\n      ),\n      Effect.catch((error) =>\n        updateHealth(\n          (current): DesktopTelemetryReceiverHealth => ({\n            ...current,\n            status: \"degraded\",\n            lastError: Option.some(error.message),\n          }),\n        ),\n      ),\n      Effect.forkScoped,\n    );\n\n    yield* Effect.forever(\n      Effect.sleep(STALE_CHECK_INTERVAL).pipe(\n        Effect.andThen(\n          snapshotMutex.withPermits(1)(\n            Effect.gen(function* () {\n              const now = yield* DateTime.now;\n              const nowMs = DateTime.toEpochMillis(now);\n              const staleAfterMs = yield* Ref.get(snapshotStaleAfterMs);\n              const staleSnapshot = yield* Ref.modify(latest, (current) => {\n                if (\n                  Option.isNone(current) ||\n                  current.value.power.stale ||\n                  nowMs - current.value.sampledAtUnixMs < staleAfterMs\n                ) {\n                  return [Option.none<DesktopHostTelemetrySnapshot>(), current] as const;\n                }\n                const stale: DesktopHostTelemetrySnapshot = {\n                  ...current.value,\n                  power: { ...current.value.power, stale: true },\n                };\n                return [Option.some(stale), Option.some(stale)] as const;\n              });\n              if (Option.isNone(staleSnapshot)) {\n                const lastContact = yield* Ref.get(lastContactAtMs);\n                if (!isDesktopTelemetryContactStale(lastContact, nowMs)) return;\n                const staleMessage = new DesktopTelemetryStale({\n                  fd,\n                  staleAfterMs: INITIAL_SAMPLE_DEADLINE_MS,\n                }).message;\n                const changed = yield* Ref.modify(health, (current) => {\n                  if (\n                    current.status === \"stopped\" ||\n                    Option.isSome(current.lastSampleAt) ||\n                    (current.status === \"degraded\" &&\n                      Option.contains(current.lastError, staleMessage))\n                  ) {\n                    return [Option.none<DesktopTelemetryReceiverHealth>(), current] as const;\n                  }\n                  const next: DesktopTelemetryReceiverHealth = {\n                    ...current,\n                    status: \"degraded\",\n                    lastError: Option.some(staleMessage),\n                  };\n                  return [Option.some(next), next] as const;\n                });\n                if (Option.isSome(changed)) {\n                  yield* PubSub.publish(healthChanges, changed.value);\n                }\n                return;\n              }\n              yield* updateHealth((currentHealth) => ({\n                ...currentHealth,\n                status: currentHealth.status === \"stopped\" ? \"stopped\" : \"degraded\",\n                lastError:\n                  currentHealth.status === \"stopped\"\n                    ? currentHealth.lastError\n                    : Option.some(new DesktopTelemetryStale({ fd, staleAfterMs }).message),\n              }));\n              yield* PubSub.publish(changes, staleSnapshot.value);\n            }),\n          ),\n        ),\n      ),\n    ).pipe(Effect.forkScoped);\n  }\n\n  return DesktopTelemetryReceiver.of({\n    latest: Ref.get(latest),\n    changes: Stream.fromPubSub(changes),\n    subscribe: snapshotMutex.withPermits(1)(\n      Effect.gen(function* () {\n        const initial = yield* Ref.get(latest);\n        const subscription = yield* PubSub.subscribe(changes);\n        return {\n          latest: initial,\n          changes: Stream.fromSubscription(subscription),\n        };\n      }),\n    ),\n    health: Ref.get(health),\n    subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, Ref.get(health)),\n    setDiagnosticsDemand,\n  });\n});\n\nexport const layer = Layer.effect(DesktopTelemetryReceiver, make());\n\nexport const layerTest = (\n  overrides: Partial<DesktopTelemetryReceiver[\"Service\"]> = {},\n): Layer.Layer<DesktopTelemetryReceiver> => {\n  const latest = overrides.latest ?? Effect.succeedNone;\n  const changes = overrides.changes ?? Stream.empty;\n  const health =\n    overrides.health ??\n    Effect.succeed({\n      status: \"unavailable\" as const,\n      lastSampleAt: Option.none<DateTime.Utc>(),\n      lastError: Option.some(\"Desktop telemetry test implementation is unavailable.\"),\n    });\n  return Layer.succeed(\n    DesktopTelemetryReceiver,\n    DesktopTelemetryReceiver.of({\n      latest,\n      changes,\n      subscribe:\n        overrides.subscribe ??\n        latest.pipe(\n          Effect.map((initial) => ({\n            latest: initial,\n            changes,\n          })),\n        ),\n      health,\n      subscribeHealth:\n        overrides.subscribeHealth ??\n        health.pipe(\n          Effect.map((initial) => ({\n            latest: initial,\n            changes: Stream.empty,\n          })),\n        ),\n      setDiagnosticsDemand: () => Effect.void,\n      ...overrides,\n    }),\n  );\n};\n","import type { HostPowerSnapshot } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as DesktopTelemetryReceiver from \"../resourceTelemetry/DesktopTelemetryReceiver.ts\";\n\nexport class HostPowerMonitor extends Context.Service<\n  HostPowerMonitor,\n  {\n    readonly snapshot: Effect.Effect<HostPowerSnapshot>;\n    readonly report: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;\n    readonly streamChanges: Stream.Stream<HostPowerSnapshot>;\n  }\n>()(\"t3/background/HostPowerMonitor\") {}\n\nexport const makeUnknownSnapshot = (\n  source: HostPowerSnapshot[\"source\"],\n  updatedAt: HostPowerSnapshot[\"updatedAt\"],\n): HostPowerSnapshot => ({\n  source,\n  idle: \"unknown\",\n  idleSeconds: null,\n  locked: \"unknown\",\n  suspended: false,\n  onBattery: \"unknown\",\n  lowPowerMode: \"unknown\",\n  thermalState: \"unknown\",\n  stale: true,\n  updatedAt,\n});\n\nfunction samePowerState(left: HostPowerSnapshot, right: HostPowerSnapshot): boolean {\n  return (\n    left.source === right.source &&\n    left.idle === right.idle &&\n    left.locked === right.locked &&\n    left.suspended === right.suspended &&\n    left.onBattery === right.onBattery &&\n    left.lowPowerMode === right.lowPowerMode &&\n    left.thermalState === right.thermalState &&\n    left.stale === right.stale\n  );\n}\n\nexport const make = Effect.fn(\"background.hostPower.make\")(function* (\n  initialSnapshot?: HostPowerSnapshot,\n) {\n  const initial = initialSnapshot ?? makeUnknownSnapshot(\"unknown\", yield* DateTime.now);\n  const latestRef = yield* Ref.make(initial);\n  const changes = yield* PubSub.sliding<HostPowerSnapshot>(1);\n\n  const report: HostPowerMonitor[\"Service\"][\"report\"] = (snapshot) =>\n    Ref.modify(latestRef, (current) => {\n      if (DateTime.isLessThan(snapshot.updatedAt, current.updatedAt)) {\n        return [Option.none<HostPowerSnapshot>(), current] as const;\n      }\n      return [\n        samePowerState(current, snapshot) ? Option.none() : Option.some(snapshot),\n        snapshot,\n      ] as const;\n    }).pipe(\n      Effect.flatMap(\n        Option.match({\n          onNone: () => Effect.void,\n          onSome: (next) => PubSub.publish(changes, next),\n        }),\n      ),\n      Effect.asVoid,\n    );\n\n  return HostPowerMonitor.of({\n    snapshot: Ref.get(latestRef),\n    report,\n    streamChanges: Stream.fromPubSub(changes),\n  });\n});\n\nexport const layer = Layer.effect(\n  HostPowerMonitor,\n  Effect.gen(function* () {\n    const desktopTelemetry = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;\n    const desktopSubscription = yield* desktopTelemetry.subscribe;\n    const initial = desktopSubscription.latest;\n    const monitor = yield* Option.match(initial, {\n      onNone: () => make(),\n      onSome: (snapshot) => make(snapshot.power),\n    });\n    yield* desktopSubscription.changes.pipe(\n      Stream.map((snapshot) => snapshot.power),\n      Stream.runForEach(monitor.report),\n      Effect.forkScoped,\n    );\n    return monitor;\n  }),\n);\n","import {\n  type AuthSessionId,\n  type BackgroundPolicySnapshot,\n  type BackgroundScope,\n  type ClientActivityLease,\n  type ClientActivityReportInput,\n  type HostPowerSnapshot,\n  type RpcClientId,\n} from \"@t3tools/contracts\";\nimport {\n  getBackgroundActivityPresetSettings,\n  resolveServerBackgroundActivitySettings,\n  type ResolvedBackgroundActivitySettings,\n} from \"@t3tools/shared/backgroundActivitySettings\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\n\nimport { ServerSettingsService } from \"../serverSettings.ts\";\nimport { subscribeBeforeSnapshot } from \"../utils/subscribeBeforeSnapshot.ts\";\nimport * as HostPowerMonitor from \"./HostPowerMonitor.ts\";\n\nexport class BackgroundPolicy extends Context.Service<\n  BackgroundPolicy,\n  {\n    readonly reportClientActivity: (\n      sessionId: AuthSessionId,\n      rpcClientId: RpcClientId,\n      input: ClientActivityReportInput,\n    ) => Effect.Effect<void>;\n    readonly removeRpcClient: (\n      sessionId: AuthSessionId,\n      rpcClientId: RpcClientId,\n    ) => Effect.Effect<void>;\n    readonly reportHostPowerState: (snapshot: HostPowerSnapshot) => Effect.Effect<void>;\n    readonly snapshot: Effect.Effect<BackgroundPolicySnapshot>;\n    readonly streamChanges: Stream.Stream<BackgroundPolicySnapshot>;\n    readonly subscribe: Effect.Effect<\n      {\n        readonly latest: BackgroundPolicySnapshot;\n        readonly changes: Stream.Stream<BackgroundPolicySnapshot>;\n      },\n      never,\n      Scope.Scope\n    >;\n    readonly hasDemand: (scope: BackgroundScope) => Effect.Effect<boolean>;\n    readonly shouldRunScopeWork: (scope: BackgroundScope) => Effect.Effect<boolean>;\n    readonly shouldRunOpportunisticWork: Effect.Effect<boolean>;\n  }\n>()(\"t3/background/BackgroundPolicy\") {}\n\nconst DEFAULT_LEASE_TTL_MS = 45_000;\nconst MAX_LEASE_TTL_MS = 120_000;\nexport const MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT = 16;\n\nfunction scopeKey(scope: BackgroundScope): string {\n  switch (scope.type) {\n    case \"server-config\":\n    case \"diagnostics\":\n      return scope.type;\n    case \"provider-status\":\n      return scope.instanceId ? `${scope.type}:${scope.instanceId}` : scope.type;\n    case \"vcs-status\":\n    case \"git-refs\":\n      return `${scope.type}:${scope.cwd}`;\n    case \"thread\":\n      return `${scope.type}:${scope.threadId}`;\n  }\n}\n\nfunction isLeaseActive(lease: ClientActivityLease, now: DateTime.Utc): boolean {\n  return DateTime.isGreaterThan(lease.expiresAt, now);\n}\n\nfunction leaseKey(lease: Pick<ClientActivityLease, \"sessionId\" | \"rpcClientId\" | \"clientId\">) {\n  return JSON.stringify([lease.sessionId, lease.rpcClientId, lease.clientId]);\n}\n\nexport function upsertClientActivityLease(\n  leases: ReadonlyMap<string, ClientActivityLease>,\n  lease: ClientActivityLease,\n  now: DateTime.Utc,\n): Map<string, ClientActivityLease> {\n  const next = new Map(leases);\n  for (const [key, current] of next) {\n    if (!isLeaseActive(current, now)) {\n      next.delete(key);\n    }\n  }\n\n  const key = leaseKey(lease);\n  if (!next.has(key)) {\n    let connectionLeaseCount = 0;\n    let oldestConnectionLease:\n      | {\n          readonly key: string;\n          readonly updatedAtMs: number;\n        }\n      | undefined;\n    for (const [currentKey, current] of next) {\n      if (current.sessionId !== lease.sessionId || current.rpcClientId !== lease.rpcClientId) {\n        continue;\n      }\n      connectionLeaseCount += 1;\n      const updatedAtMs = DateTime.toEpochMillis(current.updatedAt);\n      if (oldestConnectionLease === undefined || updatedAtMs < oldestConnectionLease.updatedAtMs) {\n        oldestConnectionLease = { key: currentKey, updatedAtMs };\n      }\n    }\n    if (\n      connectionLeaseCount >= MAX_CLIENT_ACTIVITY_LEASES_PER_RPC_CLIENT &&\n      oldestConnectionLease !== undefined\n    ) {\n      next.delete(oldestConnectionLease.key);\n    }\n  }\n\n  next.set(key, lease);\n  return next;\n}\n\nfunction isForegroundLease(lease: ClientActivityLease, now: DateTime.Utc): boolean {\n  return isLeaseActive(lease, now) && lease.visible && (lease.focused || lease.recentlyInteracted);\n}\n\nfunction leaseHasScope(lease: ClientActivityLease, scope: BackgroundScope): boolean {\n  const key = scopeKey(scope);\n  return lease.scopes.some((leaseScope) => scopeKey(leaseScope) === key);\n}\n\nfunction hasThermalPressure(hostPower: HostPowerSnapshot): boolean {\n  return hostPower.thermalState === \"serious\" || hostPower.thermalState === \"critical\";\n}\n\nfunction isHostConstrained(\n  hostPower: HostPowerSnapshot,\n  settings: ResolvedBackgroundActivitySettings,\n): boolean {\n  if (hostPower.stale) return false;\n  if (\n    hostPower.suspended ||\n    (settings.pauseWhenHostLocked && hostPower.locked === \"true\") ||\n    hasThermalPressure(hostPower)\n  ) {\n    return true;\n  }\n  if (settings.pauseWhenHostLowPower && hostPower.lowPowerMode === \"true\") return true;\n  return settings.pauseWhenOnBattery && hostPower.onBattery === \"true\";\n}\n\nfunction isClientConstrained(\n  lease: ClientActivityLease,\n  settings: ResolvedBackgroundActivitySettings,\n): boolean {\n  if (settings.pauseWhenClientLowPower && lease.lowPowerMode === \"true\") return true;\n  return settings.pauseWhenOnBattery && lease.batteryState === \"unplugged\";\n}\n\nfunction leaseMayRunScopedWork(\n  lease: ClientActivityLease,\n  scope: BackgroundScope,\n  now: DateTime.Utc,\n  settings: ResolvedBackgroundActivitySettings,\n): boolean {\n  const activeWithScope = isLeaseActive(lease, now) && leaseHasScope(lease, scope);\n  if (!activeWithScope || isClientConstrained(lease, settings)) {\n    return false;\n  }\n  if (settings.profile === \"performance\") {\n    return true;\n  }\n  return isForegroundLease(lease, now);\n}\n\nfunction computeSnapshot(input: {\n  readonly hostPower: HostPowerSnapshot;\n  readonly leases: ReadonlyMap<string, ClientActivityLease>;\n  readonly now: DateTime.Utc;\n  readonly settings: ResolvedBackgroundActivitySettings;\n  readonly updatedAt: DateTime.Utc;\n}): BackgroundPolicySnapshot {\n  const activeLeases = [...input.leases.values()].filter((lease) =>\n    isLeaseActive(lease, input.now),\n  );\n  const foregroundLeases = activeLeases.filter((lease) => isForegroundLease(lease, input.now));\n  const activeScopeKeys = new Set<string>();\n  for (const lease of activeLeases) {\n    for (const scope of lease.scopes) {\n      activeScopeKeys.add(scopeKey(scope));\n    }\n  }\n\n  return {\n    hostPower: input.hostPower,\n    leases: activeLeases,\n    activeForegroundLeaseCount: foregroundLeases.length,\n    activeScopeKeys: [...activeScopeKeys].toSorted(),\n    shouldRunOpportunisticWork:\n      foregroundLeases.some((lease) => !isClientConstrained(lease, input.settings)) &&\n      !isHostConstrained(input.hostPower, input.settings),\n    updatedAt: input.updatedAt,\n  };\n}\n\nexport const make = Effect.fn(\"background.policy.make\")(function* () {\n  const hostPowerMonitor = yield* HostPowerMonitor.HostPowerMonitor;\n  const serverSettings = yield* ServerSettingsService;\n  const leasesRef = yield* Ref.make(new Map<string, ClientActivityLease>());\n  const changes = yield* PubSub.sliding<BackgroundPolicySnapshot>(1);\n  const publishMutex = yield* Semaphore.make(1);\n\n  const backgroundActivitySettings = serverSettings.getSettings.pipe(\n    Effect.map(resolveServerBackgroundActivitySettings),\n    Effect.orElseSucceed(() => getBackgroundActivityPresetSettings(\"balanced\")),\n  );\n\n  const snapshot = Effect.gen(function* () {\n    const [hostPower, leases, now, settings] = yield* Effect.all([\n      hostPowerMonitor.snapshot,\n      Ref.get(leasesRef),\n      DateTime.now,\n      backgroundActivitySettings,\n    ]);\n    return computeSnapshot({ hostPower, leases, now, settings, updatedAt: now });\n  });\n\n  const publishSnapshotUnlocked = snapshot.pipe(\n    Effect.flatMap((next) => PubSub.publish(changes, next)),\n  );\n  const publishSnapshot = publishMutex.withPermits(1)(publishSnapshotUnlocked);\n\n  const reportClientActivity: BackgroundPolicy[\"Service\"][\"reportClientActivity\"] = (\n    sessionId,\n    rpcClientId,\n    input,\n  ) =>\n    publishMutex.withPermits(1)(\n      Effect.gen(function* () {\n        const ttlMs = Math.min(\n          Math.max(input.ttlMs ?? DEFAULT_LEASE_TTL_MS, 1_000),\n          MAX_LEASE_TTL_MS,\n        );\n        const now = yield* DateTime.now;\n        const expiresAt = DateTime.add(now, { milliseconds: ttlMs });\n        const lease: ClientActivityLease = {\n          sessionId,\n          rpcClientId,\n          clientId: input.clientId,\n          clientKind: input.clientKind,\n          visible: input.visible,\n          focused: input.focused,\n          recentlyInteracted: input.recentlyInteracted,\n          ...(input.appState !== undefined ? { appState: input.appState } : {}),\n          ...(input.lowPowerMode !== undefined ? { lowPowerMode: input.lowPowerMode } : {}),\n          ...(input.batteryState !== undefined ? { batteryState: input.batteryState } : {}),\n          ...(input.networkType !== undefined ? { networkType: input.networkType } : {}),\n          scopes: input.scopes,\n          updatedAt: now,\n          expiresAt,\n        };\n        yield* Ref.update(leasesRef, (leases) => upsertClientActivityLease(leases, lease, now));\n        yield* publishSnapshotUnlocked;\n      }),\n    );\n\n  const removeRpcClient: BackgroundPolicy[\"Service\"][\"removeRpcClient\"] = (\n    sessionId,\n    rpcClientId,\n  ) =>\n    publishMutex.withPermits(1)(\n      Ref.update(leasesRef, (leases) => {\n        const next = new Map(leases);\n        for (const [key, lease] of next) {\n          if (lease.sessionId === sessionId && lease.rpcClientId === rpcClientId) {\n            next.delete(key);\n          }\n        }\n        return next;\n      }).pipe(Effect.andThen(publishSnapshotUnlocked), Effect.asVoid),\n    );\n\n  const hasDemand: BackgroundPolicy[\"Service\"][\"hasDemand\"] = (scope) =>\n    Effect.map(snapshot, (current) => current.activeScopeKeys.includes(scopeKey(scope)));\n\n  const shouldRunScopeWork: BackgroundPolicy[\"Service\"][\"shouldRunScopeWork\"] = (scope) =>\n    Effect.gen(function* () {\n      const [current, settings] = yield* Effect.all([snapshot, backgroundActivitySettings]);\n      if (isHostConstrained(current.hostPower, settings)) {\n        return false;\n      }\n      return current.leases.some((lease) =>\n        leaseMayRunScopedWork(lease, scope, current.updatedAt, settings),\n      );\n    });\n\n  const shouldRunOpportunisticWork = Effect.map(\n    snapshot,\n    (current) => current.shouldRunOpportunisticWork,\n  );\n\n  yield* Stream.runForEach(hostPowerMonitor.streamChanges, () => publishSnapshot).pipe(\n    Effect.forkScoped,\n  );\n  yield* Stream.runForEach(serverSettings.streamChanges, () => publishSnapshot).pipe(\n    Effect.forkScoped,\n  );\n\n  yield* Effect.forever(\n    Effect.sleep(\"15 seconds\").pipe(\n      Effect.andThen(\n        publishMutex.withPermits(1)(\n          Effect.gen(function* () {\n            const now = yield* DateTime.now;\n            yield* Ref.update(leasesRef, (leases) => {\n              const next = new Map(leases);\n              for (const [key, lease] of next) {\n                if (!isLeaseActive(lease, now)) {\n                  next.delete(key);\n                }\n              }\n              return next;\n            });\n            yield* publishSnapshotUnlocked;\n          }),\n        ),\n      ),\n    ),\n  ).pipe(Effect.forkScoped);\n\n  return BackgroundPolicy.of({\n    reportClientActivity,\n    removeRpcClient,\n    reportHostPowerState: hostPowerMonitor.report,\n    snapshot,\n    streamChanges: Stream.fromPubSub(changes),\n    subscribe: subscribeBeforeSnapshot(changes, snapshot, publishMutex),\n    hasDemand,\n    shouldRunScopeWork,\n    shouldRunOpportunisticWork,\n  });\n});\n\nexport const layer = Layer.effect(BackgroundPolicy, make());\n","/**\n * Backend paths the web dev server proxies in single-origin browser dev.\n *\n * Two consumers must agree on this list: the Vite proxy map\n * (apps/web/vite.config.ts) that forwards these to the backend, and the\n * server's dev catch-all (apps/server/src/http.ts) that 404s them instead of\n * redirecting back to Vite. Drift is silent and nasty in both directions — a\n * prefix only Vite knows gets answered with index.html; a prefix only the\n * server knows redirect-loops through the proxy.\n */\nexport const DEV_PROXIED_PATH_PREFIXES = [\"/api\", \"/oauth\", \"/.well-known\", \"/ws\"] as const;\n\nexport function isDevProxiedPath(pathname: string): boolean {\n  return DEV_PROXIED_PATH_PREFIXES.some(\n    (prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`),\n  );\n}\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFS from \"node:fs\";\nimport * as NodePath from \"node:path\";\nimport * as Schema from \"effect/Schema\";\n\nexport interface RotatingFileSinkOptions {\n  readonly filePath: string;\n  readonly maxBytes: number;\n  readonly maxFiles: number;\n  readonly throwOnError?: boolean;\n}\n\nexport class RotatingFileSinkConfigurationError extends Schema.TaggedErrorClass<RotatingFileSinkConfigurationError>()(\n  \"RotatingFileSinkConfigurationError\",\n  {\n    option: Schema.Literals([\"maxBytes\", \"maxFiles\"]),\n    received: Schema.Number,\n    minimum: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `${this.option} must be >= ${this.minimum} (received ${this.received})`;\n  }\n}\n\nexport class RotatingFileSinkError extends Schema.TaggedErrorClass<RotatingFileSinkError>()(\n  \"RotatingFileSinkError\",\n  {\n    operation: Schema.Literals([\"initialize\", \"read\", \"write\", \"rotate\", \"prune\"]),\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to ${this.operation} rotating log file ${this.filePath}`;\n  }\n}\n\nconst isRotatingFileSinkError = Schema.is(RotatingFileSinkError);\n\nconst isFileNotFoundError = (cause: unknown): cause is NodeJS.ErrnoException =>\n  cause instanceof Error && \"code\" in cause && cause.code === \"ENOENT\";\n\nexport class RotatingFileSink {\n  private readonly filePath: string;\n  private readonly maxBytes: number;\n  private readonly maxFiles: number;\n  private readonly throwOnError: boolean;\n  private currentSize = 0;\n\n  constructor(options: RotatingFileSinkOptions) {\n    if (options.maxBytes < 1) {\n      throw new RotatingFileSinkConfigurationError({\n        option: \"maxBytes\",\n        received: options.maxBytes,\n        minimum: 1,\n      });\n    }\n    if (options.maxFiles < 1) {\n      throw new RotatingFileSinkConfigurationError({\n        option: \"maxFiles\",\n        received: options.maxFiles,\n        minimum: 1,\n      });\n    }\n\n    this.filePath = options.filePath;\n    this.maxBytes = options.maxBytes;\n    this.maxFiles = options.maxFiles;\n    this.throwOnError = options.throwOnError ?? false;\n\n    try {\n      NodeFS.mkdirSync(NodePath.dirname(this.filePath), { recursive: true });\n    } catch (cause) {\n      throw new RotatingFileSinkError({\n        operation: \"initialize\",\n        filePath: this.filePath,\n        cause,\n      });\n    }\n    this.pruneOverflowBackups();\n    this.currentSize = this.readCurrentSize();\n  }\n\n  write(chunk: string | Buffer): void {\n    const buffer = typeof chunk === \"string\" ? Buffer.from(chunk) : chunk;\n    if (buffer.length === 0) return;\n\n    try {\n      if (this.currentSize > 0 && this.currentSize + buffer.length > this.maxBytes) {\n        this.rotate();\n      }\n\n      NodeFS.appendFileSync(this.filePath, buffer);\n      this.currentSize += buffer.length;\n    } catch (cause) {\n      if (isRotatingFileSinkError(cause)) {\n        throw cause;\n      }\n      if (this.throwOnError) {\n        throw new RotatingFileSinkError({\n          operation: \"write\",\n          filePath: this.filePath,\n          cause,\n        });\n      }\n      this.currentSize = this.readCurrentSize();\n    }\n  }\n\n  private rotate(): void {\n    try {\n      const oldest = this.withSuffix(this.maxFiles);\n      if (NodeFS.existsSync(oldest)) {\n        NodeFS.rmSync(oldest, { force: true });\n      }\n\n      for (let index = this.maxFiles - 1; index >= 1; index -= 1) {\n        const source = this.withSuffix(index);\n        const target = this.withSuffix(index + 1);\n        if (NodeFS.existsSync(source)) {\n          NodeFS.renameSync(source, target);\n        }\n      }\n\n      if (NodeFS.existsSync(this.filePath)) {\n        NodeFS.renameSync(this.filePath, this.withSuffix(1));\n      }\n\n      this.currentSize = 0;\n    } catch (cause) {\n      if (this.throwOnError) {\n        throw new RotatingFileSinkError({\n          operation: \"rotate\",\n          filePath: this.filePath,\n          cause,\n        });\n      }\n      this.currentSize = this.readCurrentSize();\n    }\n  }\n\n  private pruneOverflowBackups(): void {\n    try {\n      const dir = NodePath.dirname(this.filePath);\n      const baseName = NodePath.basename(this.filePath);\n      for (const entry of NodeFS.readdirSync(dir)) {\n        if (!entry.startsWith(`${baseName}.`)) continue;\n        const suffix = Number(entry.slice(baseName.length + 1));\n        if (!Number.isInteger(suffix) || suffix <= this.maxFiles) continue;\n        NodeFS.rmSync(NodePath.join(dir, entry), { force: true });\n      }\n    } catch (cause) {\n      if (this.throwOnError) {\n        throw new RotatingFileSinkError({\n          operation: \"prune\",\n          filePath: this.filePath,\n          cause,\n        });\n      }\n    }\n  }\n\n  private readCurrentSize(): number {\n    try {\n      return NodeFS.statSync(this.filePath).size;\n    } catch (cause) {\n      if (isFileNotFoundError(cause)) {\n        return 0;\n      }\n      throw new RotatingFileSinkError({\n        operation: \"read\",\n        filePath: this.filePath,\n        cause,\n      });\n    }\n  }\n\n  private withSuffix(index: number): string {\n    return `${this.filePath}.${index}`;\n  }\n}\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport type * as Exit from \"effect/Exit\";\nimport * as ExitRuntime from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Tracer from \"effect/Tracer\";\nimport { OtlpResource, OtlpTracer } from \"effect/unstable/observability\";\n\nimport { RotatingFileSink } from \"./logging.ts\";\n\nconst FLUSH_BUFFER_THRESHOLD = 256;\nconst textEncoder = new TextEncoder();\n\nexport type TraceAttributes = Readonly<Record<string, unknown>>;\n\nexport interface TraceRecordEvent {\n  readonly name: string;\n  readonly timeUnixNano: string;\n  readonly attributes: Readonly<Record<string, unknown>>;\n}\n\nexport interface TraceRecordLink {\n  readonly traceId: string;\n  readonly spanId: string;\n  readonly attributes: Readonly<Record<string, unknown>>;\n}\n\ninterface BaseTraceRecord {\n  readonly name: string;\n  readonly kind: string;\n  readonly traceId: string;\n  readonly spanId: string;\n  readonly parentSpanId?: string;\n  readonly sampled: boolean;\n  readonly startTimeUnixNano: string;\n  readonly endTimeUnixNano: string;\n  readonly durationMs: number;\n  readonly attributes: Readonly<Record<string, unknown>>;\n  readonly events: ReadonlyArray<TraceRecordEvent>;\n  readonly links: ReadonlyArray<TraceRecordLink>;\n}\n\nexport interface EffectTraceRecord extends BaseTraceRecord {\n  readonly type: \"effect-span\";\n  readonly exit:\n    | {\n        readonly _tag: \"Success\";\n      }\n    | {\n        readonly _tag: \"Interrupted\";\n        readonly cause: string;\n      }\n    | {\n        readonly _tag: \"Failure\";\n        readonly cause: string;\n      };\n}\n\nexport interface OtlpTraceRecord extends BaseTraceRecord {\n  readonly type: \"otlp-span\";\n  readonly resourceAttributes: Readonly<Record<string, unknown>>;\n  readonly scope: Readonly<{\n    readonly name?: string;\n    readonly version?: string;\n    readonly attributes: Readonly<Record<string, unknown>>;\n  }>;\n  readonly status?:\n    | {\n        readonly code?: string;\n        readonly message?: string;\n      }\n    | undefined;\n}\n\nexport type TraceRecord = EffectTraceRecord | OtlpTraceRecord;\n\nfunction isStructuralTag(value: unknown): value is string {\n  return (\n    typeof value === \"string\" &&\n    value.length > 0 &&\n    value.length <= 128 &&\n    /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value)\n  );\n}\n\nexport function errorTag(error: unknown): string {\n  try {\n    if (typeof error === \"object\" && error !== null && \"_tag\" in error) {\n      return isStructuralTag(error._tag) ? error._tag : \"TaggedError\";\n    }\n    if (error instanceof Error) {\n      return isStructuralTag(error.name) ? error.name : \"Error\";\n    }\n  } catch {\n    return \"UnknownError\";\n  }\n  return typeof error;\n}\n\nexport function causeErrorTag(cause: Cause.Cause<unknown>): string {\n  const failure = Cause.findErrorOption(cause);\n  if (Option.isSome(failure)) {\n    return errorTag(failure.value);\n  }\n  return cause.reasons[0]?._tag ?? \"Empty\";\n}\n\nexport interface TraceSinkOptions {\n  readonly filePath: string;\n  readonly maxBytes: number;\n  readonly maxFiles: number;\n  readonly batchWindowMs: number;\n  readonly onFlush?: (stats: TraceSinkFlushStats) => Effect.Effect<void>;\n}\n\nexport interface TraceSinkFlushStats {\n  readonly logicalWriteBytes: number;\n  readonly count: number;\n  readonly durationMs: number;\n}\n\nexport interface TraceSink {\n  readonly filePath: string;\n  push: (record: TraceRecord) => void;\n  flush: Effect.Effect<void>;\n  close: () => Effect.Effect<void>;\n}\n\nexport interface LocalFileTracerOptions extends TraceSinkOptions {\n  readonly delegate?: Tracer.Tracer;\n  readonly sink?: TraceSink;\n}\n\ntype OtlpSpan = OtlpTracer.ScopeSpan[\"spans\"][number];\ntype OtlpSpanEvent = OtlpSpan[\"events\"][number];\ntype OtlpSpanLink = OtlpSpan[\"links\"][number];\ntype OtlpSpanStatus = OtlpSpan[\"status\"];\n\ninterface SerializableSpan {\n  readonly name: string;\n  readonly traceId: string;\n  readonly spanId: string;\n  readonly parent: Option.Option<Tracer.AnySpan>;\n  readonly status: Tracer.SpanStatus;\n  readonly sampled: boolean;\n  readonly kind: Tracer.SpanKind;\n  readonly attributes: ReadonlyMap<string, unknown>;\n  readonly links: ReadonlyArray<Tracer.SpanLink>;\n  readonly events: ReadonlyArray<\n    readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]\n  >;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction markSeen(value: object, seen: WeakSet<object>): boolean {\n  if (seen.has(value)) {\n    return true;\n  }\n  seen.add(value);\n  return false;\n}\n\nfunction normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {\n  if (\n    value === null ||\n    value === undefined ||\n    typeof value === \"string\" ||\n    typeof value === \"number\" ||\n    typeof value === \"boolean\"\n  ) {\n    return value ?? null;\n  }\n  if (typeof value === \"bigint\") {\n    return value.toString();\n  }\n  if (value instanceof Date) {\n    return Number.isNaN(value.getTime()) ? \"Invalid Date\" : value.toISOString();\n  }\n  if (value instanceof Error) {\n    return {\n      name: value.name,\n      message: value.message,\n      ...(value.stack ? { stack: value.stack } : {}),\n    };\n  }\n  if (Array.isArray(value)) {\n    if (markSeen(value, seen)) {\n      return \"[Circular]\";\n    }\n    return value.map((entry) => normalizeJsonValue(entry, seen));\n  }\n  if (value instanceof Map) {\n    if (markSeen(value, seen)) {\n      return \"[Circular]\";\n    }\n    return Object.fromEntries(\n      Array.from(value.entries(), ([key, entryValue]) => [\n        String(key),\n        normalizeJsonValue(entryValue, seen),\n      ]),\n    );\n  }\n  if (value instanceof Set) {\n    if (markSeen(value, seen)) {\n      return \"[Circular]\";\n    }\n    return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));\n  }\n  if (!isPlainObject(value)) {\n    return String(value);\n  }\n  if (markSeen(value, seen)) {\n    return \"[Circular]\";\n  }\n  return Object.fromEntries(\n    Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),\n  );\n}\n\nexport function compactTraceAttributes(\n  attributes: Readonly<Record<string, unknown>>,\n): TraceAttributes {\n  const entries: Array<[string, unknown]> = [];\n  for (const [key, value] of Object.entries(attributes)) {\n    if (value !== undefined) {\n      entries.push([key, normalizeJsonValue(value)]);\n    }\n  }\n  return Object.fromEntries(entries);\n}\n\nfunction formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord[\"exit\"] {\n  if (ExitRuntime.isSuccess(exit)) {\n    return { _tag: \"Success\" };\n  }\n  if (Cause.hasInterruptsOnly(exit.cause)) {\n    return {\n      _tag: \"Interrupted\",\n      cause: Cause.pretty(exit.cause),\n    };\n  }\n  return {\n    _tag: \"Failure\",\n    cause: Cause.pretty(exit.cause),\n  };\n}\n\nconst TRACE_ATTRIBUTE_MAX_LENGTH = 500;\nconst TRACE_ATTRIBUTE_TRUNCATED_LENGTH = 200;\nconst TRACE_ATTRIBUTE_TRUNCATION_SUFFIX = \"…[truncated]\";\nconst ALWAYS_TRUNCATED_TRACE_ATTRIBUTES: ReadonlySet<string> = new Set([\"db.query.text\"]);\n\n// Clamps strings nested inside already-normalized attribute values (arrays and\n// plain objects from normalizeJsonValue, e.g. an Error's `stack`). Returns the\n// input reference when nothing was clamped.\nfunction truncateNestedValue(value: unknown): unknown {\n  if (typeof value === \"string\") {\n    return value.length <= TRACE_ATTRIBUTE_MAX_LENGTH\n      ? value\n      : `${value.slice(0, TRACE_ATTRIBUTE_MAX_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;\n  }\n  if (Array.isArray(value)) {\n    const truncated = value.map(truncateNestedValue);\n    return truncated.some((entry, index) => entry !== value[index]) ? truncated : value;\n  }\n  if (isPlainObject(value)) {\n    let truncated: Record<string, unknown> | undefined;\n    for (const [key, entry] of Object.entries(value)) {\n      const next = truncateNestedValue(entry);\n      if (next === entry) continue;\n      truncated ??= { ...value };\n      truncated[key] = next;\n    }\n    return truncated ?? value;\n  }\n  return value;\n}\n\n/**\n * Clamps oversized attribute values on the serialized trace record so the file\n * sink stays small, including strings nested inside arrays and objects (e.g.\n * error stacks). Returns a new record when anything was clamped; never\n * mutates the input (the live span's attributes are shared with other tracers).\n */\nexport function truncateTraceAttributes(attributes: TraceAttributes): TraceAttributes {\n  let truncated: Record<string, unknown> | undefined;\n  for (const [key, value] of Object.entries(attributes)) {\n    if (typeof value === \"string\" && ALWAYS_TRUNCATED_TRACE_ATTRIBUTES.has(key)) {\n      if (value.length <= TRACE_ATTRIBUTE_TRUNCATED_LENGTH) continue;\n      truncated ??= { ...attributes };\n      truncated[key] =\n        `${value.slice(0, TRACE_ATTRIBUTE_TRUNCATED_LENGTH)}${TRACE_ATTRIBUTE_TRUNCATION_SUFFIX}`;\n      continue;\n    }\n    const next = truncateNestedValue(value);\n    if (next === value) continue;\n    truncated ??= { ...attributes };\n    truncated[key] = next;\n  }\n  return truncated ?? attributes;\n}\n\nexport function spanToTraceRecord(span: SerializableSpan): EffectTraceRecord {\n  const status = span.status as Extract<Tracer.SpanStatus, { _tag: \"Ended\" }>;\n  const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;\n\n  return {\n    type: \"effect-span\",\n    name: span.name,\n    traceId: span.traceId,\n    spanId: span.spanId,\n    ...(parentSpanId ? { parentSpanId } : {}),\n    sampled: span.sampled,\n    kind: span.kind,\n    startTimeUnixNano: String(status.startTime),\n    endTimeUnixNano: String(status.endTime),\n    durationMs: Number(status.endTime - status.startTime) / 1_000_000,\n    attributes: truncateTraceAttributes(\n      compactTraceAttributes(Object.fromEntries(span.attributes)),\n    ),\n    events: span.events.map(([name, startTime, attributes]) => ({\n      name,\n      timeUnixNano: String(startTime),\n      attributes: truncateTraceAttributes(compactTraceAttributes(attributes)),\n    })),\n    links: span.links.map((link) => ({\n      traceId: link.span.traceId,\n      spanId: link.span.spanId,\n      attributes: truncateTraceAttributes(compactTraceAttributes(link.attributes)),\n    })),\n    exit: formatTraceExit(status.exit),\n  };\n}\n\nexport const makeTraceSink = Effect.fn(\"makeTraceSink\")(function* (options: TraceSinkOptions) {\n  const sink = new RotatingFileSink({\n    filePath: options.filePath,\n    maxBytes: options.maxBytes,\n    maxFiles: options.maxFiles,\n    throwOnError: true,\n  });\n\n  let buffer: Array<string> = [];\n  let pendingFlushStats: TraceSinkFlushStats = {\n    logicalWriteBytes: 0,\n    count: 0,\n    durationMs: 0,\n  };\n\n  const flushUnsafe = () => {\n    if (buffer.length === 0) {\n      return;\n    }\n\n    const records = buffer;\n    buffer = [];\n    let persistedCount = 0;\n\n    while (persistedCount < records.length) {\n      const firstRecordBytes = textEncoder.encode(records[persistedCount]).byteLength;\n      if (firstRecordBytes > options.maxBytes) {\n        persistedCount += 1;\n        continue;\n      }\n\n      let nextIndex = persistedCount + 1;\n      let chunkBytes = firstRecordBytes;\n      while (nextIndex < records.length) {\n        const nextRecordBytes = textEncoder.encode(records[nextIndex]).byteLength;\n        if (chunkBytes + nextRecordBytes > options.maxBytes) break;\n        chunkBytes += nextRecordBytes;\n        nextIndex += 1;\n      }\n\n      const chunk = records.slice(persistedCount, nextIndex).join(\"\");\n      const startedAt = performance.now();\n      try {\n        sink.write(chunk);\n      } catch {\n        buffer.unshift(...records.slice(persistedCount));\n        return;\n      }\n      pendingFlushStats = {\n        logicalWriteBytes: pendingFlushStats.logicalWriteBytes + chunkBytes,\n        count: pendingFlushStats.count + nextIndex - persistedCount,\n        durationMs: pendingFlushStats.durationMs + Math.max(0, performance.now() - startedAt),\n      };\n      persistedCount = nextIndex;\n    }\n  };\n\n  const flush = Effect.sync(() => {\n    flushUnsafe();\n    const stats = pendingFlushStats;\n    pendingFlushStats = {\n      logicalWriteBytes: 0,\n      count: 0,\n      durationMs: 0,\n    };\n    return stats;\n  }).pipe(\n    Effect.flatMap((stats) =>\n      stats.count > 0 && options.onFlush ? options.onFlush(stats).pipe(Effect.ignore) : Effect.void,\n    ),\n    Effect.withTracerEnabled(false),\n  );\n\n  yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));\n  yield* Effect.forkScoped(\n    Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),\n  );\n\n  return {\n    filePath: options.filePath,\n    push(record) {\n      try {\n        buffer.push(`${JSON.stringify(record)}\\n`);\n        if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {\n          flushUnsafe();\n        }\n      } catch {\n        return;\n      }\n    },\n    flush,\n    close: () => flush,\n  } satisfies TraceSink;\n});\n\nclass LocalFileSpan implements Tracer.Span {\n  readonly _tag = \"Span\";\n  readonly name: string;\n  readonly spanId: string;\n  readonly traceId: string;\n  readonly parent: Option.Option<Tracer.AnySpan>;\n  readonly annotations: Tracer.Span[\"annotations\"];\n  readonly links: Array<Tracer.SpanLink>;\n  readonly sampled: boolean;\n  readonly kind: Tracer.SpanKind;\n\n  status: Tracer.SpanStatus;\n  attributes: Map<string, unknown>;\n  events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;\n  private readonly delegate: Tracer.Span;\n  private readonly push: (record: EffectTraceRecord) => void;\n\n  constructor(\n    options: Parameters<Tracer.Tracer[\"span\"]>[0],\n    delegate: Tracer.Span,\n    push: (record: EffectTraceRecord) => void,\n  ) {\n    this.delegate = delegate;\n    this.push = push;\n    this.name = delegate.name;\n    this.spanId = delegate.spanId;\n    this.traceId = delegate.traceId;\n    this.parent = options.parent;\n    this.annotations = options.annotations;\n    this.links = [...options.links];\n    this.sampled = delegate.sampled;\n    this.kind = delegate.kind;\n    this.status = {\n      _tag: \"Started\",\n      startTime: options.startTime,\n    };\n    this.attributes = new Map();\n    this.events = [];\n  }\n\n  end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {\n    this.status = {\n      _tag: \"Ended\",\n      startTime: this.status.startTime,\n      endTime,\n      exit,\n    };\n    this.delegate.end(endTime, exit);\n\n    if (this.sampled) {\n      this.push(spanToTraceRecord(this));\n    }\n  }\n\n  attribute(key: string, value: unknown): void {\n    this.attributes.set(key, value);\n    this.delegate.attribute(key, value);\n  }\n\n  event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {\n    const nextAttributes = attributes ?? {};\n    this.events.push([name, startTime, nextAttributes]);\n    this.delegate.event(name, startTime, nextAttributes);\n  }\n\n  addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {\n    this.links.push(...links);\n    this.delegate.addLinks(links);\n  }\n}\n\nexport const makeLocalFileTracer = Effect.fn(\"makeLocalFileTracer\")(function* (\n  options: LocalFileTracerOptions,\n) {\n  const sink =\n    options.sink ??\n    (yield* makeTraceSink({\n      filePath: options.filePath,\n      maxBytes: options.maxBytes,\n      maxFiles: options.maxFiles,\n      batchWindowMs: options.batchWindowMs,\n      ...(options.onFlush ? { onFlush: options.onFlush } : {}),\n    }));\n\n  const delegate =\n    options.delegate ??\n    Tracer.make({\n      span: (spanOptions) => new Tracer.NativeSpan(spanOptions),\n    });\n\n  return Tracer.make({\n    span(spanOptions) {\n      return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);\n    },\n    ...(delegate.context ? { context: delegate.context } : {}),\n  });\n});\n\nconst SPAN_KIND_MAP: Record<number, OtlpTraceRecord[\"kind\"]> = {\n  1: \"internal\",\n  2: \"server\",\n  3: \"client\",\n  4: \"producer\",\n  5: \"consumer\",\n};\n\nexport function decodeOtlpTraceRecords(\n  payload: OtlpTracer.TraceData,\n): ReadonlyArray<OtlpTraceRecord> {\n  const records: Array<OtlpTraceRecord> = [];\n\n  for (const resourceSpan of payload.resourceSpans) {\n    const resourceAttributes = decodeAttributes(resourceSpan.resource?.attributes ?? []);\n\n    for (const scopeSpan of resourceSpan.scopeSpans) {\n      for (const span of scopeSpan.spans) {\n        records.push(\n          otlpSpanToTraceRecord({\n            resourceAttributes,\n            scopeAttributes: decodeAttributes(\n              \"attributes\" in scopeSpan.scope && Array.isArray(scopeSpan.scope.attributes)\n                ? scopeSpan.scope.attributes\n                : [],\n            ),\n            scopeName: scopeSpan.scope.name,\n            scopeVersion:\n              \"version\" in scopeSpan.scope && typeof scopeSpan.scope.version === \"string\"\n                ? scopeSpan.scope.version\n                : undefined,\n            span,\n          }),\n        );\n      }\n    }\n  }\n\n  return records;\n}\n\nfunction otlpSpanToTraceRecord(input: {\n  readonly resourceAttributes: Readonly<Record<string, unknown>>;\n  readonly scopeAttributes: Readonly<Record<string, unknown>>;\n  readonly scopeName: string | undefined;\n  readonly scopeVersion: string | undefined;\n  readonly span: OtlpSpan;\n}): OtlpTraceRecord {\n  return {\n    type: \"otlp-span\",\n    name: input.span.name,\n    traceId: input.span.traceId,\n    spanId: input.span.spanId,\n    ...(input.span.parentSpanId ? { parentSpanId: input.span.parentSpanId } : {}),\n    sampled: true,\n    kind: normalizeSpanKind(input.span.kind),\n    startTimeUnixNano: input.span.startTimeUnixNano,\n    endTimeUnixNano: input.span.endTimeUnixNano,\n    durationMs:\n      Number(parseBigInt(input.span.endTimeUnixNano) - parseBigInt(input.span.startTimeUnixNano)) /\n      1_000_000,\n    attributes: decodeAttributes(input.span.attributes),\n    resourceAttributes: input.resourceAttributes,\n    scope: {\n      ...(input.scopeName ? { name: input.scopeName } : {}),\n      ...(input.scopeVersion ? { version: input.scopeVersion } : {}),\n      attributes: input.scopeAttributes,\n    },\n    events: decodeEvents(input.span.events),\n    links: decodeLinks(input.span.links),\n    status: decodeStatus(input.span.status),\n  };\n}\n\nfunction decodeStatus(input: OtlpSpanStatus): OtlpTraceRecord[\"status\"] {\n  const code = String(input.code);\n  const message = input.message;\n\n  return {\n    code,\n    ...(message ? { message } : {}),\n  };\n}\n\nfunction decodeEvents(input: ReadonlyArray<OtlpSpanEvent>): ReadonlyArray<TraceRecordEvent> {\n  return input.map((current) => ({\n    name: current.name,\n    timeUnixNano: current.timeUnixNano,\n    attributes: decodeAttributes(current.attributes),\n  }));\n}\n\nfunction decodeLinks(input: ReadonlyArray<OtlpSpanLink>): ReadonlyArray<TraceRecordLink> {\n  return input.flatMap((current) => {\n    const traceId = current.traceId;\n    const spanId = current.spanId;\n    return {\n      traceId,\n      spanId,\n      attributes: decodeAttributes(current.attributes),\n    };\n  });\n}\n\nfunction decodeAttributes(\n  input: ReadonlyArray<OtlpResource.KeyValue>,\n): Readonly<Record<string, unknown>> {\n  const entries: Record<string, unknown> = {};\n\n  for (const attribute of input) {\n    entries[attribute.key] = decodeValue(attribute.value);\n  }\n\n  return compactTraceAttributes(entries);\n}\n\nfunction decodeValue(input: OtlpResource.AnyValue | null | undefined): unknown {\n  if (input == null) {\n    return null;\n  }\n  if (\"stringValue\" in input) {\n    return input.stringValue;\n  }\n  if (\"boolValue\" in input) {\n    return input.boolValue;\n  }\n  if (\"intValue\" in input) {\n    return input.intValue;\n  }\n  if (\"doubleValue\" in input) {\n    return input.doubleValue;\n  }\n  if (\"bytesValue\" in input) {\n    return input.bytesValue;\n  }\n  if (input.arrayValue) {\n    return input.arrayValue.values.map((entry) => decodeValue(entry));\n  }\n  if (input.kvlistValue) {\n    return decodeAttributes(input.kvlistValue.values);\n  }\n  return null;\n}\n\nfunction normalizeSpanKind(input: number): OtlpTraceRecord[\"kind\"] {\n  return SPAN_KIND_MAP[input] || \"internal\";\n}\n\nfunction parseBigInt(input: string): bigint {\n  try {\n    return BigInt(input);\n  } catch {\n    return 0n;\n  }\n}\n","export const WORKSPACE_BROWSER_PREVIEW_EXTENSIONS = [\".htm\", \".html\", \".pdf\"] as const;\n\nexport const WORKSPACE_IMAGE_PREVIEW_EXTENSIONS = [\n  \".avif\",\n  \".gif\",\n  \".ico\",\n  \".jpeg\",\n  \".jpg\",\n  \".png\",\n  \".svg\",\n  \".webp\",\n] as const;\n\nfunction hasPreviewExtension(path: string, extensions: ReadonlyArray<string>): boolean {\n  const pathWithoutQuery = path.split(/[?#]/, 1)[0]?.toLowerCase() ?? \"\";\n  return extensions.some((extension) => pathWithoutQuery.endsWith(extension));\n}\n\nexport function isWorkspaceBrowserPreviewPath(path: string): boolean {\n  return hasPreviewExtension(path, WORKSPACE_BROWSER_PREVIEW_EXTENSIONS);\n}\n\nexport function isWorkspaceImagePreviewPath(path: string): boolean {\n  return hasPreviewExtension(path, WORKSPACE_IMAGE_PREVIEW_EXTENSIONS);\n}\n\nexport function isWorkspacePreviewEntryPath(path: string): boolean {\n  return isWorkspaceBrowserPreviewPath(path) || isWorkspaceImagePreviewPath(path);\n}\n","export const PROJECT_FAVICON_FALLBACK_MARKER = \"project-favicon-missing\";\n\nexport function getProjectFaviconCacheKey(\n  environmentId: string,\n  workspaceRoot: string,\n  url: string,\n) {\n  let revision = url;\n\n  try {\n    const pathname = new URL(url, \"https://t3.invalid\").pathname;\n    revision = pathname.slice(pathname.lastIndexOf(\"/\") + 1);\n  } catch {\n    // Keep the full value as a safe fallback for malformed URLs.\n  }\n\n  return JSON.stringify([environmentId, workspaceRoot, revision]);\n}\n\nexport function isProjectFaviconFallbackUrl(url: string | null | undefined): boolean {\n  if (!url) return false;\n\n  try {\n    const pathname = new URL(url, \"https://t3.invalid\").pathname;\n    return pathname.slice(pathname.lastIndexOf(\"/\") + 1) === PROJECT_FAVICON_FALLBACK_MARKER;\n  } catch {\n    return false;\n  }\n}\n","import * as Schema from \"effect/Schema\";\n\nimport { T3ProjectFile, SYNAPTIC_PROJECT_FILE_SCHEMA_URL } from \"@t3tools/contracts\";\n\nimport { fromLenientJson } from \"./schemaJson.ts\";\n\n/**\n * Codec between the raw `synaptic.json` file contents (lenient JSONC string)\n * and the decoded {@link T3ProjectFile}.\n */\nexport const T3ProjectFileFromJson = fromLenientJson(T3ProjectFile);\n\n/**\n * Build the publishable JSON Schema document for `synaptic.json` (draft 2020-12).\n *\n * Served from the marketing site at {@link SYNAPTIC_PROJECT_FILE_SCHEMA_URL} so\n * editors get LSP support via a `$schema` reference.\n */\nexport function buildT3ProjectFileJsonSchema(): Record<string, unknown> {\n  const document = Schema.toJsonSchemaDocument(T3ProjectFile);\n  const jsonSchema: Record<string, unknown> = {\n    $schema: \"https://json-schema.org/draft/2020-12/schema\",\n    $id: SYNAPTIC_PROJECT_FILE_SCHEMA_URL,\n    ...document.schema,\n  };\n  if (document.definitions && Object.keys(document.definitions).length > 0) {\n    jsonSchema.$defs = document.definitions;\n  }\n  return jsonSchema;\n}\n","/**\n * T3ProjectFileLoader - Effect service that loads the checked-in `synaptic.json`\n * project file from a workspace root.\n *\n * Loading is best-effort: a missing file resolves to `Option.none`, and\n * unreadable or invalid files are logged and treated as absent so callers\n * can fall back to their defaults.\n *\n * @module T3ProjectFileLoader\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport { SYNAPTIC_PROJECT_FILE_NAME, type T3ProjectFile } from \"@t3tools/contracts\";\nimport { T3ProjectFileFromJson } from \"@t3tools/shared/t3ProjectFile\";\n\nconst decodeT3ProjectFileJson = Schema.decodeEffect(T3ProjectFileFromJson);\n\nexport class T3ProjectFileLoadError extends Schema.TaggedErrorClass<T3ProjectFileLoadError>()(\n  \"T3ProjectFileLoadError\",\n  {\n    operation: Schema.Literals([\"read\", \"decode\"]),\n    workspaceRoot: Schema.String,\n    filePath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to ${this.operation} ${SYNAPTIC_PROJECT_FILE_NAME} at ${this.filePath}.`;\n  }\n}\n\n/** Service tag for synaptic.json project file loading. */\nexport class T3ProjectFileLoader extends Context.Service<\n  T3ProjectFileLoader,\n  {\n    /**\n     * Load and decode `synaptic.json` at the workspace root.\n     *\n     * Never fails: missing, unreadable, or invalid files resolve to\n     * `Option.none` (invalid files are logged as warnings).\n     */\n    readonly load: (workspaceRoot: string) => Effect.Effect<Option.Option<T3ProjectFile>>;\n  }\n>()(\"t3/project/T3ProjectFileLoader\") {}\n\nconst logT3ProjectFileLoadError = (error: T3ProjectFileLoadError) =>\n  Effect.logWarning(error).pipe(\n    Effect.annotateLogs({\n      operation: error.operation,\n      workspaceRoot: error.workspaceRoot,\n      filePath: error.filePath,\n      errorTag: error._tag,\n    }),\n  );\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const load: T3ProjectFileLoader[\"Service\"][\"load\"] = Effect.fn(\"T3ProjectFileLoader.load\")(\n    function* (workspaceRoot) {\n      const filePath = path.join(workspaceRoot, SYNAPTIC_PROJECT_FILE_NAME);\n      const raw = yield* fileSystem.readFileString(filePath).pipe(\n        Effect.map(Option.some),\n        Effect.catchTags({\n          PlatformError: (error) =>\n            error.reason._tag === \"NotFound\"\n              ? Effect.succeed(Option.none<string>())\n              : logT3ProjectFileLoadError(\n                  new T3ProjectFileLoadError({\n                    operation: \"read\",\n                    workspaceRoot,\n                    filePath,\n                    cause: error,\n                  }),\n                ).pipe(Effect.as(Option.none<string>())),\n        }),\n      );\n      if (Option.isNone(raw)) {\n        return Option.none<T3ProjectFile>();\n      }\n      return yield* decodeT3ProjectFileJson(raw.value).pipe(\n        Effect.map(Option.some),\n        Effect.catchTags({\n          SchemaError: (error) =>\n            logT3ProjectFileLoadError(\n              new T3ProjectFileLoadError({\n                operation: \"decode\",\n                workspaceRoot,\n                filePath,\n                cause: error,\n              }),\n            ).pipe(Effect.as(Option.none<T3ProjectFile>())),\n        }),\n      );\n    },\n  );\n\n  return T3ProjectFileLoader.of({ load });\n});\n\nexport const layer = Layer.effect(T3ProjectFileLoader, make);\n","/**\n * ProjectFaviconResolver - Effect service contract for project icon discovery.\n *\n * Resolves a representative favicon or app icon file for a workspace by\n * checking common file locations and project source metadata.\n *\n * @module ProjectFaviconResolver\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as WorkspacePaths from \"../workspace/WorkspacePaths.ts\";\nimport * as T3ProjectFileLoader from \"./T3ProjectFileLoader.ts\";\n\n// Well-known favicon paths checked in order.\nconst FAVICON_CANDIDATES = [\n  \"favicon.svg\",\n  \"favicon.ico\",\n  \"favicon.png\",\n  \"public/favicon.svg\",\n  \"public/favicon.ico\",\n  \"public/favicon.png\",\n  \"app/favicon.ico\",\n  \"app/favicon.png\",\n  \"app/icon.svg\",\n  \"app/icon.png\",\n  \"app/icon.ico\",\n  \"src/favicon.ico\",\n  \"src/favicon.svg\",\n  \"src/app/favicon.ico\",\n  \"src/app/icon.svg\",\n  \"src/app/icon.png\",\n  \"assets/icon.svg\",\n  \"assets/icon.png\",\n  \"assets/logo.svg\",\n  \"assets/logo.png\",\n  \".idea/icon.svg\",\n] as const;\n\n// Files that may contain a <link rel=\"icon\"> or icon metadata declaration.\nconst ICON_SOURCE_FILES = [\n  \"index.html\",\n  \"public/index.html\",\n  \"app/routes/__root.tsx\",\n  \"src/routes/__root.tsx\",\n  \"app/root.tsx\",\n  \"src/root.tsx\",\n  \"src/index.html\",\n] as const;\n\n// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.\nconst LINK_ICON_HTML_RE =\n  /<link\\b(?=[^>]*\\brel=[\"'](?:icon|shortcut icon)[\"'])(?=[^>]*\\bhref=[\"']([^\"'?]+))[^>]*>/i;\nconst LINK_ICON_OBJ_RE =\n  /(?=[^}]*\\brel\\s*:\\s*[\"'](?:icon|shortcut icon)[\"'])(?=[^}]*\\bhref\\s*:\\s*[\"']([^\"'?]+))[^}]*/i;\n\nexport class ProjectFaviconResolutionError extends Schema.TaggedErrorClass<ProjectFaviconResolutionError>()(\n  \"ProjectFaviconResolutionError\",\n  {\n    operation: Schema.Literals([\n      \"normalize-workspace\",\n      \"resolve-path\",\n      \"stat-candidate\",\n      \"read-source\",\n    ]),\n    workspaceRoot: Schema.String,\n    relativePath: Schema.optional(Schema.String),\n    absolutePath: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to resolve project favicon during ${this.operation} for workspace ${this.workspaceRoot}.`;\n  }\n}\n\n/** Service tag for project favicon resolution. */\nexport class ProjectFaviconResolver extends Context.Service<\n  ProjectFaviconResolver,\n  {\n    /**\n     * Resolve a favicon or icon file path for the provided workspace root.\n     *\n     * Returns `null` when no candidate icon file can be found.\n     */\n    readonly resolvePath: (\n      cwd: string,\n    ) => Effect.Effect<string | null, ProjectFaviconResolutionError>;\n  }\n>()(\"t3/project/ProjectFaviconResolver\") {}\n\nfunction extractIconHref(source: string): string | null {\n  const htmlMatch = source.match(LINK_ICON_HTML_RE);\n  if (htmlMatch?.[1]) return htmlMatch[1];\n  const objMatch = source.match(LINK_ICON_OBJ_RE);\n  if (objMatch?.[1]) return objMatch[1];\n  return null;\n}\n\nconst optionOnNotFound = <A, R>(\n  effect: Effect.Effect<A, PlatformError.PlatformError, R>,\n): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>\n  effect.pipe(\n    Effect.map(Option.some),\n    Effect.catchTags({\n      PlatformError: (error) =>\n        error.reason._tag === \"NotFound\" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),\n    }),\n  );\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader;\n\n  const resolveIconHref = (href: string): ReadonlyArray<string> => {\n    const clean = href.replace(/^\\//, \"\");\n    return [path.join(\"public\", clean), clean];\n  };\n\n  const findExistingFile = Effect.fn(\"ProjectFaviconResolver.findExistingFile\")(function* (\n    projectCwd: string,\n    relativeCandidates: ReadonlyArray<string>,\n  ): Effect.fn.Return<string | null, ProjectFaviconResolutionError> {\n    for (const relativePath of relativeCandidates) {\n      const candidate = yield* workspacePaths\n        .resolveRelativePathWithinRoot({\n          workspaceRoot: projectCwd,\n          relativePath,\n        })\n        .pipe(\n          Effect.map(Option.some),\n          Effect.catchTags({\n            WorkspacePathOutsideRootError: () =>\n              Effect.succeed(\n                Option.none<{ readonly absolutePath: string; readonly relativePath: string }>(),\n              ),\n          }),\n        );\n      if (Option.isNone(candidate)) {\n        continue;\n      }\n      const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProjectFaviconResolutionError({\n              operation: \"stat-candidate\",\n              workspaceRoot: projectCwd,\n              relativePath,\n              absolutePath: candidate.value.absolutePath,\n              cause,\n            }),\n        ),\n      );\n      if (Option.isSome(stats) && stats.value.type === \"File\") {\n        return candidate.value.absolutePath;\n      }\n    }\n    return null;\n  });\n\n  const resolvePath: ProjectFaviconResolver[\"Service\"][\"resolvePath\"] = Effect.fn(\n    \"ProjectFaviconResolver.resolvePath\",\n  )(function* (cwd) {\n    const projectCwd = yield* workspacePaths.normalizeWorkspaceRoot(cwd).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProjectFaviconResolutionError({\n            operation: \"normalize-workspace\",\n            workspaceRoot: cwd,\n            cause,\n          }),\n      ),\n    );\n    // A synaptic.json iconPath takes precedence over the well-known locations.\n    const projectFile = yield* projectFileLoader.load(projectCwd);\n    if (Option.isSome(projectFile) && projectFile.value.iconPath !== undefined) {\n      const existing = yield* findExistingFile(projectCwd, [projectFile.value.iconPath]);\n      if (existing) {\n        return existing;\n      }\n    }\n\n    for (const candidate of FAVICON_CANDIDATES) {\n      const existing = yield* findExistingFile(projectCwd, [candidate]);\n      if (existing) {\n        return existing;\n      }\n    }\n\n    for (const sourceFile of ICON_SOURCE_FILES) {\n      const sourcePath = yield* workspacePaths\n        .resolveRelativePathWithinRoot({\n          workspaceRoot: projectCwd,\n          relativePath: sourceFile,\n        })\n        .pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProjectFaviconResolutionError({\n                operation: \"resolve-path\",\n                workspaceRoot: projectCwd,\n                relativePath: sourceFile,\n                cause,\n              }),\n          ),\n        );\n      const source = yield* optionOnNotFound(\n        fileSystem.readFileString(sourcePath.absolutePath),\n      ).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProjectFaviconResolutionError({\n              operation: \"read-source\",\n              workspaceRoot: projectCwd,\n              relativePath: sourceFile,\n              absolutePath: sourcePath.absolutePath,\n              cause,\n            }),\n        ),\n      );\n      if (Option.isNone(source)) {\n        continue;\n      }\n      const href = extractIconHref(source.value);\n      if (!href) {\n        continue;\n      }\n      const existing = yield* findExistingFile(projectCwd, resolveIconHref(href));\n      if (existing) {\n        return existing;\n      }\n    }\n\n    return null;\n  });\n\n  return ProjectFaviconResolver.of({ resolvePath });\n});\n\nexport const layer = Layer.effect(ProjectFaviconResolver, make);\n","import type { AssetResource } from \"@t3tools/contracts\";\nimport {\n  AssetAttachmentNotFoundError,\n  AssetPreviewTypeValidationError,\n  AssetProjectFaviconInspectionError,\n  AssetProjectFaviconNotFoundError,\n  AssetProjectFaviconResolutionError,\n  AssetSigningKeyLoadError,\n  AssetWorkspaceAssetInspectionError,\n  AssetWorkspaceAssetNotFoundError,\n  AssetWorkspaceContextNotFoundError,\n  AssetWorkspacePathValidationError,\n  AssetWorkspaceResolutionError,\n  AssetWorkspaceRootNormalizationError,\n} from \"@t3tools/contracts\";\nimport {\n  isWorkspaceImagePreviewPath,\n  isWorkspacePreviewEntryPath,\n  WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,\n  WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,\n} from \"@t3tools/shared/filePreview\";\nimport { PROJECT_FAVICON_FALLBACK_MARKER } from \"@t3tools/shared/projectFavicon\";\nimport * as Clock from \"effect/Clock\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\n\nimport {\n  base64UrlDecodeUtf8,\n  base64UrlEncode,\n  signPayload,\n  timingSafeEqualBase64Url,\n} from \"../auth/utils.ts\";\nimport * as ServerSecretStore from \"../auth/ServerSecretStore.ts\";\nimport { resolveAttachmentPathById } from \"../attachmentStore.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport * as ProjectFaviconResolver from \"../project/ProjectFaviconResolver.ts\";\nimport * as WorkspacePaths from \"../workspace/WorkspacePaths.ts\";\n\nexport const ASSET_ROUTE_PREFIX = \"/api/assets\";\n\nconst SIGNING_SECRET_NAME = \"asset-access-signing-key\";\nconst ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;\nconst PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000;\nconst PROJECT_FAVICON_VERSION_PREFIX = \"v\";\nconst PREVIEW_ASSET_EXTENSIONS = new Set([\n  ...WORKSPACE_BROWSER_PREVIEW_EXTENSIONS,\n  ...WORKSPACE_IMAGE_PREVIEW_EXTENSIONS,\n  \".css\",\n  \".js\",\n  \".mjs\",\n  \".otf\",\n  \".ttf\",\n  \".woff\",\n  \".woff2\",\n]);\n\nconst AssetClaimsSchema = Schema.Union([\n  Schema.Struct({\n    version: Schema.Literal(1),\n    kind: Schema.Literal(\"workspace-file\"),\n    workspaceRoot: Schema.String,\n    baseRelativePath: Schema.String,\n    expiresAt: Schema.Number,\n  }),\n  Schema.Struct({\n    version: Schema.Literal(1),\n    kind: Schema.Literal(\"workspace-file-exact\"),\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    expiresAt: Schema.Number,\n  }),\n  Schema.Struct({\n    version: Schema.Literal(1),\n    kind: Schema.Literal(\"attachment\"),\n    attachmentId: Schema.String,\n    expiresAt: Schema.Number,\n  }),\n  Schema.Struct({\n    version: Schema.Literal(1),\n    kind: Schema.Literal(\"project-favicon\"),\n    workspaceRoot: Schema.String,\n    relativePath: Schema.NullOr(Schema.String),\n    expiresAt: Schema.Number,\n  }),\n]);\ntype AssetClaims = typeof AssetClaimsSchema.Type;\n\nconst AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);\nconst decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);\nconst encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);\n\nexport type ResolvedAsset = { readonly kind: \"file\"; readonly path: string };\n\nfunction decodeClaims(encodedPayload: string): AssetClaims | null {\n  try {\n    return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));\n  } catch {\n    return null;\n  }\n}\n\nfunction decodeRelativePath(value: string): string | null {\n  try {\n    return decodeURIComponent(value);\n  } catch {\n    return null;\n  }\n}\n\nconst optionOnNotFound = <A, R>(\n  effect: Effect.Effect<A, PlatformError.PlatformError, R>,\n): Effect.Effect<Option.Option<A>, PlatformError.PlatformError, R> =>\n  effect.pipe(\n    Effect.map(Option.some),\n    Effect.catchTags({\n      PlatformError: (error) =>\n        error.reason._tag === \"NotFound\" ? Effect.succeed(Option.none<A>()) : Effect.fail(error),\n    }),\n  );\n\nconst resolveCanonicalWorkspaceFile = Effect.fn(\"AssetAccess.resolveCanonicalWorkspaceFile\")(\n  function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {\n    const fileSystem = yield* FileSystem.FileSystem;\n    const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n    const resolved = yield* workspacePaths.resolveRelativePathWithinRoot(input).pipe(\n      Effect.map(Option.some),\n      Effect.catchTags({\n        WorkspacePathOutsideRootError: () => Effect.succeed(Option.none()),\n      }),\n    );\n    if (Option.isNone(resolved)) return null;\n\n    const [canonicalRoot, canonicalFile] = yield* Effect.all([\n      optionOnNotFound(fileSystem.realPath(input.workspaceRoot)),\n      optionOnNotFound(fileSystem.realPath(resolved.value.absolutePath)),\n    ]);\n    if (Option.isNone(canonicalRoot) || Option.isNone(canonicalFile)) return null;\n\n    const path = yield* Path.Path;\n    const relative = path.relative(canonicalRoot.value, canonicalFile.value);\n    if (relative === \"\" || relative.startsWith(\"..\") || path.isAbsolute(relative)) return null;\n\n    const info = yield* optionOnNotFound(fileSystem.stat(canonicalFile.value));\n    return Option.isSome(info) && info.value.type === \"File\" ? canonicalFile.value : null;\n  },\n);\n\nconst resolveCanonicalWorkspaceFileForRequest = (input: {\n  readonly workspaceRoot: string;\n  readonly relativePath: string;\n}) =>\n  resolveCanonicalWorkspaceFile(input).pipe(\n    Effect.tapError((cause) =>\n      Effect.logError(\"Failed to resolve canonical asset path.\", {\n        workspaceRoot: input.workspaceRoot,\n        relativePath: input.relativePath,\n        cause,\n      }),\n    ),\n    Effect.orElseSucceed(() => null),\n  );\n\nexport const issueAssetUrl = Effect.fn(\"AssetAccess.issueAssetUrl\")(function* (input: {\n  readonly resource: AssetResource;\n  readonly workspaceRoot?: string;\n}) {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;\n  let claims: AssetClaims;\n  let fileName: string;\n\n  switch (input.resource._tag) {\n    case \"workspace-file\": {\n      if (!input.workspaceRoot) {\n        return yield* new AssetWorkspaceContextNotFoundError({\n          resource: input.resource,\n        });\n      }\n      const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.workspaceRoot).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetWorkspaceRootNormalizationError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      const relativePath = path.isAbsolute(input.resource.path)\n        ? path.relative(workspaceRoot, input.resource.path)\n        : input.resource.path;\n      const resolved = yield* workspacePaths\n        .resolveRelativePathWithinRoot({ workspaceRoot, relativePath })\n        .pipe(\n          Effect.mapError(\n            (cause) =>\n              new AssetWorkspacePathValidationError({\n                resource: input.resource,\n                cause,\n              }),\n          ),\n        );\n      if (!isWorkspacePreviewEntryPath(resolved.relativePath)) {\n        return yield* new AssetPreviewTypeValidationError({\n          resource: input.resource,\n        });\n      }\n      const canonicalFile = yield* resolveCanonicalWorkspaceFile({\n        workspaceRoot,\n        relativePath: resolved.relativePath,\n      }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetWorkspaceAssetInspectionError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      if (!canonicalFile) {\n        return yield* new AssetWorkspaceAssetNotFoundError({\n          resource: input.resource,\n        });\n      }\n      const canonicalWorkspaceRoot = yield* fileSystem.realPath(workspaceRoot).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetWorkspaceResolutionError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      claims = isWorkspaceImagePreviewPath(resolved.relativePath)\n        ? {\n            version: 1,\n            kind: \"workspace-file-exact\",\n            workspaceRoot: canonicalWorkspaceRoot,\n            relativePath: resolved.relativePath,\n            expiresAt,\n          }\n        : {\n            version: 1,\n            kind: \"workspace-file\",\n            workspaceRoot: canonicalWorkspaceRoot,\n            baseRelativePath: path.dirname(resolved.relativePath),\n            expiresAt,\n          };\n      fileName = path.basename(resolved.relativePath);\n      break;\n    }\n    case \"attachment\": {\n      const config = yield* ServerConfig.ServerConfig;\n      const attachmentPath = resolveAttachmentPathById({\n        attachmentsDir: config.attachmentsDir,\n        attachmentId: input.resource.attachmentId,\n      });\n      if (!attachmentPath) {\n        return yield* new AssetAttachmentNotFoundError({\n          resource: input.resource,\n        });\n      }\n      claims = {\n        version: 1,\n        kind: \"attachment\",\n        attachmentId: input.resource.attachmentId,\n        expiresAt,\n      };\n      fileName = path.basename(attachmentPath);\n      break;\n    }\n    case \"project-favicon\": {\n      const workspaceRoot = yield* workspacePaths.normalizeWorkspaceRoot(input.resource.cwd).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetWorkspaceRootNormalizationError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;\n      const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(\n        Effect.mapError(\n          (cause) =>\n            new AssetProjectFaviconResolutionError({\n              resource: input.resource,\n              cause,\n            }),\n        ),\n      );\n      const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;\n      const canonicalFaviconPath = relativePath\n        ? yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(\n            Effect.mapError(\n              (cause) =>\n                new AssetProjectFaviconInspectionError({\n                  resource: input.resource,\n                  cause,\n                }),\n            ),\n          )\n        : null;\n      if (relativePath && !canonicalFaviconPath) {\n        return yield* new AssetProjectFaviconNotFoundError({\n          resource: input.resource,\n        });\n      }\n      claims = {\n        version: 1,\n        kind: \"project-favicon\",\n        workspaceRoot: yield* fileSystem.realPath(workspaceRoot).pipe(\n          Effect.mapError(\n            (cause) =>\n              new AssetWorkspaceResolutionError({\n                resource: input.resource,\n                cause,\n              }),\n          ),\n        ),\n        relativePath,\n        expiresAt,\n      };\n      if (relativePath && canonicalFaviconPath) {\n        const crypto = yield* Crypto.Crypto;\n        const faviconBytes = yield* fileSystem.readFile(canonicalFaviconPath).pipe(\n          Effect.mapError(\n            (cause) =>\n              new AssetProjectFaviconInspectionError({\n                resource: input.resource,\n                cause,\n              }),\n          ),\n        );\n        const revision = yield* crypto.digest(\"SHA-256\", faviconBytes).pipe(\n          Effect.map(Encoding.encodeHex),\n          Effect.mapError(\n            (cause) =>\n              new AssetProjectFaviconInspectionError({\n                resource: input.resource,\n                cause,\n              }),\n          ),\n        );\n        fileName = `${PROJECT_FAVICON_VERSION_PREFIX}${revision}-${path.basename(relativePath)}`;\n      } else {\n        fileName = PROJECT_FAVICON_FALLBACK_MARKER;\n      }\n      break;\n    }\n  }\n\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(\n    Effect.mapError(\n      (cause) =>\n        new AssetSigningKeyLoadError({\n          resource: input.resource,\n          cause,\n        }),\n    ),\n  );\n  if (claims.kind === \"project-favicon\") {\n    const issuedAt = yield* Clock.currentTimeMillis;\n    expiresAt =\n      (Math.floor(issuedAt / PROJECT_FAVICON_TOKEN_BUCKET_MS) + 2) *\n      PROJECT_FAVICON_TOKEN_BUCKET_MS;\n    claims = { ...claims, expiresAt };\n  }\n  const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));\n  const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;\n  return {\n    relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,\n    expiresAt,\n  };\n});\n\nexport const resolveAsset = Effect.fn(\"AssetAccess.resolveAsset\")(function* (\n  token: string,\n  relativePath: string,\n) {\n  const [encodedPayload, signature] = token.split(\".\");\n  if (!encodedPayload || !signature) return null;\n\n  const secretStore = yield* ServerSecretStore.ServerSecretStore;\n  const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(\n    Effect.tapError((cause) => Effect.logError(\"Failed to load the asset signing key.\", { cause })),\n    Effect.orElseSucceed(() => null),\n  );\n  if (!signingSecret) return null;\n  if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;\n\n  const claims = decodeClaims(encodedPayload);\n  if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;\n\n  if (claims.kind === \"attachment\") {\n    const config = yield* ServerConfig.ServerConfig;\n    const attachmentPath = resolveAttachmentPathById({\n      attachmentsDir: config.attachmentsDir,\n      attachmentId: claims.attachmentId,\n    });\n    if (!attachmentPath) return null;\n    const fileSystem = yield* FileSystem.FileSystem;\n    const info = yield* optionOnNotFound(fileSystem.stat(attachmentPath)).pipe(\n      Effect.tapError((cause) =>\n        Effect.logError(\"Failed to inspect attachment asset.\", {\n          attachmentId: claims.attachmentId,\n          path: attachmentPath,\n          cause,\n        }),\n      ),\n      Effect.orElseSucceed(() => Option.none()),\n    );\n    return Option.isSome(info) && info.value.type === \"File\"\n      ? ({ kind: \"file\", path: attachmentPath } satisfies ResolvedAsset)\n      : null;\n  }\n\n  if (claims.kind === \"project-favicon\") {\n    if (claims.relativePath === null) return null;\n    const faviconPath = yield* resolveCanonicalWorkspaceFileForRequest({\n      workspaceRoot: claims.workspaceRoot,\n      relativePath: claims.relativePath,\n    });\n    return faviconPath ? ({ kind: \"file\", path: faviconPath } satisfies ResolvedAsset) : null;\n  }\n\n  const decodedPath = decodeRelativePath(relativePath);\n  if (decodedPath === null) return null;\n  const path = yield* Path.Path;\n  if (claims.kind === \"workspace-file-exact\") {\n    if (decodedPath !== path.basename(claims.relativePath)) return null;\n    const exactWorkspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({\n      workspaceRoot: claims.workspaceRoot,\n      relativePath: claims.relativePath,\n    });\n    return exactWorkspaceFile\n      ? ({ kind: \"file\", path: exactWorkspaceFile } satisfies ResolvedAsset)\n      : null;\n  }\n  const segments = decodedPath.split(/[\\\\/]/);\n  if (\n    decodedPath.length === 0 ||\n    decodedPath.includes(\"\\0\") ||\n    segments.some((segment) => segment === \".\" || segment === \"..\" || segment.startsWith(\".\")) ||\n    !PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())\n  ) {\n    return null;\n  }\n  const joinedRelativePath =\n    claims.baseRelativePath === \".\" ? decodedPath : path.join(claims.baseRelativePath, decodedPath);\n  const workspaceFile = yield* resolveCanonicalWorkspaceFileForRequest({\n    workspaceRoot: claims.workspaceRoot,\n    relativePath: joinedRelativePath,\n  });\n  return workspaceFile ? ({ kind: \"file\", path: workspaceFile } satisfies ResolvedAsset) : null;\n});\n","import type { TraceRecord, TraceSink } from \"@t3tools/shared/observability\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nexport class BrowserTraceCollector extends Context.Service<\n  BrowserTraceCollector,\n  {\n    readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;\n  }\n>()(\"t3/observability/BrowserTraceCollector\") {}\n\nexport const make = (sink: TraceSink): BrowserTraceCollector[\"Service\"] =>\n  BrowserTraceCollector.of({\n    record: (records) =>\n      Effect.sync(() => {\n        for (const record of records) {\n          sink.push(record);\n        }\n      }),\n  });\n\nexport const layer = (sink: TraceSink) => Layer.succeed(BrowserTraceCollector, make(sink));\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Tracer from \"effect/Tracer\";\nimport type { HttpClient } from \"effect/unstable/http\";\nimport { OtlpSerialization, OtlpTracer } from \"effect/unstable/observability\";\n\nexport interface RelayClientTracingConfig {\n  readonly tracesUrl: string;\n  readonly tracesDataset: string;\n  readonly tracesToken: string;\n}\n\nexport interface RelayClientTracingResource {\n  readonly serviceName: string;\n  readonly serviceVersion?: string;\n  readonly runtime: string;\n  readonly client: string;\n  readonly component?: string;\n}\n\nexport class RelayClientTracer extends Context.Reference(\n  \"@t3tools/shared/relayTracing/RelayClientTracer\",\n  {\n    defaultValue: () => Option.none<Tracer.Tracer>(),\n  },\n) {}\n\nexport const withRelayClientTracing = <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> =>\n  RelayClientTracer.pipe(\n    Effect.flatMap(\n      Option.match({\n        onNone: () => effect,\n        onSome: (tracer) => effect.pipe(Effect.provideService(Tracer.Tracer, tracer)),\n      }),\n    ),\n  );\n\nfunction cleanTraceStack(error: Error): string {\n  const stack = error.stack ?? `${error.name}: ${error.message}`;\n  const lines = stack.split(\"\\n\");\n  const effectFrameIndex = lines.findIndex(\n    (line, index) => index > 0 && /(?:Generator\\.next|~effect\\/Effect)/.test(line),\n  );\n  return effectFrameIndex < 0 ? stack : lines.slice(0, effectFrameIndex).join(\"\\n\");\n}\n\nfunction traceSafeError(value: unknown, seen = new WeakSet<object>()): Error {\n  const message =\n    value instanceof Error\n      ? value.message\n      : typeof value === \"object\" &&\n          value !== null &&\n          \"message\" in value &&\n          typeof value.message === \"string\"\n        ? value.message\n        : String(value);\n\n  let cause: Error | undefined;\n  if (typeof value === \"object\" && value !== null && !seen.has(value)) {\n    seen.add(value);\n    if (\"cause\" in value && value.cause !== undefined) {\n      cause = traceSafeError(value.cause, seen);\n    }\n  }\n\n  const error = new Error(message, cause ? { cause } : undefined);\n  if (value instanceof Error) {\n    error.name = value.name;\n    error.stack = cleanTraceStack(value);\n  } else if (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"name\" in value &&\n    typeof value.name === \"string\"\n  ) {\n    error.name = value.name;\n  }\n  if (cause) {\n    error.stack = `${error.stack ?? `${error.name}: ${error.message}`}\\nCaused by: ${cause.stack ?? `${cause.name}: ${cause.message}`}`;\n  }\n  return error;\n}\n\nfunction traceSafeExit(exit: Exit.Exit<unknown, unknown>): Exit.Exit<unknown, unknown> {\n  if (Exit.isSuccess(exit)) {\n    return exit;\n  }\n  return Exit.failCause(\n    Cause.fromReasons(\n      exit.cause.reasons.map((reason) => {\n        if (Cause.isFailReason(reason)) {\n          return Cause.makeFailReason(traceSafeError(reason.error));\n        }\n        if (Cause.isDieReason(reason)) {\n          return Cause.makeDieReason(traceSafeError(reason.defect));\n        }\n        return reason;\n      }),\n    ),\n  );\n}\n\nfunction nonInterferingTracer(delegate: Tracer.Tracer): Tracer.Tracer {\n  return Tracer.make({\n    span(options) {\n      const span = delegate.span(options);\n      const end = span.end.bind(span);\n      span.end = (endTime, exit) => {\n        try {\n          end(endTime, traceSafeExit(exit));\n        } catch {\n          // Telemetry is best-effort and must never change application behavior.\n        }\n      };\n      return span;\n    },\n    ...(delegate.context ? { context: delegate.context } : {}),\n  });\n}\n\nexport function makeRelayClientTracingLayer(\n  config: RelayClientTracingConfig | null,\n  resource: RelayClientTracingResource,\n): Layer.Layer<never, never, HttpClient.HttpClient> {\n  if (config === null) {\n    return Layer.succeed(RelayClientTracer, Option.none());\n  }\n\n  const tracerLayer = OtlpTracer.layer({\n    url: config.tracesUrl,\n    headers: {\n      Authorization: `Bearer ${config.tracesToken}`,\n      \"X-Axiom-Dataset\": config.tracesDataset,\n    },\n    resource: {\n      serviceName: resource.serviceName,\n      serviceVersion: resource.serviceVersion,\n      attributes: {\n        \"service.runtime\": resource.runtime,\n        \"service.component\": resource.component ?? \"relay-client\",\n        \"t3.client.surface\": resource.client,\n      },\n    },\n  }).pipe(Layer.provide(OtlpSerialization.layerJson));\n\n  return Layer.effect(\n    RelayClientTracer,\n    Tracer.Tracer.pipe(Effect.map(nonInterferingTracer), Effect.map(Option.some)),\n  ).pipe(Layer.provide(tracerLayer));\n}\n","import { withRelayClientTracing } from \"@t3tools/shared/relayTracing\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport { HttpServerRequest, HttpTraceContext } from \"effect/unstable/http\";\n\nexport const traceRelayRequest = <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R> => effect.pipe(withRelayClientTracing);\n\nexport const traceAuthenticatedRelayRequest = <A, E, R>(\n  effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E, R | HttpServerRequest.HttpServerRequest> =>\n  HttpServerRequest.HttpServerRequest.pipe(\n    Effect.flatMap((request) =>\n      Option.match(HttpTraceContext.fromHeaders(request.headers), {\n        onNone: () => effect,\n        onSome: (parent) => effect.pipe(Effect.withParentSpan(parent)),\n      }),\n    ),\n    withRelayClientTracing,\n  );\n","import {\n  AuthAccessReadScope,\n  AuthAccessWriteScope,\n  AuthStandardClientScopes,\n  AuthOrchestrationOperateScope,\n  AuthOrchestrationReadScope,\n  AuthRelayReadScope,\n  AuthRelayWriteScope,\n  AuthReviewWriteScope,\n  AuthTerminalOperateScope,\n  EnvironmentAuthInvalidError,\n  type EnvironmentAuthInvalidReason,\n  EnvironmentHttpApi,\n  EnvironmentInternalError,\n  type EnvironmentInternalErrorReason,\n  EnvironmentOperationForbiddenError,\n  EnvironmentRequestInvalidError,\n  type EnvironmentRequestInvalidReason,\n  EnvironmentResourceNotFoundError,\n  type EnvironmentResourceNotFoundReason,\n  EnvironmentScopeRequiredError,\n  EnvironmentAuthenticatedAuth,\n  EnvironmentAuthenticatedPrincipal,\n} from \"@t3tools/contracts\";\nimport type { AuthEnvironmentScope } from \"@t3tools/contracts\";\nimport { parseAllowedOAuthScope } from \"@t3tools/shared/oauthScope\";\nimport { causeErrorTag } from \"@t3tools/shared/observability\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport { identity } from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as Cookies from \"effect/unstable/http/Cookies\";\nimport * as HttpEffect from \"effect/unstable/http/HttpEffect\";\nimport { HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\n\nimport * as EnvironmentAuth from \"./EnvironmentAuth.ts\";\nimport * as SessionStore from \"./SessionStore.ts\";\nimport { traceAuthenticatedRelayRequest, traceRelayRequest } from \"../cloud/traceRelayRequest.ts\";\nimport { deriveAuthClientMetadata } from \"./utils.ts\";\nimport { verifyRequestDpopProof } from \"./dpop.ts\";\n\nconst CREDENTIAL_RESPONSE_HEADERS = {\n  \"cache-control\": \"no-store\",\n  pragma: \"no-cache\",\n} as const;\n\nconst appendCredentialResponseHeaders = HttpEffect.appendPreResponseHandler((_request, response) =>\n  Effect.succeed(HttpServerResponse.setHeaders(response, CREDENTIAL_RESPONSE_HEADERS)),\n);\n\nconst appendDpopChallengeHeader = HttpEffect.appendPreResponseHandler((_request, response) =>\n  Effect.succeed(HttpServerResponse.setHeader(response, \"www-authenticate\", \"DPoP\")),\n);\n\nconst appendDpopChallengeOnUnauthorized = (error: EnvironmentAuthInvalidError) =>\n  Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const usesDpop =\n      (request.originalUrl.startsWith(\"/oauth/token\") && request.headers.dpop !== undefined) ||\n      request.headers.authorization?.startsWith(\"DPoP \") === true;\n    if (usesDpop) {\n      yield* appendDpopChallengeHeader;\n    }\n    return yield* error;\n  });\n\nexport const currentEnvironmentTraceId = Effect.currentParentSpan.pipe(\n  Effect.map((span) => span.traceId),\n  Effect.orElseSucceed(() => \"unavailable\"),\n);\n\nexport function annotateEnvironmentRequest(endpoint: string) {\n  return Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const url = HttpServerRequest.toURL(request);\n    const traceId = yield* currentEnvironmentTraceId;\n\n    yield* Effect.addFinalizer((exit) =>\n      exit._tag === \"Failure\"\n        ? Effect.logWarning(\"environment api request failed\", {\n            endpoint,\n            traceId,\n            errorTag: causeErrorTag(exit.cause),\n            cause: exit.cause,\n          })\n        : Effect.void,\n    );\n    yield* Effect.annotateLogsScoped({ \"environment.endpoint\": endpoint, traceId });\n    yield* Effect.annotateCurrentSpan({\n      \"environment.endpoint\": endpoint,\n      \"http.request.method\": request.method,\n      \"url.path\": url._tag === \"Some\" ? url.value.pathname : \"unknown\",\n    });\n  });\n}\n\nexport function failEnvironmentAuthInvalid(reason: EnvironmentAuthInvalidReason) {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(new EnvironmentAuthInvalidError({ code: \"auth_invalid\", reason, traceId })),\n    ),\n  );\n}\n\nexport function failEnvironmentInvalidRequest(reason: EnvironmentRequestInvalidReason) {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(new EnvironmentRequestInvalidError({ code: \"invalid_request\", reason, traceId })),\n    ),\n  );\n}\n\nexport function failEnvironmentScopeRequired(requiredScope: AuthEnvironmentScope) {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(\n        new EnvironmentScopeRequiredError({\n          code: \"insufficient_scope\",\n          requiredScope,\n          traceId,\n        }),\n      ),\n    ),\n  );\n}\n\nfunction failEnvironmentOperationForbidden(reason: \"current_session_revoke_not_allowed\") {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(\n        new EnvironmentOperationForbiddenError({\n          code: \"operation_forbidden\",\n          reason,\n          traceId,\n        }),\n      ),\n    ),\n  );\n}\n\nexport function failEnvironmentNotFound(reason: EnvironmentResourceNotFoundReason) {\n  return currentEnvironmentTraceId.pipe(\n    Effect.flatMap((traceId) =>\n      Effect.fail(new EnvironmentResourceNotFoundError({ code: \"not_found\", reason, traceId })),\n    ),\n  );\n}\n\nexport function failEnvironmentInternal(reason: EnvironmentInternalErrorReason, error?: unknown) {\n  return Effect.gen(function* () {\n    const traceId = yield* currentEnvironmentTraceId;\n    if (error !== undefined) {\n      yield* Effect.logError(\"environment api operation failed\", {\n        reason,\n        traceId,\n        cause: error,\n      });\n    }\n    return yield* new EnvironmentInternalError({ code: \"internal_error\", reason, traceId });\n  });\n}\n\nexport const requireEnvironmentScope = Effect.fn(\"environment.auth.requireScope\")(function* (\n  scope: AuthEnvironmentScope,\n) {\n  const session = yield* EnvironmentAuthenticatedPrincipal;\n  if (!session.scopes.has(scope)) {\n    return yield* failEnvironmentScopeRequired(scope);\n  }\n  return session;\n});\n\nexport const environmentAuthenticatedAuthLayer = Layer.effect(\n  EnvironmentAuthenticatedAuth,\n  Effect.gen(function* () {\n    const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    return (httpEffect) =>\n      Effect.gen(function* () {\n        const request = yield* HttpServerRequest.HttpServerRequest;\n        const session = yield* serverAuth.authenticateHttpRequest(request).pipe(\n          Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n            failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"internal_error\", error),\n          ),\n        );\n        return yield* httpEffect.pipe(\n          Effect.provideService(EnvironmentAuthenticatedPrincipal, {\n            ...session,\n            scopes: new Set(session.scopes),\n          }),\n          session.subject === \"cloud-connect\" ? traceAuthenticatedRelayRequest : identity,\n        );\n      }).pipe(Effect.catchTag(\"EnvironmentAuthInvalidError\", appendDpopChallengeOnUnauthorized));\n  }),\n);\n\nexport const authHttpApiLayer = HttpApiBuilder.group(\n  EnvironmentHttpApi,\n  \"auth\",\n  Effect.fnUntraced(function* (handlers) {\n    const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    const sessions = yield* SessionStore.SessionStore;\n\n    return handlers\n      .handle(\n        \"session\",\n        Effect.fn(\"environment.auth.session\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const request = yield* HttpServerRequest.HttpServerRequest;\n            return yield* serverAuth.getSessionState(request);\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"internal_error\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"browserSession\",\n        Effect.fn(\"environment.auth.browserSession\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const request = yield* HttpServerRequest.HttpServerRequest;\n            const result = yield* serverAuth.createBrowserSession(\n              args.payload.credential,\n              deriveAuthClientMetadata({ request }),\n            );\n            const sessionCookies = yield* Effect.fromResult(\n              Cookies.set(Cookies.empty, sessions.cookieName, result.sessionToken, {\n                expires: DateTime.toDate(result.response.expiresAt),\n                httpOnly: true,\n                path: \"/\",\n                sameSite: \"lax\",\n              }),\n            ).pipe(Effect.catch(() => failEnvironmentInternal(\"browser_session_cookie_failed\")));\n\n            yield* HttpEffect.appendPreResponseHandler((_request, response) =>\n              Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),\n            );\n            yield* appendCredentialResponseHeaders;\n            return result.response;\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n            failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"browser_session_issuance_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"token\",\n        Effect.fn(\"environment.auth.token\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const request = yield* HttpServerRequest.HttpServerRequest;\n            const requestedScopes =\n              args.payload.scope === undefined\n                ? undefined\n                : parseAllowedOAuthScope({\n                    value: args.payload.scope,\n                    allowedScopes: new Set<AuthEnvironmentScope>([\n                      AuthOrchestrationReadScope,\n                      AuthOrchestrationOperateScope,\n                      AuthTerminalOperateScope,\n                      AuthReviewWriteScope,\n                      AuthAccessReadScope,\n                      AuthAccessWriteScope,\n                      AuthRelayReadScope,\n                      AuthRelayWriteScope,\n                    ]),\n                  });\n            if (requestedScopes === null) {\n              return yield* failEnvironmentInvalidRequest(\"invalid_scope\");\n            }\n            const proofKeyThumbprint = args.headers.dpop\n              ? yield* verifyRequestDpopProof({ request }).pipe(\n                  Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, () =>\n                    appendDpopChallengeHeader.pipe(\n                      Effect.andThen(failEnvironmentAuthInvalid(\"invalid_credential\")),\n                    ),\n                  ),\n                  Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n                    failEnvironmentInternal(\"access_token_issuance_failed\", error),\n                  ),\n                )\n              : undefined;\n            yield* appendCredentialResponseHeaders;\n            return yield* serverAuth.exchangeBootstrapCredentialForAccessToken(\n              args.payload.subject_token,\n              requestedScopes,\n              deriveAuthClientMetadata({\n                request,\n                presented: {\n                  ...(args.payload.client_label ? { label: args.payload.client_label } : {}),\n                  ...(args.payload.client_device_type\n                    ? { deviceType: args.payload.client_device_type }\n                    : {}),\n                  ...(args.payload.client_os ? { os: args.payload.client_os } : {}),\n                },\n              }),\n              proofKeyThumbprint ? { proofKeyThumbprint } : undefined,\n            );\n          },\n          traceRelayRequest,\n          Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n            failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInvalidRequestError, (error) =>\n            failEnvironmentInvalidRequest(EnvironmentAuth.serverAuthInvalidRequestReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"access_token_issuance_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"webSocketTicket\",\n        Effect.fn(\"environment.auth.webSocketTicket\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* EnvironmentAuthenticatedPrincipal;\n            yield* appendCredentialResponseHeaders;\n            return yield* serverAuth.issueWebSocketTicket(session);\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"websocket_ticket_issuance_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"pairingCredential\",\n        Effect.fn(\"environment.auth.pairingCredential\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* requireEnvironmentScope(AuthAccessWriteScope);\n            const delegatedScopes = args.payload.scopes ?? AuthStandardClientScopes;\n            if (\n              delegatedScopes.length === 0 ||\n              new Set<AuthEnvironmentScope>(delegatedScopes).size !== delegatedScopes.length\n            ) {\n              return yield* failEnvironmentInvalidRequest(\"invalid_scope\");\n            }\n            for (const delegatedScope of delegatedScopes) {\n              if (!session.scopes.has(delegatedScope)) {\n                return yield* failEnvironmentScopeRequired(delegatedScope);\n              }\n            }\n            return yield* serverAuth.issuePairingCredential(args.payload);\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"pairing_credential_issuance_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"pairingLinks\",\n        Effect.fn(\"environment.auth.pairingLinks\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            yield* requireEnvironmentScope(AuthAccessReadScope);\n            return yield* serverAuth.listPairingLinks();\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"pairing_links_load_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"revokePairingLink\",\n        Effect.fn(\"environment.auth.revokePairingLink\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            yield* requireEnvironmentScope(AuthAccessWriteScope);\n            const revoked = yield* serverAuth.revokePairingLink(args.payload.id);\n            return { revoked };\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"pairing_link_revoke_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"clients\",\n        Effect.fn(\"environment.auth.clients\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* requireEnvironmentScope(AuthAccessReadScope);\n            return yield* serverAuth.listClientSessions(session.sessionId);\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"client_sessions_load_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"revokeClient\",\n        Effect.fn(\"environment.auth.revokeClient\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* requireEnvironmentScope(AuthAccessWriteScope);\n            const revoked = yield* serverAuth.revokeClientSession(\n              session.sessionId,\n              args.payload.sessionId,\n            );\n            return { revoked };\n          },\n          Effect.catchTag(\"ServerAuthForbiddenOperationError\", () =>\n            failEnvironmentOperationForbidden(\"current_session_revoke_not_allowed\"),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"client_session_revoke_failed\", error),\n          ),\n        ),\n      )\n      .handle(\n        \"revokeOtherClients\",\n        Effect.fn(\"environment.auth.revokeOtherClients\")(\n          function* (args) {\n            yield* annotateEnvironmentRequest(args.endpoint.name);\n            const session = yield* requireEnvironmentScope(AuthAccessWriteScope);\n            const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId);\n            return { revokedCount };\n          },\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"client_session_revoke_failed\", error),\n          ),\n        ),\n      );\n  }),\n);\n","export const browserApiCorsAllowedMethods = [\"GET\", \"POST\", \"OPTIONS\"] as const;\nexport const browserApiCorsAllowedHeaders = [\n  \"authorization\",\n  \"b3\",\n  \"traceparent\",\n  \"content-type\",\n  \"dpop\",\n] as const;\n\nexport const browserApiCorsHeaders = {\n  \"access-control-allow-origin\": \"*\",\n  \"access-control-allow-methods\": browserApiCorsAllowedMethods.join(\", \"),\n  \"access-control-allow-headers\": browserApiCorsAllowedHeaders.join(\", \"),\n} as const;\n","import Mime from \"@effect/platform-node/Mime\";\nimport {\n  AuthOrchestrationOperateScope,\n  AuthOrchestrationReadScope,\n  EnvironmentHttpApi,\n} from \"@t3tools/contracts\";\nimport { isDevProxiedPath } from \"@t3tools/shared/devProxy\";\nimport { decodeOtlpTraceRecords } from \"@t3tools/shared/observability\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport { cast } from \"effect/Function\";\nimport {\n  HttpBody,\n  HttpClient,\n  HttpClientResponse,\n  HttpMiddleware,\n  HttpRouter,\n  HttpServerResponse,\n  HttpServerRequest,\n  HttpServerRespondable,\n} from \"effect/unstable/http\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\nimport { OtlpTracer } from \"effect/unstable/observability\";\n\nimport * as ServerConfig from \"./config.ts\";\nimport { ASSET_ROUTE_PREFIX, resolveAsset } from \"./assets/AssetAccess.ts\";\nimport * as BrowserTraceCollector from \"./observability/BrowserTraceCollector.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\nimport { traceRelayRequest } from \"./cloud/traceRelayRequest.ts\";\nimport {\n  annotateEnvironmentRequest,\n  failEnvironmentScopeRequired,\n  failEnvironmentAuthInvalid,\n  failEnvironmentInternal,\n} from \"./auth/http.ts\";\nimport * as ServerEnvironment from \"./environment/ServerEnvironment.ts\";\nimport { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from \"./httpCors.ts\";\n\nconst OTLP_TRACES_PROXY_PATH = \"/api/observability/v1/traces\";\nconst LOOPBACK_HOSTNAMES = new Set([\"127.0.0.1\", \"::1\", \"localhost\"]);\nconst DESKTOP_RENDERER_ORIGINS = [\"synapticcode://app\", \"synapticcode-dev://app\"];\nexport const httpCompressionLayer = HttpRouter.middleware(HttpMiddleware.compression(), {\n  global: true,\n});\n\nexport const browserApiCorsLayer = Layer.unwrap(\n  Effect.gen(function* () {\n    const config = yield* ServerConfig.ServerConfig;\n    const devOrigin = config.devUrl?.origin;\n    // Dev uses credentialed requests from Vite or the Electron custom origin, so both must be\n    // explicit. Packaged desktop omits credentials and uses Effect's default wildcard origin.\n    //\n    // SYNAPTIC_DEV_ALLOWED_ORIGINS covers dev servers reached from a second\n    // origin — a tailnet name, a LAN IP, a phone. Browser dev normally proxies\n    // through Vite and is same-origin (no preflight at all), so this is a\n    // safety net for the desktop renderer and any direct-to-backend caller.\n    return HttpRouter.cors({\n      ...(devOrigin\n        ? {\n            allowedOrigins: [devOrigin, ...DESKTOP_RENDERER_ORIGINS, ...config.devAllowedOrigins],\n            credentials: true,\n          }\n        : {}),\n      allowedMethods: browserApiCorsAllowedMethods,\n      allowedHeaders: browserApiCorsAllowedHeaders,\n      maxAge: 600,\n    });\n  }),\n);\n\nexport function isLoopbackHostname(hostname: string): boolean {\n  const normalizedHostname = hostname\n    .trim()\n    .toLowerCase()\n    .replace(/^\\[(.*)\\]$/, \"$1\");\n  return LOOPBACK_HOSTNAMES.has(normalizedHostname);\n}\n\nexport function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string {\n  const redirectUrl = new URL(devUrl.toString());\n  redirectUrl.pathname = requestUrl.pathname;\n  redirectUrl.search = requestUrl.search;\n  redirectUrl.hash = requestUrl.hash;\n  return redirectUrl.toString();\n}\n\nconst authenticateRawRouteWithScope = (\n  scope: typeof AuthOrchestrationReadScope | typeof AuthOrchestrationOperateScope,\n) =>\n  Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n    const session = yield* serverAuth.authenticateHttpRequest(request).pipe(\n      Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n        failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n      ),\n      Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n        failEnvironmentInternal(\"internal_error\", error),\n      ),\n    );\n    if (!session.scopes.includes(scope)) {\n      return yield* failEnvironmentScopeRequired(scope);\n    }\n  });\n\nexport const serverEnvironmentHttpApiLayer = HttpApiBuilder.group(\n  EnvironmentHttpApi,\n  \"metadata\",\n  Effect.fnUntraced(function* (handlers) {\n    const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;\n    return handlers.handle(\n      \"descriptor\",\n      Effect.fn(\"environment.metadata.descriptor\")(function* (args) {\n        yield* annotateEnvironmentRequest(args.endpoint.name);\n        return yield* serverEnvironment.getDescriptor;\n      }, traceRelayRequest),\n    );\n  }),\n);\n\nclass DecodeOtlpTraceRecordsError extends Data.TaggedError(\"DecodeOtlpTraceRecordsError\")<{\n  readonly cause: unknown;\n  readonly bodyJson: OtlpTracer.TraceData;\n}> {}\n\nexport const otlpTracesProxyRouteLayer = HttpRouter.add(\n  \"POST\",\n  OTLP_TRACES_PROXY_PATH,\n  Effect.gen(function* () {\n    yield* authenticateRawRouteWithScope(AuthOrchestrationOperateScope);\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const config = yield* ServerConfig.ServerConfig;\n    const otlpTracesUrl = config.otlpTracesUrl;\n    const browserTraceCollector = yield* BrowserTraceCollector.BrowserTraceCollector;\n    const httpClient = yield* HttpClient.HttpClient;\n    const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);\n\n    yield* Effect.try({\n      try: () => decodeOtlpTraceRecords(bodyJson),\n      catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),\n    }).pipe(\n      Effect.flatMap((records) => browserTraceCollector.record(records)),\n      Effect.catch((cause) =>\n        Effect.logWarning(\"Failed to decode browser OTLP traces\", {\n          cause,\n          bodyJson,\n        }),\n      ),\n    );\n\n    if (otlpTracesUrl === undefined) {\n      return HttpServerResponse.empty({ status: 204 });\n    }\n\n    return yield* httpClient\n      .post(otlpTracesUrl, {\n        body: HttpBody.jsonUnsafe(bodyJson),\n      })\n      .pipe(\n        Effect.flatMap(HttpClientResponse.filterStatusOk),\n        Effect.as(HttpServerResponse.empty({ status: 204 })),\n        Effect.tapError((cause) =>\n          Effect.logWarning(\"Failed to export browser OTLP traces\", {\n            cause,\n            otlpTracesUrl,\n          }),\n        ),\n        Effect.orElseSucceed(() =>\n          HttpServerResponse.text(\"Trace export failed.\", { status: 502 }),\n        ),\n      );\n  }).pipe(\n    Effect.catchTags({\n      EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,\n      EnvironmentInternalError: HttpServerRespondable.toResponse,\n      EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,\n    }),\n  ),\n);\n\nexport const assetRouteLayer = HttpRouter.add(\n  \"GET\",\n  `${ASSET_ROUTE_PREFIX}/*`,\n  Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const url = HttpServerRequest.toURL(request);\n    if (Option.isNone(url)) {\n      return HttpServerResponse.text(\"Bad Request\", { status: 400 });\n    }\n\n    const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);\n    const separatorIndex = suffix.indexOf(\"/\");\n    if (separatorIndex <= 0) {\n      return HttpServerResponse.text(\"Not Found\", { status: 404 });\n    }\n\n    const asset = yield* resolveAsset(\n      suffix.slice(0, separatorIndex),\n      suffix.slice(separatorIndex + 1),\n    );\n    if (!asset) {\n      return HttpServerResponse.text(\"Not Found\", { status: 404 });\n    }\n    return yield* HttpServerResponse.file(asset.path, {\n      status: 200,\n      headers: {\n        \"Cache-Control\": \"private, max-age=3600\",\n        \"X-Content-Type-Options\": \"nosniff\",\n      },\n    }).pipe(\n      Effect.orElseSucceed(() => HttpServerResponse.text(\"Internal Server Error\", { status: 500 })),\n    );\n  }),\n);\n\nexport const staticAndDevRouteLayer = HttpRouter.add(\n  \"GET\",\n  \"*\",\n  Effect.gen(function* () {\n    const request = yield* HttpServerRequest.HttpServerRequest;\n    const url = HttpServerRequest.toURL(request);\n\n    if (Option.isNone(url)) {\n      return HttpServerResponse.text(\"Bad Request\", { status: 400 });\n    }\n\n    const config = yield* ServerConfig.ServerConfig;\n    if (config.devUrl && isDevProxiedPath(url.value.pathname)) {\n      return HttpServerResponse.text(\"Not Found\", { status: 404 });\n    }\n\n    if (config.devUrl && isLoopbackHostname(url.value.hostname)) {\n      return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), {\n        status: 302,\n      });\n    }\n\n    const staticDir =\n      config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);\n    if (!staticDir) {\n      return HttpServerResponse.text(\"No static directory configured and no dev URL set.\", {\n        status: 503,\n      });\n    }\n\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const staticRoot = path.resolve(staticDir);\n    const staticRequestPath = url.value.pathname === \"/\" ? \"/index.html\" : url.value.pathname;\n    const rawStaticRelativePath = staticRequestPath.replace(/^[/\\\\]+/, \"\");\n    const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith(\"..\");\n    const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\\\]+/, \"\");\n    const hasPathTraversalSegment = staticRelativePath.startsWith(\"..\");\n    if (\n      staticRelativePath.length === 0 ||\n      hasRawLeadingParentSegment ||\n      hasPathTraversalSegment ||\n      staticRelativePath.includes(\"\\0\")\n    ) {\n      return HttpServerResponse.text(\"Invalid static file path\", { status: 400 });\n    }\n\n    const isWithinStaticRoot = (candidate: string) =>\n      candidate === staticRoot ||\n      candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);\n\n    let filePath = path.resolve(staticRoot, staticRelativePath);\n    if (!isWithinStaticRoot(filePath)) {\n      return HttpServerResponse.text(\"Invalid static file path\", { status: 400 });\n    }\n\n    const ext = path.extname(filePath);\n    if (!ext) {\n      filePath = path.resolve(filePath, \"index.html\");\n      if (!isWithinStaticRoot(filePath)) {\n        return HttpServerResponse.text(\"Invalid static file path\", { status: 400 });\n      }\n    }\n\n    const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));\n    if (!fileInfo || fileInfo.type !== \"File\") {\n      const indexPath = path.resolve(staticRoot, \"index.html\");\n      const indexData = yield* fileSystem\n        .readFile(indexPath)\n        .pipe(Effect.orElseSucceed(() => null));\n      if (!indexData) {\n        return HttpServerResponse.text(\"Not Found\", { status: 404 });\n      }\n      return HttpServerResponse.uint8Array(indexData, {\n        status: 200,\n        contentType: \"text/html; charset=utf-8\",\n      });\n    }\n\n    const contentType = Mime.getType(filePath) ?? \"application/octet-stream\";\n    const data = yield* fileSystem.readFile(filePath).pipe(Effect.orElseSucceed(() => null));\n    if (!data) {\n      return HttpServerResponse.text(\"Internal Server Error\", { status: 500 });\n    }\n\n    return HttpServerResponse.uint8Array(data, {\n      status: 200,\n      contentType,\n    });\n  }),\n);\n","import { NonNegativeInt, ThreadId, type VcsError } from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\n\nimport type { ProjectionRepositoryError } from \"../persistence/Errors.ts\";\n\nexport const CheckpointDiffOperation = Schema.Literals([\n  \"CheckpointDiffQuery.getTurnDiff\",\n  \"CheckpointDiffQuery.getFullThreadDiff\",\n]);\nexport type CheckpointDiffOperation = typeof CheckpointDiffOperation.Type;\n\n/** The computed result does not satisfy the checkpoint RPC contract. */\nexport class CheckpointDiffResultInvalidError extends Schema.TaggedErrorClass<CheckpointDiffResultInvalidError>()(\n  \"CheckpointDiffResultInvalidError\",\n  {\n    operation: CheckpointDiffOperation,\n    threadId: ThreadId,\n  },\n) {\n  override get message(): string {\n    const result =\n      this.operation === \"CheckpointDiffQuery.getTurnDiff\" ? \"turn diff\" : \"full thread diff\";\n    return `Checkpoint invariant violation in ${this.operation}: Computed ${result} result does not satisfy contract schema.`;\n  }\n}\n\n/** Projection state no longer contains the requested checkpoint thread. */\nexport class CheckpointThreadNotFoundError extends Schema.TaggedErrorClass<CheckpointThreadNotFoundError>()(\n  \"CheckpointThreadNotFoundError\",\n  {\n    operation: CheckpointDiffOperation,\n    threadId: ThreadId,\n  },\n) {\n  override get message(): string {\n    return `Checkpoint invariant violation in ${this.operation}: Thread '${this.threadId}' not found.`;\n  }\n}\n\n/** The checkpoint thread has no workspace path from which to compute a diff. */\nexport class CheckpointWorkspacePathMissingError extends Schema.TaggedErrorClass<CheckpointWorkspacePathMissingError>()(\n  \"CheckpointWorkspacePathMissingError\",\n  {\n    operation: CheckpointDiffOperation,\n    threadId: ThreadId,\n  },\n) {\n  override get message(): string {\n    const diff =\n      this.operation === \"CheckpointDiffQuery.getTurnDiff\" ? \"turn diff\" : \"full thread diff\";\n    return `Checkpoint invariant violation in ${this.operation}: Workspace path missing for thread '${this.threadId}' when computing ${diff}.`;\n  }\n}\n\n/** The requested turn lies beyond the latest available checkpoint. */\nexport class CheckpointTurnRangeUnavailableError extends Schema.TaggedErrorClass<CheckpointTurnRangeUnavailableError>()(\n  \"CheckpointTurnRangeUnavailableError\",\n  {\n    operation: CheckpointDiffOperation,\n    threadId: ThreadId,\n    requestedTurnCount: NonNegativeInt,\n    availableTurnCount: NonNegativeInt,\n  },\n) {\n  override get message(): string {\n    return `Checkpoint unavailable for thread ${this.threadId} turn ${this.requestedTurnCount}: Turn diff range exceeds current turn count: requested ${this.requestedTurnCount}, current ${this.availableTurnCount}.`;\n  }\n}\n\n/** Expected checkpoint metadata does not contain the requested Git ref. */\nexport class CheckpointRefUnavailableError extends Schema.TaggedErrorClass<CheckpointRefUnavailableError>()(\n  \"CheckpointRefUnavailableError\",\n  {\n    operation: CheckpointDiffOperation,\n    threadId: ThreadId,\n    turnCount: NonNegativeInt,\n    checkpoint: Schema.Literals([\"from\", \"to\"]),\n  },\n) {\n  override get message(): string {\n    return `Checkpoint unavailable for thread ${this.threadId} turn ${this.turnCount}: Checkpoint ref is unavailable for turn ${this.turnCount}.`;\n  }\n}\n\nexport type CheckpointStoreError = VcsError;\n\nexport type CheckpointServiceError =\n  | CheckpointStoreError\n  | ProjectionRepositoryError\n  | CheckpointDiffResultInvalidError\n  | CheckpointThreadNotFoundError\n  | CheckpointWorkspacePathMissingError\n  | CheckpointTurnRangeUnavailableError\n  | CheckpointRefUnavailableError;\n","import * as Encoding from \"effect/Encoding\";\nimport { CheckpointRef, ProjectId, type ThreadId } from \"@t3tools/contracts\";\n\nexport const CHECKPOINT_REFS_PREFIX = \"refs/t3/checkpoints\";\n\nexport function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {\n  return CheckpointRef.make(\n    `${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,\n  );\n}\n\nexport function resolveThreadWorkspaceCwd(input: {\n  readonly thread: {\n    readonly projectId: ProjectId;\n    readonly worktreePath: string | null;\n  };\n  readonly projects: ReadonlyArray<{\n    readonly id: ProjectId;\n    readonly workspaceRoot: string;\n  }>;\n}): string | undefined {\n  const worktreeCwd = input.thread.worktreePath ?? undefined;\n  if (worktreeCwd) {\n    return worktreeCwd;\n  }\n\n  return input.projects.find((project) => project.id === input.thread.projectId)?.workspaceRoot;\n}\n","export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {\n  const remoteNames: Array<string> = [];\n  for (const line of stdout.split(\"\\n\")) {\n    const remoteName = line.trim();\n    if (remoteName.length > 0) {\n      remoteNames.push(remoteName);\n    }\n  }\n  return remoteNames;\n}\n\nexport function parseRemoteNames(stdout: string): ReadonlyArray<string> {\n  return parseRemoteNamesInGitOrder(stdout).toSorted((a, b) => b.length - a.length);\n}\n\nexport function parseRemoteRefWithRemoteNames(\n  ref: string,\n  remoteNames: ReadonlyArray<string>,\n): { remoteRef: string; remoteName: string; branchName: string } | null {\n  const trimmedRef = ref.trim();\n  if (trimmedRef.length === 0) {\n    return null;\n  }\n\n  for (const remoteName of remoteNames) {\n    const remotePrefix = `${remoteName}/`;\n    if (!trimmedRef.startsWith(remotePrefix)) {\n      continue;\n    }\n    const branchName = trimmedRef.slice(remotePrefix.length).trim();\n    if (branchName.length === 0) {\n      return null;\n    }\n    return {\n      remoteRef: trimmedRef,\n      remoteName,\n      branchName,\n    };\n  }\n\n  return null;\n}\n\nexport function extractBranchNameFromRemoteRef(\n  ref: string,\n  options?: {\n    remoteName?: string | null;\n    remoteNames?: ReadonlyArray<string>;\n  },\n): string {\n  const normalized = ref.trim();\n  if (normalized.length === 0) {\n    return \"\";\n  }\n\n  if (normalized.startsWith(\"refs/remotes/\")) {\n    return extractBranchNameFromRemoteRef(normalized.slice(\"refs/remotes/\".length), options);\n  }\n\n  const remoteNames = options?.remoteName ? [options.remoteName] : (options?.remoteNames ?? []);\n  const parsedRemoteRef = parseRemoteRefWithRemoteNames(normalized, remoteNames);\n  if (parsedRemoteRef) {\n    return parsedRemoteRef.branchName;\n  }\n\n  const firstSlash = normalized.indexOf(\"/\");\n  if (firstSlash === -1) {\n    return normalized;\n  }\n  return normalized.slice(firstSlash + 1).trim();\n}\n","import * as Arr from \"effect/Array\";\nimport * as Cache from \"effect/Cache\";\nimport * as Data from \"effect/Data\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport {\n  GitCommandError,\n  type ReviewDiffFileContentsInput,\n  type ReviewDiffPreviewInput,\n  type ReviewDiffPreviewSource,\n  type VcsRef,\n} from \"@t3tools/contracts\";\nimport { dedupeRemoteBranchesWithLocalMatches, normalizeGitRemoteUrl } from \"@t3tools/shared/git\";\nimport { compactTraceAttributes } from \"@t3tools/shared/observability\";\nimport { decodeJsonResult } from \"@t3tools/shared/schemaJson\";\nimport { gitCommandDuration, gitCommandsTotal, withMetrics } from \"../observability/Metrics.ts\";\nimport * as GitVcsDriver from \"./GitVcsDriver.ts\";\nimport {\n  parseRemoteNames,\n  parseRemoteNamesInGitOrder,\n  parseRemoteRefWithRemoteNames,\n} from \"../git/remoteRefs.ts\";\nimport { ServerConfig } from \"../config.ts\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;\nconst OUTPUT_TRUNCATED_MARKER = \"\\n\\n[truncated]\";\nconst PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000;\nconst RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000;\nconst RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;\nconst RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;\nconst REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000;\nconst REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES = 80_000;\nconst REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES = 1024 * 1024;\nconst WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000;\nconst STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);\nconst STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);\n\nconst STATUS_UPSTREAM_REFRESH_FAILURE_BASE_COOLDOWN = Duration.seconds(30);\nconst STATUS_UPSTREAM_REFRESH_FAILURE_MAX_COOLDOWN = Duration.minutes(15);\nconst STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;\nconst REPOSITORY_PATHS_CACHE_CAPACITY = 2_048;\nconst REPOSITORY_PATHS_CACHE_TTL = Duration.minutes(10);\nconst REPOSITORY_PATHS_REFRESH_COALESCE_TTL = Duration.seconds(5);\nconst NON_REPOSITORY_PATHS_CACHE_TTL = Duration.seconds(1);\nconst LIST_REFS_SNAPSHOT_CACHE_CAPACITY = 64;\nconst LIST_REFS_SNAPSHOT_CACHE_TTL = Duration.minutes(2);\nconst LIST_REFS_REFRESH_COALESCE_TTL = Duration.seconds(5);\nconst LIST_REFS_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30);\nconst STATUS_DEFAULT_BRANCH_CACHE_TTL = Duration.minutes(5);\nconst STATUS_ORIGIN_EXISTS_CACHE_TTL = Duration.minutes(5);\nconst STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({\n  GCM_INTERACTIVE: \"never\",\n  GIT_ASKPASS: \"\",\n  GIT_TERMINAL_PROMPT: \"0\",\n  SSH_ASKPASS: \"\",\n  SSH_ASKPASS_REQUIRE: \"never\",\n} satisfies NodeJS.ProcessEnv);\nconst DEFAULT_BASE_BRANCH_CANDIDATES = [\"main\", \"master\"] as const;\nconst GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;\nconst NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetails>({\n  isRepo: false,\n  hasOriginRemote: false,\n  isDefaultBranch: false,\n  branch: null,\n  upstreamRef: null,\n  hasWorkingTreeChanges: false,\n  workingTree: { files: [], insertions: 0, deletions: 0 },\n  hasUpstream: false,\n  aheadCount: 0,\n  behindCount: 0,\n  aheadOfDefaultCount: 0,\n});\nconst NON_REPOSITORY_REMOTE_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitRemoteStatusDetails>({\n  isRepo: false,\n  isDefaultBranch: false,\n  branch: null,\n  upstreamRef: null,\n  hasUpstream: false,\n  aheadCount: 0,\n  behindCount: 0,\n  aheadOfDefaultCount: 0,\n});\n\ntype TraceTailState = {\n  processedChars: number;\n  remainder: string;\n};\n\nclass StatusRemoteRefreshCacheKey extends Data.Class<{\n  gitCommonDir: string;\n  remoteName: string;\n}> {}\n\nfunction statusUpstreamRefreshFailureCooldown(consecutiveFailures: number): Duration.Duration {\n  const exponent = Math.max(0, consecutiveFailures - 1);\n  const cooldownMs =\n    Duration.toMillis(STATUS_UPSTREAM_REFRESH_FAILURE_BASE_COOLDOWN) * Math.pow(2, exponent);\n  return Duration.min(Duration.millis(cooldownMs), STATUS_UPSTREAM_REFRESH_FAILURE_MAX_COOLDOWN);\n}\n\nclass GitRefsSnapshotCacheKey extends Data.Class<{\n  gitCommonDir: string;\n  epoch: number;\n}> {}\n\nclass GitRefsRefreshCacheKey extends Data.Class<{\n  gitCommonDir: string;\n  generation: number;\n}> {}\n\ninterface GitRepositoryPaths {\n  readonly gitCommonDir: string;\n  readonly worktreeRoot: string | null;\n  readonly currentBranch: string | null;\n}\n\ninterface GitRefsSnapshot {\n  readonly localBranches: ReadonlyArray<VcsRef>;\n  readonly remoteBranches: ReadonlyArray<VcsRef>;\n  readonly hasPrimaryRemote: boolean;\n}\n\ninterface ExecuteGitOptions {\n  stdin?: string | undefined;\n  timeoutMs?: number | undefined;\n  allowNonZeroExit?: boolean | undefined;\n  fallbackErrorDetail?: string | undefined;\n  env?: NodeJS.ProcessEnv | undefined;\n  maxOutputBytes?: number | undefined;\n  appendTruncationMarker?: boolean | undefined;\n  progress?: GitVcsDriver.ExecuteGitProgress | undefined;\n}\n\nfunction parseBranchAb(value: string): { ahead: number; behind: number } {\n  const match = value.match(/^\\+(\\d+)\\s+-(\\d+)$/);\n  if (!match) return { ahead: 0, behind: 0 };\n  return {\n    ahead: Number(match[1] ?? \"0\"),\n    behind: Number(match[2] ?? \"0\"),\n  };\n}\n\nfunction parseNumstatEntries(\n  stdout: string,\n): Array<{ path: string; insertions: number; deletions: number }> {\n  const entries: Array<{ path: string; insertions: number; deletions: number }> = [];\n  for (const line of stdout.split(/\\r?\\n/g)) {\n    if (line.trim().length === 0) continue;\n    const [addedRaw, deletedRaw, ...pathParts] = line.split(\"\\t\");\n    const rawPath =\n      pathParts.length > 1 ? (pathParts.at(-1) ?? \"\").trim() : pathParts.join(\"\\t\").trim();\n    if (rawPath.length === 0) continue;\n    const added = Number.parseInt(addedRaw ?? \"0\", 10);\n    const deleted = Number.parseInt(deletedRaw ?? \"0\", 10);\n    const renameArrowIndex = rawPath.indexOf(\" => \");\n    const normalizedPath =\n      renameArrowIndex >= 0 ? rawPath.slice(renameArrowIndex + \" => \".length).trim() : rawPath;\n    entries.push({\n      path: normalizedPath.length > 0 ? normalizedPath : rawPath,\n      insertions: Number.isFinite(added) ? added : 0,\n      deletions: Number.isFinite(deleted) ? deleted : 0,\n    });\n  }\n  return entries;\n}\n\nfunction parsePorcelainPath(line: string): string | null {\n  if (line.startsWith(\"? \") || line.startsWith(\"! \")) {\n    const simple = line.slice(2).trim();\n    return simple.length > 0 ? simple : null;\n  }\n\n  if (!(line.startsWith(\"1 \") || line.startsWith(\"2 \") || line.startsWith(\"u \"))) {\n    return null;\n  }\n\n  const tabIndex = line.indexOf(\"\\t\");\n  if (tabIndex >= 0) {\n    const fromTab = line.slice(tabIndex + 1);\n    const [filePath] = fromTab.split(\"\\t\");\n    return filePath?.trim().length ? filePath.trim() : null;\n  }\n\n  const parts = line.trim().split(/\\s+/g);\n  const filePath = parts.at(-1) ?? \"\";\n  return filePath.length > 0 ? filePath : null;\n}\n\nfunction filterBranchesForListQuery(\n  refs: ReadonlyArray<VcsRef>,\n  query?: string,\n): ReadonlyArray<VcsRef> {\n  if (!query) {\n    return refs;\n  }\n\n  const normalizedQuery = query.toLowerCase();\n  return refs.filter((refName) => refName.name.toLowerCase().includes(normalizedQuery));\n}\n\nfunction paginateBranches(input: {\n  refs: ReadonlyArray<VcsRef>;\n  cursor?: number | undefined;\n  limit?: number | undefined;\n}): {\n  refs: ReadonlyArray<VcsRef>;\n  nextCursor: number | null;\n  totalCount: number;\n} {\n  const cursor = input.cursor ?? 0;\n  const limit = input.limit ?? GIT_LIST_BRANCHES_DEFAULT_LIMIT;\n  const totalCount = input.refs.length;\n  const refs = input.refs.slice(cursor, cursor + limit);\n  const nextCursor = cursor + refs.length < totalCount ? cursor + refs.length : null;\n\n  return {\n    refs,\n    nextCursor,\n    totalCount,\n  };\n}\n\nfunction parseWorktreeBranchPaths(stdout: string): ReadonlyMap<string, string> {\n  const worktreePaths = new Map<string, string>();\n  let currentPath: string | null = null;\n  let currentBranch: string | null = null;\n  let currentPrunable = false;\n\n  const flush = () => {\n    if (currentPath !== null && currentBranch !== null && !currentPrunable) {\n      worktreePaths.set(currentBranch, currentPath);\n    }\n    currentPath = null;\n    currentBranch = null;\n    currentPrunable = false;\n  };\n\n  for (const field of stdout.split(\"\\0\")) {\n    if (field === \"\") {\n      flush();\n    } else if (field.startsWith(\"worktree \")) {\n      currentPath = field.slice(\"worktree \".length);\n    } else if (field.startsWith(\"branch refs/heads/\")) {\n      currentBranch = field.slice(\"branch refs/heads/\".length);\n    } else if (field === \"prunable\" || field.startsWith(\"prunable \")) {\n      currentPrunable = true;\n    }\n  }\n  flush();\n\n  return worktreePaths;\n}\n\nfunction splitNullSeparatedPaths(input: string, truncated: boolean): string[] {\n  const parts = input.split(\"\\0\");\n  if (parts.length === 0) return [];\n\n  if (truncated && parts[parts.length - 1]?.length) {\n    parts.pop();\n  }\n\n  return parts.filter((value) => value.length > 0);\n}\n\nexport function splitNullSeparatedGitStdoutPaths(\n  result: Pick<GitVcsDriver.ExecuteGitResult, \"stdout\" | \"stdoutTruncated\">,\n): string[] {\n  return splitNullSeparatedPaths(result.stdout, result.stdoutTruncated);\n}\n\nfunction sanitizeRemoteName(value: string): string {\n  const sanitized = value\n    .trim()\n    .replace(/[^A-Za-z0-9._-]+/g, \"-\")\n    .replace(/^-+|-+$/g, \"\");\n  return sanitized.length > 0 ? sanitized : \"fork\";\n}\n\nfunction parseRemoteFetchUrls(stdout: string): Map<string, string> {\n  const remotes = new Map<string, string>();\n  for (const line of stdout.split(\"\\n\")) {\n    const trimmed = line.trim();\n    if (trimmed.length === 0) continue;\n    const match = /^(\\S+)\\s+(\\S+)\\s+\\((fetch|push)\\)$/.exec(trimmed);\n    if (!match) continue;\n    const [, remoteName = \"\", remoteUrl = \"\", direction = \"\"] = match;\n    if (direction !== \"fetch\" || remoteName.length === 0 || remoteUrl.length === 0) {\n      continue;\n    }\n    remotes.set(remoteName, remoteUrl);\n  }\n  return remotes;\n}\n\nfunction parseUpstreamRefWithRemoteNames(\n  upstreamRef: string,\n  remoteNames: ReadonlyArray<string>,\n): { upstreamRef: string; remoteName: string; branchName: string } | null {\n  const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames);\n  if (!parsed) {\n    return null;\n  }\n\n  return {\n    upstreamRef,\n    remoteName: parsed.remoteName,\n    branchName: parsed.branchName,\n  };\n}\n\nfunction parseUpstreamRefByFirstSeparator(\n  upstreamRef: string,\n): { upstreamRef: string; remoteName: string; branchName: string } | null {\n  const separatorIndex = upstreamRef.indexOf(\"/\");\n  if (separatorIndex <= 0 || separatorIndex === upstreamRef.length - 1) {\n    return null;\n  }\n\n  const remoteName = upstreamRef.slice(0, separatorIndex).trim();\n  const branchName = upstreamRef.slice(separatorIndex + 1).trim();\n  if (remoteName.length === 0 || branchName.length === 0) {\n    return null;\n  }\n\n  return {\n    upstreamRef,\n    remoteName,\n    branchName,\n  };\n}\n\nfunction parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {\n  for (const line of stdout.split(\"\\n\")) {\n    const trimmedLine = line.trim();\n    if (trimmedLine.length === 0) {\n      continue;\n    }\n    const [branchNameRaw, upstreamBranchRaw = \"\"] = trimmedLine.split(\"\\t\");\n    const branchName = branchNameRaw?.trim() ?? \"\";\n    const candidateUpstreamRef = upstreamBranchRaw.trim();\n    if (branchName.length === 0 || candidateUpstreamRef.length === 0) {\n      continue;\n    }\n    if (candidateUpstreamRef === upstreamRef) {\n      return branchName;\n    }\n  }\n\n  return null;\n}\n\nfunction deriveLocalBranchNameFromRemoteRef(branchName: string): string | null {\n  const separatorIndex = branchName.indexOf(\"/\");\n  if (separatorIndex <= 0 || separatorIndex === branchName.length - 1) {\n    return null;\n  }\n  const localBranch = branchName.slice(separatorIndex + 1).trim();\n  return localBranch.length > 0 ? localBranch : null;\n}\n\nfunction gitCommandContext(\n  input: Pick<GitVcsDriver.ExecuteGitInput, \"operation\" | \"cwd\" | \"args\">,\n) {\n  return {\n    operation: input.operation,\n    command: \"git\",\n    cwd: input.cwd,\n    argumentCount: input.args.length,\n  } as const;\n}\n\nfunction parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null {\n  const trimmed = value.trim();\n  const prefix = `refs/remotes/${remoteName}/`;\n  if (!trimmed.startsWith(prefix)) {\n    return null;\n  }\n  const refName = trimmed.slice(prefix.length).trim();\n  return refName.length > 0 ? refName : null;\n}\n\nfunction isMissingGitCwdError(error: GitCommandError): boolean {\n  if (!(error.cause instanceof PlatformError.PlatformError)) {\n    return false;\n  }\n\n  const reason = error.cause.reason;\n  if (reason._tag === \"NotFound\") {\n    return reason.pathOrDescriptor === error.cwd;\n  }\n\n  return (\n    reason._tag === \"BadResource\" &&\n    reason.pathOrDescriptor === error.cwd &&\n    typeof reason.cause === \"object\" &&\n    reason.cause !== null &&\n    \"code\" in reason.cause &&\n    reason.cause.code === \"ENOTDIR\"\n  );\n}\n\nfunction isNonRepositoryGitStderr(stderr: string): boolean {\n  return stderr.toLowerCase().includes(\"not a git repository\");\n}\nfunction isUnbornHeadStderr(stderr: string): boolean {\n  return (\n    stderr.toLowerCase().includes(\"unknown revision\") &&\n    stderr.toLowerCase().includes(\"path not in the working tree\")\n  );\n}\n\ninterface Trace2Monitor {\n  readonly env: NodeJS.ProcessEnv;\n  readonly flush: Effect.Effect<void, never>;\n}\n\nconst nowUnixNano = DateTime.now.pipe(\n  Effect.map((now) => BigInt(DateTime.toEpochMillis(now)) * 1_000_000n),\n);\n\nconst addCurrentSpanEvent = (name: string, attributes: Record<string, unknown>) =>\n  Effect.gen(function* () {\n    const span = yield* Effect.currentSpan;\n    const timestamp = yield* nowUnixNano;\n    yield* Effect.sync(() => {\n      span.event(name, timestamp, compactTraceAttributes(attributes));\n    });\n  }).pipe(\n    Effect.catchTags({\n      NoSuchElementError: () => Effect.void,\n    }),\n  );\n\nfunction trace2ChildKey(record: Record<string, unknown>): string | null {\n  const childId = record.child_id;\n  if (typeof childId === \"number\" || typeof childId === \"string\") {\n    return String(childId);\n  }\n  const hookName = record.hook_name;\n  return typeof hookName === \"string\" && hookName.trim().length > 0 ? hookName.trim() : null;\n}\n\nconst Trace2Record = Schema.Record(Schema.String, Schema.Unknown);\n\nconst createTrace2Monitor = Effect.fn(\"createTrace2Monitor\")(function* (\n  input: Pick<GitVcsDriver.ExecuteGitInput, \"operation\" | \"cwd\" | \"args\">,\n  progress: GitVcsDriver.ExecuteGitProgress | undefined,\n): Effect.fn.Return<\n  Trace2Monitor,\n  PlatformError.PlatformError,\n  Scope.Scope | FileSystem.FileSystem | Path.Path\n> {\n  if (!progress?.onHookStarted && !progress?.onHookFinished) {\n    return {\n      env: {},\n      flush: Effect.void,\n    };\n  }\n\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const traceFilePath = yield* fs.makeTempFileScoped({\n    prefix: `t3code-git-trace2-${process.pid}-`,\n    suffix: \".json\",\n  });\n  const hookStartByChildKey = new Map<string, { hookName: string; startedAtMs: number }>();\n  const traceTailState = yield* Ref.make<TraceTailState>({\n    processedChars: 0,\n    remainder: \"\",\n  });\n\n  const handleTraceLine = Effect.fn(\"handleTraceLine\")(function* (line: string) {\n    const trimmedLine = line.trim();\n    if (trimmedLine.length === 0) {\n      return;\n    }\n\n    const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine);\n    if (Result.isFailure(traceRecord)) {\n      yield* Effect.logDebug(\n        `GitVcsDriver.trace2: failed to parse trace line for ${input.operation} in ${input.cwd} (${input.args.length} arguments)`,\n        traceRecord.failure,\n      );\n      return;\n    }\n\n    if (traceRecord.success.child_class !== \"hook\") {\n      return;\n    }\n\n    const event = traceRecord.success.event;\n    const childKey = trace2ChildKey(traceRecord.success);\n    if (childKey === null) {\n      return;\n    }\n    const started = hookStartByChildKey.get(childKey);\n    const hookNameFromEvent =\n      typeof traceRecord.success.hook_name === \"string\" ? traceRecord.success.hook_name.trim() : \"\";\n    const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? \"\");\n    if (hookName.length === 0) {\n      return;\n    }\n\n    if (event === \"child_start\") {\n      const now = yield* DateTime.now;\n      hookStartByChildKey.set(childKey, { hookName, startedAtMs: DateTime.toEpochMillis(now) });\n      yield* addCurrentSpanEvent(\"git.hook.started\", {\n        hookName,\n      });\n      if (progress.onHookStarted) {\n        yield* progress.onHookStarted(hookName);\n      }\n      return;\n    }\n\n    if (event === \"child_exit\") {\n      hookStartByChildKey.delete(childKey);\n      const code = traceRecord.success.exitCode;\n      const exitCode = typeof code === \"number\" && Number.isInteger(code) ? code : null;\n      const now = yield* DateTime.now;\n      const durationMs = started\n        ? Math.max(0, DateTime.toEpochMillis(now) - started.startedAtMs)\n        : null;\n      yield* addCurrentSpanEvent(\"git.hook.finished\", {\n        hookName: started?.hookName ?? hookName,\n        exitCode,\n        durationMs,\n      });\n      if (progress.onHookFinished) {\n        yield* progress.onHookFinished({\n          hookName: started?.hookName ?? hookName,\n          exitCode,\n          durationMs,\n        });\n      }\n    }\n  });\n\n  const deltaMutex = yield* Semaphore.make(1);\n  const readTraceDelta = deltaMutex.withPermit(\n    fs.readFileString(traceFilePath).pipe(\n      Effect.flatMap((contents) =>\n        Effect.uninterruptible(\n          Ref.modify(traceTailState, ({ processedChars, remainder }) => {\n            if (contents.length <= processedChars) {\n              return [[], { processedChars, remainder }];\n            }\n\n            const appended = contents.slice(processedChars);\n            const combined = remainder + appended;\n            const lines = combined.split(\"\\n\");\n            const nextRemainder = lines.pop() ?? \"\";\n\n            return [\n              lines.map((line) => line.replace(/\\r$/, \"\")),\n              {\n                processedChars: contents.length,\n                remainder: nextRemainder,\n              },\n            ];\n          }).pipe(\n            Effect.flatMap((lines) => Effect.forEach(lines, handleTraceLine, { discard: true })),\n          ),\n        ),\n      ),\n      Effect.ignore({ log: true }),\n    ),\n  );\n  const traceFileName = path.basename(traceFilePath);\n  yield* Stream.runForEach(fs.watch(traceFilePath), (event) => {\n    const eventPath = event.path;\n    const isTargetTraceEvent =\n      eventPath === traceFilePath ||\n      eventPath === traceFileName ||\n      path.basename(eventPath) === traceFileName;\n    if (!isTargetTraceEvent) return Effect.void;\n    return readTraceDelta;\n  }).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);\n\n  const finalizeTrace2Monitor = Effect.fn(\"finalizeTrace2Monitor\")(function* () {\n    yield* readTraceDelta;\n    const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [\n      remainder.trim(),\n      {\n        processedChars,\n        remainder: \"\",\n      },\n    ]);\n    if (finalLine.length > 0) {\n      yield* handleTraceLine(finalLine);\n    }\n  });\n\n  yield* Effect.addFinalizer(finalizeTrace2Monitor);\n\n  return {\n    env: {\n      GIT_TRACE2_EVENT: traceFilePath,\n    },\n    flush: readTraceDelta,\n  };\n});\n\nconst collectOutput = Effect.fnUntraced(function* (\n  input: Pick<GitVcsDriver.ExecuteGitInput, \"operation\" | \"cwd\" | \"args\">,\n  stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,\n  maxOutputBytes: number,\n  appendTruncationMarker: boolean,\n  onLine: ((line: string) => Effect.Effect<void, never>) | undefined,\n): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {\n  const decoder = new TextDecoder();\n  let bytes = 0;\n  let text = \"\";\n  let lineBuffer = \"\";\n  let truncated = false;\n\n  const emitCompleteLines = Effect.fnUntraced(function* (flush: boolean) {\n    let newlineIndex = lineBuffer.indexOf(\"\\n\");\n    while (newlineIndex >= 0) {\n      const line = lineBuffer.slice(0, newlineIndex).replace(/\\r$/, \"\");\n      lineBuffer = lineBuffer.slice(newlineIndex + 1);\n      if (line.length > 0 && onLine) {\n        yield* onLine(line);\n      }\n      newlineIndex = lineBuffer.indexOf(\"\\n\");\n    }\n\n    if (flush) {\n      const trailing = lineBuffer.replace(/\\r$/, \"\");\n      lineBuffer = \"\";\n      if (trailing.length > 0 && onLine) {\n        yield* onLine(trailing);\n      }\n    }\n  });\n\n  const processChunk = Effect.fnUntraced(function* (chunk: Uint8Array) {\n    if (appendTruncationMarker && truncated) {\n      return;\n    }\n    const nextBytes = bytes + chunk.byteLength;\n    if (!appendTruncationMarker && nextBytes > maxOutputBytes) {\n      return yield* new GitCommandError({\n        ...gitCommandContext(input),\n        detail: `Git output exceeded ${maxOutputBytes} bytes and was truncated.`,\n        outputLength: nextBytes,\n      });\n    }\n\n    const chunkToDecode =\n      appendTruncationMarker && nextBytes > maxOutputBytes\n        ? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes))\n        : chunk;\n    bytes += chunkToDecode.byteLength;\n    truncated = appendTruncationMarker && nextBytes > maxOutputBytes;\n\n    const decoded = decoder.decode(chunkToDecode, { stream: !truncated });\n    text += decoded;\n    lineBuffer += decoded;\n    yield* emitCompleteLines(false);\n  });\n\n  yield* Stream.runForEach(stream, processChunk).pipe(\n    Effect.catchTags({\n      PlatformError: (cause) =>\n        new GitCommandError({\n          ...gitCommandContext(input),\n          detail: \"Failed to read Git process output.\",\n          cause,\n        }),\n    }),\n  );\n\n  const remainder = truncated ? \"\" : decoder.decode();\n  text += remainder;\n  lineBuffer += remainder;\n  yield* emitCompleteLines(true);\n  return {\n    text,\n    truncated,\n  };\n});\n\nexport const makeGitVcsDriverCore = Effect.fn(\"makeGitVcsDriverCore\")(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const { worktreesDir } = yield* ServerConfig;\n  const crypto = yield* Crypto.Crypto;\n\n  const executeRaw: GitVcsDriver.GitVcsDriver[\"Service\"][\"execute\"] = Effect.fnUntraced(\n    function* (input) {\n      const commandInput = {\n        ...input,\n        args: [...input.args],\n      } as const;\n      const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n      const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n      const appendTruncationMarker = input.appendTruncationMarker ?? false;\n\n      const runGitCommand = Effect.fn(\"runGitCommand\")(function* () {\n        const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe(\n          Effect.provideService(Path.Path, path),\n          Effect.provideService(FileSystem.FileSystem, fileSystem),\n          Effect.mapError(\n            (cause) =>\n              new GitCommandError({\n                ...gitCommandContext(commandInput),\n                detail: \"Failed to create Git trace monitor.\",\n                cause,\n              }),\n          ),\n        );\n        const child = yield* commandSpawner\n          .spawn(\n            ChildProcess.make(\"git\", commandInput.args, {\n              cwd: commandInput.cwd,\n              env: {\n                ...process.env,\n                ...input.env,\n                ...trace2Monitor.env,\n              },\n            }),\n          )\n          .pipe(\n            Effect.mapError(\n              (cause) =>\n                new GitCommandError({\n                  ...gitCommandContext(commandInput),\n                  detail: \"Failed to spawn Git process.\",\n                  cause,\n                }),\n            ),\n          );\n\n        const [stdout, stderr, exitCode] = yield* Effect.all(\n          [\n            collectOutput(\n              commandInput,\n              child.stdout,\n              maxOutputBytes,\n              appendTruncationMarker,\n              input.progress?.onStdoutLine,\n            ),\n            collectOutput(\n              commandInput,\n              child.stderr,\n              maxOutputBytes,\n              appendTruncationMarker,\n              input.progress?.onStderrLine,\n            ),\n            child.exitCode.pipe(\n              Effect.mapError(\n                (cause) =>\n                  new GitCommandError({\n                    ...gitCommandContext(commandInput),\n                    detail: \"Failed to read Git process exit code.\",\n                    cause,\n                  }),\n              ),\n            ),\n            input.stdin === undefined\n              ? Effect.void\n              : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(\n                  Effect.mapError(\n                    (cause) =>\n                      new GitCommandError({\n                        ...gitCommandContext(commandInput),\n                        detail: \"Failed to write Git process input.\",\n                        cause,\n                      }),\n                  ),\n                ),\n          ],\n          { concurrency: \"unbounded\" },\n        ).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));\n        yield* trace2Monitor.flush;\n\n        if (!input.allowNonZeroExit && exitCode !== 0) {\n          return yield* new GitCommandError({\n            ...gitCommandContext(commandInput),\n            detail: \"Git command exited with a non-zero status.\",\n            exitCode,\n            stdoutLength: stdout.text.length,\n            stderrLength: stderr.text.length,\n          });\n        }\n\n        return {\n          exitCode,\n          stdout: stdout.text,\n          stderr: stderr.text,\n          stdoutTruncated: stdout.truncated,\n          stderrTruncated: stderr.truncated,\n        } satisfies GitVcsDriver.ExecuteGitResult;\n      });\n\n      return yield* runGitCommand().pipe(\n        Effect.scoped,\n        Effect.timeoutOption(timeoutMs),\n        Effect.flatMap((result) =>\n          Option.match(result, {\n            onNone: () =>\n              Effect.fail(\n                new GitCommandError({\n                  ...gitCommandContext(commandInput),\n                  detail: \"Git command timed out.\",\n                }),\n              ),\n            onSome: Effect.succeed,\n          }),\n        ),\n      );\n    },\n  );\n\n  const execute: GitVcsDriver.GitVcsDriver[\"Service\"][\"execute\"] = (input) =>\n    executeRaw(input).pipe(\n      withMetrics({\n        counter: gitCommandsTotal,\n        timer: gitCommandDuration,\n        attributes: {\n          operation: input.operation,\n        },\n      }),\n      Effect.withSpan(input.operation, {\n        kind: \"client\",\n        attributes: {\n          \"git.operation\": input.operation,\n          \"git.cwd\": input.cwd,\n          \"git.args_count\": input.args.length,\n        },\n      }),\n    );\n\n  const executeGit = (\n    operation: string,\n    cwd: string,\n    args: readonly string[],\n    options: ExecuteGitOptions = {},\n  ): Effect.Effect<GitVcsDriver.ExecuteGitResult, GitCommandError> =>\n    execute({\n      operation,\n      cwd,\n      args,\n      ...(options.stdin !== undefined ? { stdin: options.stdin } : {}),\n      ...(options.env !== undefined ? { env: options.env } : {}),\n      allowNonZeroExit: true,\n      ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n      ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),\n      ...(options.appendTruncationMarker !== undefined\n        ? { appendTruncationMarker: options.appendTruncationMarker }\n        : {}),\n      ...(options.progress ? { progress: options.progress } : {}),\n    }).pipe(\n      Effect.flatMap((result) => {\n        if (options.allowNonZeroExit || result.exitCode === 0) {\n          return Effect.succeed(result);\n        }\n        return Effect.fail(\n          new GitCommandError({\n            ...gitCommandContext({ operation, cwd, args }),\n            detail: options.fallbackErrorDetail ?? \"Git command exited with a non-zero status.\",\n            ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),\n            stdoutLength: result.stdout.length,\n            stderrLength: result.stderr.length,\n          }),\n        );\n      }),\n    );\n\n  const executeGitWithStableDiagnostics = (\n    operation: string,\n    cwd: string,\n    args: readonly string[],\n    options: ExecuteGitOptions = {},\n  ): Effect.Effect<GitVcsDriver.ExecuteGitResult, GitCommandError> =>\n    executeGit(operation, cwd, args, {\n      ...options,\n      env: {\n        ...options.env,\n        LC_ALL: \"C\",\n      },\n    });\n\n  const runGit = (\n    operation: string,\n    cwd: string,\n    args: readonly string[],\n    allowNonZeroExit = false,\n  ): Effect.Effect<void, GitCommandError> =>\n    executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid);\n\n  const runGitStdout = (\n    operation: string,\n    cwd: string,\n    args: readonly string[],\n    allowNonZeroExit = false,\n  ): Effect.Effect<string, GitCommandError> =>\n    executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(\n      Effect.map((result) => result.stdout),\n    );\n\n  const runGitStdoutWithOptions = (\n    operation: string,\n    cwd: string,\n    args: readonly string[],\n    options: ExecuteGitOptions = {},\n  ): Effect.Effect<string, GitCommandError> =>\n    executeGit(operation, cwd, args, options).pipe(\n      Effect.map((result) =>\n        result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout,\n      ),\n    );\n\n  const branchExists = (cwd: string, refName: string): Effect.Effect<boolean, GitCommandError> =>\n    executeGit(\n      \"GitVcsDriver.branchExists\",\n      cwd,\n      [\"show-ref\", \"--verify\", \"--quiet\", `refs/heads/${refName}`],\n      {\n        allowNonZeroExit: true,\n        timeoutMs: 5_000,\n      },\n    ).pipe(Effect.map((result) => result.exitCode === 0));\n\n  const resolveAvailableBranchName = Effect.fn(\"resolveAvailableBranchName\")(function* (\n    cwd: string,\n    desiredBranch: string,\n  ) {\n    const isDesiredTaken = yield* branchExists(cwd, desiredBranch);\n    if (!isDesiredTaken) {\n      return desiredBranch;\n    }\n\n    for (let suffix = 1; suffix <= 100; suffix += 1) {\n      const candidate = `${desiredBranch}-${suffix}`;\n      const isCandidateTaken = yield* branchExists(cwd, candidate);\n      if (!isCandidateTaken) {\n        return candidate;\n      }\n    }\n\n    return yield* new GitCommandError({\n      ...gitCommandContext({\n        operation: \"GitVcsDriver.renameBranch\",\n        cwd,\n        args: [\"branch\", \"-m\", \"--\", desiredBranch],\n      }),\n      detail: `Could not find an available branch name for '${desiredBranch}'.`,\n    });\n  });\n\n  const resolveCurrentUpstream = Effect.fn(\"resolveCurrentUpstream\")(function* (cwd: string) {\n    const upstreamRef = yield* runGitStdout(\n      \"GitVcsDriver.resolveCurrentUpstream\",\n      cwd,\n      [\"rev-parse\", \"--abbrev-ref\", \"--symbolic-full-name\", \"@{upstream}\"],\n      true,\n    ).pipe(Effect.map((stdout) => stdout.trim()));\n\n    if (upstreamRef.length === 0 || upstreamRef === \"@{upstream}\") {\n      return null;\n    }\n\n    const remoteNames = yield* runGitStdout(\"GitVcsDriver.listRemoteNames\", cwd, [\"remote\"]).pipe(\n      Effect.map(parseRemoteNames),\n      Effect.orElseSucceed((): ReadonlyArray<string> => []),\n    );\n    return (\n      parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ??\n      parseUpstreamRefByFirstSeparator(upstreamRef)\n    );\n  });\n\n  const fetchRemoteForStatus = (\n    gitCommonDir: string,\n    remoteName: string,\n  ): Effect.Effect<void, GitCommandError> => {\n    const fetchCwd =\n      path.basename(gitCommonDir) === \".git\" ? path.dirname(gitCommonDir) : gitCommonDir;\n    return executeGit(\n      \"GitVcsDriver.fetchRemoteForStatus\",\n      fetchCwd,\n      [\"--git-dir\", gitCommonDir, \"fetch\", \"--quiet\", \"--no-tags\", remoteName],\n      {\n        env: STATUS_UPSTREAM_REFRESH_ENV,\n        fallbackErrorDetail: \"Background Git fetch exited with a non-zero status.\",\n        timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),\n      },\n    ).pipe(Effect.asVoid);\n  };\n\n  const resolveRepositoryPathsUncached = Effect.fn(\"resolveRepositoryPathsUncached\")(function* (\n    cwd: string,\n  ) {\n    const commonDirResult = yield* executeGitWithStableDiagnostics(\n      \"GitVcsDriver.resolveRepositoryPaths.commonDir\",\n      cwd,\n      [\"rev-parse\", \"--git-common-dir\"],\n      {\n        timeoutMs: 5_000,\n        allowNonZeroExit: true,\n      },\n    );\n    if (commonDirResult.exitCode !== 0) {\n      const stderr = commonDirResult.stderr.trim();\n      if (isNonRepositoryGitStderr(stderr)) {\n        return null;\n      }\n      return yield* new GitCommandError({\n        ...gitCommandContext({\n          operation: \"GitVcsDriver.resolveRepositoryPaths.commonDir\",\n          cwd,\n          args: [\"rev-parse\", \"--git-common-dir\"],\n        }),\n        detail: \"Failed to resolve the Git common directory.\",\n        exitCode: commonDirResult.exitCode,\n        stdoutLength: commonDirResult.stdout.length,\n        stderrLength: commonDirResult.stderr.length,\n      });\n    }\n\n    const commonDirOutput = commonDirResult.stdout.trim();\n    const resolvedGitCommonDir = path.isAbsolute(commonDirOutput)\n      ? path.normalize(commonDirOutput)\n      : path.resolve(cwd, commonDirOutput);\n    const gitCommonDir = yield* fileSystem\n      .realPath(resolvedGitCommonDir)\n      .pipe(Effect.orElseSucceed(() => resolvedGitCommonDir));\n    const [worktreeRootResult, currentBranchResult] = yield* Effect.all(\n      [\n        executeGit(\n          \"GitVcsDriver.resolveRepositoryPaths.worktreeRoot\",\n          cwd,\n          [\"rev-parse\", \"--show-toplevel\"],\n          {\n            timeoutMs: 5_000,\n            allowNonZeroExit: true,\n          },\n        ),\n        executeGit(\n          \"GitVcsDriver.resolveRepositoryPaths.currentBranch\",\n          cwd,\n          [\"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"],\n          {\n            timeoutMs: 5_000,\n            allowNonZeroExit: true,\n          },\n        ),\n      ],\n      { concurrency: 2 },\n    );\n    const worktreeRootOutput = worktreeRootResult.stdout.trim();\n    const worktreeRoot =\n      worktreeRootResult.exitCode === 0 && worktreeRootOutput.length > 0\n        ? path.normalize(\n            path.isAbsolute(worktreeRootOutput)\n              ? worktreeRootOutput\n              : path.resolve(cwd, worktreeRootOutput),\n          )\n        : null;\n    const currentBranchOutput = currentBranchResult.stdout.trim();\n    const currentBranch =\n      currentBranchResult.exitCode === 0 && currentBranchOutput.length > 0\n        ? currentBranchOutput\n        : null;\n\n    return {\n      gitCommonDir,\n      worktreeRoot,\n      currentBranch,\n    } satisfies GitRepositoryPaths;\n  });\n\n  const repositoryPathsCache = yield* Cache.makeWith(\n    (cwd: string) => resolveRepositoryPathsUncached(cwd),\n    {\n      capacity: REPOSITORY_PATHS_CACHE_CAPACITY,\n      timeToLive: Exit.match({\n        onSuccess: (repositoryPaths) =>\n          repositoryPaths === null ? NON_REPOSITORY_PATHS_CACHE_TTL : REPOSITORY_PATHS_CACHE_TTL,\n        onFailure: () => Duration.zero,\n      }),\n    },\n  );\n  const repositoryPathsRefreshCache = yield* Cache.makeWith(\n    (cwd: string) =>\n      Cache.invalidate(repositoryPathsCache, cwd).pipe(\n        Effect.andThen(Cache.get(repositoryPathsCache, cwd)),\n      ),\n    {\n      capacity: REPOSITORY_PATHS_CACHE_CAPACITY,\n      timeToLive: Exit.match({\n        onSuccess: (repositoryPaths) =>\n          repositoryPaths === null\n            ? NON_REPOSITORY_PATHS_CACHE_TTL\n            : REPOSITORY_PATHS_REFRESH_COALESCE_TTL,\n        onFailure: () => Duration.zero,\n      }),\n    },\n  );\n  const normalizeRepositoryPathsCacheKey = (cwd: string) => path.normalize(path.resolve(cwd));\n  const resolveRepositoryPaths = (cwd: string, refresh = false) => {\n    const cacheKey = normalizeRepositoryPathsCacheKey(cwd);\n    return Cache.get(refresh ? repositoryPathsRefreshCache : repositoryPathsCache, cacheKey);\n  };\n\n  const defaultBranchCache = yield* Cache.makeWith(\n    (gitCommonDir: string) =>\n      Effect.gen(function* () {\n        const path = yield* Path.Path;\n        const fetchCwd =\n          path.basename(gitCommonDir) === \".git\" ? path.dirname(gitCommonDir) : gitCommonDir;\n        return yield* executeGit(\n          \"GitVcsDriver.statusDetails.defaultBranch\",\n          fetchCwd,\n          [\"--git-dir\", gitCommonDir, \"symbolic-ref\", \"refs/remotes/origin/HEAD\"],\n          { allowNonZeroExit: true },\n        ).pipe(\n          Effect.map((result) => {\n            if (result.exitCode !== 0) return null;\n            return parseDefaultBranchFromRemoteHeadRef(result.stdout, \"origin\");\n          }),\n        );\n      }),\n    {\n      capacity: 2_048,\n      timeToLive: Exit.match({\n        onSuccess: () => STATUS_DEFAULT_BRANCH_CACHE_TTL,\n        onFailure: () => Duration.zero,\n      }),\n    },\n  );\n  const originExistsCache = yield* Cache.makeWith(\n    (gitCommonDir: string) =>\n      Effect.gen(function* () {\n        const path = yield* Path.Path;\n        const fetchCwd =\n          path.basename(gitCommonDir) === \".git\" ? path.dirname(gitCommonDir) : gitCommonDir;\n        return yield* executeGit(\n          \"GitVcsDriver.statusDetails.originExists\",\n          fetchCwd,\n          [\"--git-dir\", gitCommonDir, \"remote\", \"get-url\", \"origin\"],\n          { allowNonZeroExit: true },\n        ).pipe(Effect.map((result) => result.exitCode === 0));\n      }),\n    {\n      capacity: 2_048,\n      timeToLive: Exit.match({\n        onSuccess: () => STATUS_ORIGIN_EXISTS_CACHE_TTL,\n        onFailure: () => Duration.zero,\n      }),\n    },\n  );\n  const invalidateStatusStaticCaches = (cwd: string) =>\n    Effect.gen(function* () {\n      const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe(\n        Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),\n      );\n      const cacheKey = repositoryPaths?.gitCommonDir ?? normalizeRepositoryPathsCacheKey(cwd);\n      yield* Cache.invalidate(defaultBranchCache, cacheKey);\n      yield* Cache.invalidate(originExistsCache, cacheKey);\n    });\n\n  const resolveGitCommonDir = Effect.fn(\"resolveGitCommonDir\")(function* (cwd: string) {\n    const repositoryPaths = yield* resolveRepositoryPaths(cwd);\n    if (repositoryPaths !== null) {\n      return repositoryPaths.gitCommonDir;\n    }\n    return yield* new GitCommandError({\n      ...gitCommandContext({\n        operation: \"GitVcsDriver.resolveGitCommonDir\",\n        cwd,\n        args: [\"rev-parse\", \"--git-common-dir\"],\n      }),\n      detail: \"Cannot resolve a Git common directory outside a repository.\",\n    });\n  });\n\n  const statusRemoteRefreshFailureCounts = new Map<string, number>();\n  const statusRemoteRefreshFailureKey = (cacheKey: StatusRemoteRefreshCacheKey) =>\n    `${cacheKey.gitCommonDir}\\0${cacheKey.remoteName}`;\n  const recordStatusRemoteRefreshFailure = (cacheKey: StatusRemoteRefreshCacheKey) => {\n    const key = statusRemoteRefreshFailureKey(cacheKey);\n    const nextCount = (statusRemoteRefreshFailureCounts.get(key) ?? 0) + 1;\n    statusRemoteRefreshFailureCounts.delete(key);\n    statusRemoteRefreshFailureCounts.set(key, nextCount);\n    if (statusRemoteRefreshFailureCounts.size > STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY) {\n      const oldestKey = statusRemoteRefreshFailureCounts.keys().next().value;\n      if (oldestKey !== undefined) {\n        statusRemoteRefreshFailureCounts.delete(oldestKey);\n      }\n    }\n  };\n  const clearStatusRemoteRefreshFailures = (cacheKey: StatusRemoteRefreshCacheKey) => {\n    statusRemoteRefreshFailureCounts.delete(statusRemoteRefreshFailureKey(cacheKey));\n  };\n  const refreshStatusRemoteCacheEntry = Effect.fn(\"refreshStatusRemoteCacheEntry\")(function* (\n    cacheKey: StatusRemoteRefreshCacheKey,\n  ) {\n    return yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName).pipe(\n      Effect.tap(() => Effect.sync(() => clearStatusRemoteRefreshFailures(cacheKey))),\n      Effect.tapError(() => Effect.sync(() => recordStatusRemoteRefreshFailure(cacheKey))),\n      Effect.as(true as const),\n    );\n  });\n\n  const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {\n    capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,\n    // A failed background fetch is intentionally cached and exponentially\n    // backed off. Status reads swallow this failure and use the last fetched\n    // refs, so repeated thread mounts cannot turn a slow or unavailable remote\n    // into a repository-wide Git subprocess storm.\n    timeToLive: (exit, cacheKey) =>\n      Exit.isSuccess(exit)\n        ? STATUS_UPSTREAM_REFRESH_INTERVAL\n        : statusUpstreamRefreshFailureCooldown(\n            statusRemoteRefreshFailureCounts.get(statusRemoteRefreshFailureKey(cacheKey)) ?? 1,\n          ),\n  });\n\n  const refreshStatusUpstreamIfStale = Effect.fn(\"refreshStatusUpstreamIfStale\")(function* (\n    cwd: string,\n  ) {\n    const upstream = yield* resolveCurrentUpstream(cwd);\n    if (!upstream) return;\n    const gitCommonDir = yield* resolveGitCommonDir(cwd);\n    yield* Cache.get(\n      statusRemoteRefreshCache,\n      new StatusRemoteRefreshCacheKey({\n        gitCommonDir,\n        remoteName: upstream.remoteName,\n      }),\n    );\n  });\n\n  const resolveDefaultBranchName = (\n    cwd: string,\n    remoteName: string,\n  ): Effect.Effect<string | null, GitCommandError> =>\n    executeGit(\n      \"GitVcsDriver.resolveDefaultBranchName\",\n      cwd,\n      [\"symbolic-ref\", `refs/remotes/${remoteName}/HEAD`],\n      { allowNonZeroExit: true },\n    ).pipe(\n      Effect.map((result) => {\n        if (result.exitCode !== 0) {\n          return null;\n        }\n        return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName);\n      }),\n    );\n\n  const remoteBranchExists = (\n    cwd: string,\n    remoteName: string,\n    refName: string,\n  ): Effect.Effect<boolean, GitCommandError> =>\n    executeGit(\n      \"GitVcsDriver.remoteBranchExists\",\n      cwd,\n      [\"show-ref\", \"--verify\", \"--quiet\", `refs/remotes/${remoteName}/${refName}`],\n      {\n        allowNonZeroExit: true,\n      },\n    ).pipe(Effect.map((result) => result.exitCode === 0));\n\n  const remoteExists: GitVcsDriver.GitVcsDriver[\"Service\"][\"remoteExists\"] = (input) =>\n    executeGit(\"GitVcsDriver.remoteExists\", input.cwd, [\"remote\", \"get-url\", input.remoteName], {\n      allowNonZeroExit: true,\n    }).pipe(Effect.map((result) => result.exitCode === 0));\n\n  const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>\n    remoteExists({ cwd, remoteName: \"origin\" });\n\n  const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>\n    runGitStdout(\"GitVcsDriver.listRemoteNames\", cwd, [\"remote\"]).pipe(\n      Effect.map(parseRemoteNamesInGitOrder),\n    );\n\n  const resolvePublishBranchName = Effect.fn(\"resolvePublishBranchName\")(function* (\n    cwd: string,\n    branchName: string,\n  ) {\n    const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.orElseSucceed(() => []));\n    const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames);\n    return parsedRemoteRef?.branchName ?? branchName;\n  });\n\n  const resolvePrimaryRemoteName = Effect.fn(\"resolvePrimaryRemoteName\")(function* (cwd: string) {\n    if (yield* originRemoteExists(cwd)) {\n      return \"origin\";\n    }\n    const remotes = yield* listRemoteNames(cwd);\n    const [firstRemote] = remotes;\n    if (firstRemote) {\n      return firstRemote;\n    }\n    return yield* new GitCommandError({\n      ...gitCommandContext({\n        operation: \"GitVcsDriver.resolvePrimaryRemoteName\",\n        cwd,\n        args: [\"remote\"],\n      }),\n      detail: \"No git remote is configured for this repository.\",\n    });\n  });\n\n  const resolvePushRemoteName = Effect.fn(\"resolvePushRemoteName\")(function* (\n    cwd: string,\n    refName: string,\n  ) {\n    const branchPushRemote = yield* runGitStdout(\n      \"GitVcsDriver.resolvePushRemoteName.branchPushRemote\",\n      cwd,\n      [\"config\", \"--get\", `branch.${refName}.pushRemote`],\n      true,\n    ).pipe(Effect.map((stdout) => stdout.trim()));\n    if (branchPushRemote.length > 0) {\n      return branchPushRemote;\n    }\n\n    const pushDefaultRemote = yield* runGitStdout(\n      \"GitVcsDriver.resolvePushRemoteName.remotePushDefault\",\n      cwd,\n      [\"config\", \"--get\", \"remote.pushDefault\"],\n      true,\n    ).pipe(Effect.map((stdout) => stdout.trim()));\n    if (pushDefaultRemote.length > 0) {\n      return pushDefaultRemote;\n    }\n\n    return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.orElseSucceed(() => null));\n  });\n\n  const ensureRemote: GitVcsDriver.GitVcsDriver[\"Service\"][\"ensureRemote\"] = Effect.fn(\n    \"ensureRemote\",\n  )(function* (input) {\n    const preferredName = sanitizeRemoteName(input.preferredName);\n    const normalizedTargetUrl = normalizeGitRemoteUrl(input.url);\n    const remoteFetchUrls = yield* runGitStdout(\n      \"GitVcsDriver.ensureRemote.listRemoteUrls\",\n      input.cwd,\n      [\"remote\", \"-v\"],\n    ).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout)));\n\n    for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) {\n      if (normalizeGitRemoteUrl(remoteUrl) === normalizedTargetUrl) {\n        return remoteName;\n      }\n    }\n\n    let remoteName = preferredName;\n    let suffix = 1;\n    while (remoteFetchUrls.has(remoteName)) {\n      remoteName = `${preferredName}-${suffix}`;\n      suffix += 1;\n    }\n\n    yield* runGit(\"GitVcsDriver.ensureRemote.add\", input.cwd, [\n      \"remote\",\n      \"add\",\n      remoteName,\n      input.url,\n    ]);\n    return remoteName;\n  });\n\n  const resolveBaseBranchForNoUpstream = Effect.fn(\"resolveBaseBranchForNoUpstream\")(function* (\n    cwd: string,\n    refName: string,\n  ) {\n    const configuredBaseBranch = yield* runGitStdout(\n      \"GitVcsDriver.resolveBaseBranchForNoUpstream.config\",\n      cwd,\n      [\"config\", \"--get\", `branch.${refName}.gh-merge-base`],\n      true,\n    ).pipe(Effect.map((stdout) => stdout.trim()));\n\n    const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe(\n      Effect.orElseSucceed(() => null),\n    );\n    const defaultBranch =\n      primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName);\n    const candidates = [\n      configuredBaseBranch.length > 0 ? configuredBaseBranch : null,\n      defaultBranch,\n      ...DEFAULT_BASE_BRANCH_CANDIDATES,\n    ];\n\n    for (const candidate of candidates) {\n      if (!candidate) {\n        continue;\n      }\n\n      const remotePrefix =\n        primaryRemoteName && primaryRemoteName !== \"origin\" ? `${primaryRemoteName}/` : null;\n      const normalizedCandidate = candidate.startsWith(\"origin/\")\n        ? candidate.slice(\"origin/\".length)\n        : remotePrefix && candidate.startsWith(remotePrefix)\n          ? candidate.slice(remotePrefix.length)\n          : candidate;\n      if (normalizedCandidate.length === 0 || normalizedCandidate === refName) {\n        continue;\n      }\n\n      if (\n        primaryRemoteName &&\n        (yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate))\n      ) {\n        return `${primaryRemoteName}/${normalizedCandidate}`;\n      }\n\n      if (yield* branchExists(cwd, normalizedCandidate)) {\n        return normalizedCandidate;\n      }\n    }\n\n    return null;\n  });\n\n  const computeAheadCountAgainstBase = Effect.fn(\"computeAheadCountAgainstBase\")(function* (\n    cwd: string,\n    refName: string,\n  ) {\n    const baseRef = yield* resolveBaseBranchForNoUpstream(cwd, refName);\n    if (!baseRef) {\n      return 0;\n    }\n\n    const result = yield* executeGit(\n      \"GitVcsDriver.computeAheadCountAgainstBase\",\n      cwd,\n      [\"rev-list\", \"--count\", `${baseRef}..HEAD`],\n      { allowNonZeroExit: true },\n    );\n    if (result.exitCode !== 0) {\n      return 0;\n    }\n\n    const parsed = Number.parseInt(result.stdout.trim(), 10);\n    return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;\n  });\n\n  const readStatusDetailsRemote = Effect.fn(\"readStatusDetailsRemote\")(function* (cwd: string) {\n    const branchResult = yield* executeGitWithStableDiagnostics(\n      \"GitVcsDriver.statusDetailsRemote.branch\",\n      cwd,\n      [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"],\n      { allowNonZeroExit: true },\n    ).pipe(\n      Effect.catchTags({\n        GitCommandError: (error) =>\n          isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),\n      }),\n    );\n\n    if (branchResult === null) {\n      return NON_REPOSITORY_REMOTE_STATUS_DETAILS;\n    }\n    if (branchResult.exitCode !== 0) {\n      if (isNonRepositoryGitStderr(branchResult.stderr)) {\n        return NON_REPOSITORY_REMOTE_STATUS_DETAILS;\n      }\n      return yield* new GitCommandError({\n        ...gitCommandContext({\n          operation: \"GitVcsDriver.statusDetailsRemote.branch\",\n          cwd,\n          args: [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"],\n        }),\n        detail: \"Git branch lookup failed.\",\n        exitCode: branchResult.exitCode,\n        stdoutLength: branchResult.stdout.length,\n        stderrLength: branchResult.stderr.length,\n      });\n    }\n\n    const branchValue = branchResult.stdout.trim();\n    const branch = branchValue.length > 0 && branchValue !== \"HEAD\" ? branchValue : null;\n    const upstream = yield* resolveCurrentUpstream(cwd);\n    const upstreamRef = upstream?.upstreamRef ?? null;\n    let aheadCount = 0;\n    let behindCount = 0;\n\n    if (upstreamRef) {\n      const divergence = yield* executeGit(\n        \"GitVcsDriver.statusDetailsRemote.divergence\",\n        cwd,\n        [\"rev-list\", \"--left-right\", \"--count\", `HEAD...${upstreamRef}`],\n        { allowNonZeroExit: true },\n      );\n      if (divergence.exitCode === 0) {\n        const [aheadRaw, behindRaw] = divergence.stdout.trim().split(/\\s+/);\n        const parsedAhead = Number.parseInt(aheadRaw ?? \"0\", 10);\n        const parsedBehind = Number.parseInt(behindRaw ?? \"0\", 10);\n        aheadCount = Number.isFinite(parsedAhead) ? Math.max(0, parsedAhead) : 0;\n        behindCount = Number.isFinite(parsedBehind) ? Math.max(0, parsedBehind) : 0;\n      }\n    } else if (branch) {\n      aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(\n        Effect.orElseSucceed(() => 0),\n      );\n    }\n\n    const defaultBranch = yield* resolveDefaultBranchName(cwd, \"origin\");\n    const isDefaultBranch =\n      branch !== null &&\n      (branch === defaultBranch ||\n        (defaultBranch === null && (branch === \"main\" || branch === \"master\")));\n    const aheadOfDefaultCount =\n      branch && !isDefaultBranch\n        ? upstreamRef === null\n          ? aheadCount\n          : yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0))\n        : 0;\n\n    return {\n      isRepo: true,\n      isDefaultBranch,\n      branch,\n      upstreamRef,\n      hasUpstream: upstreamRef !== null,\n      aheadCount,\n      behindCount,\n      aheadOfDefaultCount,\n    };\n  });\n\n  const readStatusDetailsLocal = Effect.fn(\"readStatusDetailsLocal\")(function* (cwd: string) {\n    const statusResult = yield* executeGitWithStableDiagnostics(\n      \"GitVcsDriver.statusDetails.status\",\n      cwd,\n      [\"status\", \"--porcelain=2\", \"--branch\"],\n      {\n        allowNonZeroExit: true,\n      },\n    ).pipe(\n      Effect.catchTags({\n        GitCommandError: (error) =>\n          isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),\n      }),\n    );\n\n    if (statusResult === null) {\n      return NON_REPOSITORY_STATUS_DETAILS;\n    }\n\n    if (statusResult.exitCode !== 0) {\n      if (isNonRepositoryGitStderr(statusResult.stderr)) {\n        return NON_REPOSITORY_STATUS_DETAILS;\n      }\n      return yield* new GitCommandError({\n        ...gitCommandContext({\n          operation: \"GitVcsDriver.statusDetails.status\",\n          cwd,\n          args: [\"status\", \"--porcelain=2\", \"--branch\"],\n        }),\n        detail: \"Git status failed.\",\n        exitCode: statusResult.exitCode,\n        stdoutLength: statusResult.stdout.length,\n        stderrLength: statusResult.stderr.length,\n      });\n    }\n\n    const repositoryPaths = yield* resolveRepositoryPaths(cwd).pipe(\n      Effect.catchTags({ GitCommandError: () => Effect.succeed(null) }),\n    );\n    const statusCacheKey = repositoryPaths?.gitCommonDir;\n    const [numstatStdout, defaultBranch, hasPrimaryRemote] = yield* Effect.all(\n      [\n        executeGitWithStableDiagnostics(\n          \"GitVcsDriver.statusDetails.numstat\",\n          cwd,\n          [\"diff\", \"HEAD\", \"--numstat\"],\n          { allowNonZeroExit: true },\n        ).pipe(\n          Effect.flatMap((result) => {\n            if (result.exitCode === 0) return Effect.succeed(result.stdout);\n            if (isUnbornHeadStderr(result.stderr)) {\n              return Effect.map(\n                Effect.all([\n                  runGitStdout(\"GitVcsDriver.statusDetails.numstat.unborn\", cwd, [\n                    \"diff\",\n                    \"--numstat\",\n                  ]),\n                  runGitStdout(\"GitVcsDriver.statusDetails.numstat.unborn.staged\", cwd, [\n                    \"diff\",\n                    \"--cached\",\n                    \"--numstat\",\n                  ]),\n                ]),\n                ([unstagedStdout, stagedStdout]) => {\n                  const staged = parseNumstatEntries(stagedStdout);\n                  const unstaged = parseNumstatEntries(unstagedStdout);\n                  const map = new Map<string, { insertions: number; deletions: number }>();\n                  for (const entry of [...staged, ...unstaged]) {\n                    const existing = map.get(entry.path) ?? {\n                      insertions: 0,\n                      deletions: 0,\n                    };\n                    existing.insertions += entry.insertions;\n                    existing.deletions += entry.deletions;\n                    map.set(entry.path, existing);\n                  }\n                  return Array.from(map.entries())\n                    .map(([p, s]) => `${s.insertions}\\t${s.deletions}\\t${p}`)\n                    .join(\"\\n\");\n                },\n              );\n            }\n            return Effect.fail(\n              new GitCommandError({\n                ...gitCommandContext({\n                  operation: \"GitVcsDriver.statusDetails.numstat\",\n                  cwd,\n                  args: [\"diff\", \"HEAD\", \"--numstat\"],\n                }),\n                detail: \"git diff HEAD --numstat failed.\",\n                exitCode: result.exitCode,\n                stdoutLength: result.stdout.length,\n                stderrLength: result.stderr.length,\n              }),\n            );\n          }),\n        ),\n        statusCacheKey\n          ? Cache.get(defaultBranchCache, statusCacheKey).pipe(Effect.orElseSucceed(() => null))\n          : resolveDefaultBranchName(cwd, \"origin\").pipe(Effect.orElseSucceed(() => null)),\n        statusCacheKey\n          ? Cache.get(originExistsCache, statusCacheKey).pipe(Effect.orElseSucceed(() => false))\n          : originRemoteExists(cwd).pipe(Effect.orElseSucceed(() => false)),\n      ],\n      { concurrency: \"unbounded\" },\n    );\n    const statusStdout = statusResult.stdout;\n\n    let refName: string | null = null;\n    let upstreamRef: string | null = null;\n    let aheadCount = 0;\n    let behindCount = 0;\n    let aheadOfDefaultCount = 0;\n    let hasWorkingTreeChanges = false;\n    const changedFilesWithoutNumstat = new Set<string>();\n\n    for (const line of statusStdout.split(/\\r?\\n/g)) {\n      if (line.startsWith(\"# branch.head \")) {\n        const value = line.slice(\"# branch.head \".length).trim();\n        refName = value.startsWith(\"(\") ? null : value;\n        continue;\n      }\n      if (line.startsWith(\"# branch.upstream \")) {\n        const value = line.slice(\"# branch.upstream \".length).trim();\n        upstreamRef = value.length > 0 ? value : null;\n        continue;\n      }\n      if (line.startsWith(\"# branch.ab \")) {\n        const value = line.slice(\"# branch.ab \".length).trim();\n        const parsed = parseBranchAb(value);\n        aheadCount = parsed.ahead;\n        behindCount = parsed.behind;\n        continue;\n      }\n      if (line.trim().length > 0 && !line.startsWith(\"#\")) {\n        hasWorkingTreeChanges = true;\n        const pathValue = parsePorcelainPath(line);\n        if (pathValue) changedFilesWithoutNumstat.add(pathValue);\n      }\n    }\n\n    const fallbackAheadCount =\n      !upstreamRef && refName\n        ? yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0))\n        : null;\n\n    if (fallbackAheadCount !== null) {\n      aheadCount = fallbackAheadCount;\n      behindCount = 0;\n    }\n\n    const isDefaultBranch =\n      refName !== null &&\n      (refName === defaultBranch ||\n        (defaultBranch === null && (refName === \"main\" || refName === \"master\")));\n    if (refName && !isDefaultBranch) {\n      aheadOfDefaultCount =\n        fallbackAheadCount !== null\n          ? fallbackAheadCount\n          : yield* computeAheadCountAgainstBase(cwd, refName).pipe(Effect.orElseSucceed(() => 0));\n    }\n\n    const numstatEntries = parseNumstatEntries(numstatStdout);\n    const fileStatMap = new Map<string, { insertions: number; deletions: number }>();\n    for (const entry of numstatEntries) {\n      fileStatMap.set(entry.path, { insertions: entry.insertions, deletions: entry.deletions });\n    }\n\n    let insertions = 0;\n    let deletions = 0;\n    const files = Array.from(fileStatMap.entries())\n      .map(([filePath, stat]) => {\n        insertions += stat.insertions;\n        deletions += stat.deletions;\n        return { path: filePath, insertions: stat.insertions, deletions: stat.deletions };\n      })\n      .toSorted((a, b) => a.path.localeCompare(b.path));\n\n    for (const filePath of changedFilesWithoutNumstat) {\n      if (fileStatMap.has(filePath)) continue;\n      files.push({ path: filePath, insertions: 0, deletions: 0 });\n    }\n    files.sort((a, b) => a.path.localeCompare(b.path));\n\n    return {\n      isRepo: true,\n      hasOriginRemote: hasPrimaryRemote,\n      isDefaultBranch,\n      branch: refName,\n      upstreamRef,\n      hasWorkingTreeChanges,\n      workingTree: {\n        files,\n        insertions,\n        deletions,\n      },\n      hasUpstream: upstreamRef !== null,\n      aheadCount,\n      behindCount,\n      aheadOfDefaultCount,\n    };\n  });\n\n  const statusDetailsLocal: GitVcsDriver.GitVcsDriver[\"Service\"][\"statusDetailsLocal\"] = Effect.fn(\n    \"statusDetailsLocal\",\n  )(function* (cwd) {\n    return yield* readStatusDetailsLocal(cwd);\n  });\n\n  const statusDetails: GitVcsDriver.GitVcsDriver[\"Service\"][\"statusDetails\"] = Effect.fn(\n    \"statusDetails\",\n  )(function* (cwd) {\n    yield* refreshStatusUpstreamIfStale(cwd).pipe(\n      Effect.catchTags({\n        GitCommandError: (error) =>\n          isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),\n      }),\n      Effect.ignoreCause({ log: true }),\n    );\n    return yield* readStatusDetailsLocal(cwd);\n  });\n\n  const statusDetailsRemote: GitVcsDriver.GitVcsDriver[\"Service\"][\"statusDetailsRemote\"] =\n    Effect.fn(\"statusDetailsRemote\")(function* (cwd, options) {\n      if (options?.refreshUpstream !== false) {\n        yield* refreshStatusUpstreamIfStale(cwd).pipe(\n          Effect.catchTags({\n            GitCommandError: (error) =>\n              isMissingGitCwdError(error) ? Effect.void : Effect.fail(error),\n          }),\n          Effect.ignoreCause({ log: true }),\n        );\n      }\n      return yield* readStatusDetailsRemote(cwd);\n    });\n\n  const status: GitVcsDriver.GitVcsDriver[\"Service\"][\"status\"] = (input) =>\n    statusDetails(input.cwd).pipe(\n      Effect.map((details) => ({\n        isRepo: details.isRepo,\n        hasPrimaryRemote: details.hasOriginRemote,\n        isDefaultRef: details.isDefaultBranch,\n        refName: details.branch,\n        hasWorkingTreeChanges: details.hasWorkingTreeChanges,\n        workingTree: details.workingTree,\n        hasUpstream: details.hasUpstream,\n        aheadCount: details.aheadCount,\n        behindCount: details.behindCount,\n        aheadOfDefaultCount: details.aheadOfDefaultCount,\n        pr: null,\n      })),\n    );\n\n  const prepareCommitContext: GitVcsDriver.GitVcsDriver[\"Service\"][\"prepareCommitContext\"] =\n    Effect.fn(\"prepareCommitContext\")(function* (cwd, filePaths) {\n      if (filePaths && filePaths.length > 0) {\n        yield* runGit(\"GitVcsDriver.prepareCommitContext.reset\", cwd, [\"reset\"]).pipe(\n          Effect.catchTags({\n            GitCommandError: () => Effect.void,\n          }),\n        );\n        yield* runGit(\"GitVcsDriver.prepareCommitContext.addSelected\", cwd, [\n          \"--literal-pathspecs\",\n          \"add\",\n          \"-A\",\n          \"--\",\n          ...filePaths,\n        ]);\n      } else {\n        yield* runGit(\"GitVcsDriver.prepareCommitContext.addAll\", cwd, [\"add\", \"-A\"]);\n      }\n\n      const stagedSummary = yield* runGitStdout(\n        \"GitVcsDriver.prepareCommitContext.stagedSummary\",\n        cwd,\n        [\"diff\", \"--cached\", \"--name-status\"],\n      ).pipe(Effect.map((stdout) => stdout.trim()));\n      if (stagedSummary.length === 0) {\n        return null;\n      }\n\n      const stagedPatch = yield* runGitStdoutWithOptions(\n        \"GitVcsDriver.prepareCommitContext.stagedPatch\",\n        cwd,\n        [\"diff\", \"--no-ext-diff\", \"--cached\", \"--patch\", \"--minimal\"],\n        {\n          maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES,\n          appendTruncationMarker: true,\n        },\n      );\n\n      return {\n        stagedSummary,\n        stagedPatch,\n      };\n    });\n\n  const commit: GitVcsDriver.GitVcsDriver[\"Service\"][\"commit\"] = Effect.fn(\"commit\")(function* (\n    cwd,\n    subject,\n    body,\n    options?: GitVcsDriver.GitCommitOptions,\n  ) {\n    const args = [\"commit\", \"-m\", subject];\n    const trimmedBody = body.trim();\n    if (trimmedBody.length > 0) {\n      args.push(\"-m\", trimmedBody);\n    }\n    const progress =\n      options?.progress?.onOutputLine === undefined\n        ? options?.progress\n        : {\n            ...options.progress,\n            onStdoutLine: (line: string) =>\n              options.progress?.onOutputLine?.({ stream: \"stdout\", text: line }) ?? Effect.void,\n            onStderrLine: (line: string) =>\n              options.progress?.onOutputLine?.({ stream: \"stderr\", text: line }) ?? Effect.void,\n          };\n    yield* executeGit(\"GitVcsDriver.commit.commit\", cwd, args, {\n      ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n      ...(progress ? { progress } : {}),\n    }).pipe(Effect.asVoid);\n    const commitSha = yield* runGitStdout(\"GitVcsDriver.commit.revParseHead\", cwd, [\n      \"rev-parse\",\n      \"HEAD\",\n    ]).pipe(Effect.map((stdout) => stdout.trim()));\n\n    return { commitSha };\n  });\n\n  const pushCurrentBranch: GitVcsDriver.GitVcsDriver[\"Service\"][\"pushCurrentBranch\"] = Effect.fn(\n    \"pushCurrentBranch\",\n  )(function* (cwd, fallbackBranch, options) {\n    const details = yield* statusDetails(cwd);\n    const branch = details.branch ?? fallbackBranch;\n    if (!branch) {\n      return yield* new GitCommandError({\n        ...gitCommandContext({\n          operation: \"GitVcsDriver.pushCurrentBranch\",\n          cwd,\n          args: [\"push\"],\n        }),\n        detail: \"Cannot push from detached HEAD.\",\n      });\n    }\n\n    const requestedRemoteName = options?.remoteName?.trim() || null;\n    if (requestedRemoteName) {\n      const publishBranch = yield* resolvePublishBranchName(cwd, branch);\n      yield* runGit(\"GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote\", cwd, [\n        \"push\",\n        \"-u\",\n        requestedRemoteName,\n        `HEAD:refs/heads/${publishBranch}`,\n      ]);\n      return {\n        status: \"pushed\" as const,\n        branch,\n        upstreamBranch: `${requestedRemoteName}/${publishBranch}`,\n        setUpstream: true,\n      };\n    }\n\n    const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;\n    if (hasNoLocalDelta) {\n      if (details.hasUpstream) {\n        return {\n          status: \"skipped_up_to_date\" as const,\n          branch,\n          ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),\n        };\n      }\n\n      const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(\n        Effect.orElseSucceed(() => null),\n      );\n      if (comparableBaseBranch) {\n        const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe(\n          Effect.orElseSucceed(() => null),\n        );\n        if (!publishRemoteName) {\n          return {\n            status: \"skipped_up_to_date\" as const,\n            branch,\n          };\n        }\n\n        const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe(\n          Effect.orElseSucceed(() => false),\n        );\n        if (hasRemoteBranch) {\n          return {\n            status: \"skipped_up_to_date\" as const,\n            branch,\n          };\n        }\n      }\n    }\n\n    if (!details.hasUpstream) {\n      const publishRemoteName = yield* resolvePushRemoteName(cwd, branch);\n      if (!publishRemoteName) {\n        return yield* new GitCommandError({\n          ...gitCommandContext({\n            operation: \"GitVcsDriver.pushCurrentBranch\",\n            cwd,\n            args: [\"push\"],\n          }),\n          detail: \"Cannot push because no git remote is configured for this repository.\",\n        });\n      }\n      const publishBranch = yield* resolvePublishBranchName(cwd, branch);\n      yield* runGit(\"GitVcsDriver.pushCurrentBranch.pushWithUpstream\", cwd, [\n        \"push\",\n        \"-u\",\n        publishRemoteName,\n        `HEAD:refs/heads/${publishBranch}`,\n      ]);\n      return {\n        status: \"pushed\" as const,\n        branch,\n        upstreamBranch: `${publishRemoteName}/${publishBranch}`,\n        setUpstream: true,\n      };\n    }\n\n    const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe(\n      Effect.orElseSucceed(() => null),\n    );\n    if (currentUpstream) {\n      yield* runGit(\"GitVcsDriver.pushCurrentBranch.pushUpstream\", cwd, [\n        \"push\",\n        currentUpstream.remoteName,\n        `HEAD:refs/heads/${currentUpstream.branchName}`,\n      ]);\n      return {\n        status: \"pushed\" as const,\n        branch,\n        upstreamBranch: currentUpstream.upstreamRef,\n        setUpstream: false,\n      };\n    }\n\n    yield* runGit(\"GitVcsDriver.pushCurrentBranch.push\", cwd, [\"push\"]);\n    return {\n      status: \"pushed\" as const,\n      branch,\n      ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),\n      setUpstream: false,\n    };\n  });\n\n  const pullCurrentBranch: GitVcsDriver.GitVcsDriver[\"Service\"][\"pullCurrentBranch\"] = Effect.fn(\n    \"pullCurrentBranch\",\n  )(function* (cwd) {\n    const details = yield* statusDetails(cwd);\n    const refName = details.branch;\n    if (!refName) {\n      return yield* new GitCommandError({\n        ...gitCommandContext({\n          operation: \"GitVcsDriver.pullCurrentBranch\",\n          cwd,\n          args: [\"pull\", \"--ff-only\"],\n        }),\n        detail: \"Cannot pull from detached HEAD.\",\n      });\n    }\n    if (!details.hasUpstream) {\n      return yield* new GitCommandError({\n        ...gitCommandContext({\n          operation: \"GitVcsDriver.pullCurrentBranch\",\n          cwd,\n          args: [\"pull\", \"--ff-only\"],\n        }),\n        detail: \"Current branch has no upstream configured. Push with upstream first.\",\n      });\n    }\n    const beforeSha = yield* runGitStdout(\n      \"GitVcsDriver.pullCurrentBranch.beforeSha\",\n      cwd,\n      [\"rev-parse\", \"HEAD\"],\n      true,\n    ).pipe(Effect.map((stdout) => stdout.trim()));\n    yield* executeGit(\"GitVcsDriver.pullCurrentBranch.pull\", cwd, [\"pull\", \"--ff-only\"], {\n      timeoutMs: 30_000,\n      fallbackErrorDetail: \"git pull failed\",\n    });\n    const afterSha = yield* runGitStdout(\n      \"GitVcsDriver.pullCurrentBranch.afterSha\",\n      cwd,\n      [\"rev-parse\", \"HEAD\"],\n      true,\n    ).pipe(Effect.map((stdout) => stdout.trim()));\n\n    const refreshed = yield* statusDetails(cwd);\n    return {\n      status: beforeSha.length > 0 && beforeSha === afterSha ? \"skipped_up_to_date\" : \"pulled\",\n      refName,\n      upstreamRef: refreshed.upstreamRef,\n    };\n  });\n\n  const readRangeContext: GitVcsDriver.GitVcsDriver[\"Service\"][\"readRangeContext\"] = Effect.fn(\n    \"readRangeContext\",\n  )(function* (cwd, baseRef) {\n    const range = `${baseRef}..HEAD`;\n    const [commitSummary, diffSummary, diffPatch] = yield* Effect.all(\n      [\n        runGitStdoutWithOptions(\n          \"GitVcsDriver.readRangeContext.log\",\n          cwd,\n          [\"log\", \"--oneline\", range],\n          {\n            maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES,\n            appendTruncationMarker: true,\n          },\n        ),\n        runGitStdoutWithOptions(\n          \"GitVcsDriver.readRangeContext.diffStat\",\n          cwd,\n          [\"diff\", \"--stat\", range],\n          {\n            maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES,\n            appendTruncationMarker: true,\n          },\n        ),\n        runGitStdoutWithOptions(\n          \"GitVcsDriver.readRangeContext.diffPatch\",\n          cwd,\n          [\"diff\", \"--no-ext-diff\", \"--patch\", \"--minimal\", range],\n          {\n            maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES,\n            appendTruncationMarker: true,\n          },\n        ),\n      ],\n      { concurrency: \"unbounded\" },\n    );\n\n    return {\n      commitSummary,\n      diffSummary,\n      diffPatch,\n    };\n  });\n\n  const readUntrackedReviewDiffs = Effect.fn(\"readUntrackedReviewDiffs\")(function* (cwd: string) {\n    const untrackedResult = yield* executeGit(\n      \"GitVcsDriver.readUntrackedReviewDiffs.list\",\n      cwd,\n      [\"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"],\n      {\n        maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,\n        appendTruncationMarker: true,\n      },\n    );\n    const untrackedPaths = splitNullSeparatedGitStdoutPaths(untrackedResult);\n    if (untrackedPaths.length === 0) {\n      return { diff: \"\", truncated: untrackedResult.stdoutTruncated };\n    }\n\n    const diffs = yield* Effect.forEach(\n      untrackedPaths,\n      (relativePath) =>\n        executeGit(\n          \"GitVcsDriver.readUntrackedReviewDiffs.diff\",\n          cwd,\n          [\n            \"diff\",\n            \"--no-index\",\n            \"--patch\",\n            \"--no-color\",\n            \"--no-ext-diff\",\n            \"--no-textconv\",\n            \"--minimal\",\n            \"--\",\n            \"/dev/null\",\n            relativePath,\n          ],\n          {\n            allowNonZeroExit: true,\n            maxOutputBytes: REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES,\n            appendTruncationMarker: true,\n          },\n        ),\n      { concurrency: 4 },\n    );\n\n    return {\n      diff: Arr.filterMap(diffs, (result) =>\n        result.stdout.trim().length > 0 ? Result.succeed(result.stdout) : Result.failVoid,\n      ).join(\"\\n\"),\n      truncated: untrackedResult.stdoutTruncated || diffs.some((result) => result.stdoutTruncated),\n    };\n  });\n\n  const getReviewDiffPreview = Effect.fn(\"getReviewDiffPreview\")(function* (\n    input: ReviewDiffPreviewInput,\n  ) {\n    const details = yield* statusDetailsLocal(input.cwd);\n    if (!details.isRepo) {\n      return {\n        cwd: input.cwd,\n        generatedAt: yield* DateTime.now,\n        sources: [],\n      };\n    }\n\n    const branch = details.branch;\n    const baseRef =\n      input.baseRef ??\n      (branch\n        ? yield* resolveBaseBranchForNoUpstream(input.cwd, branch).pipe(\n            Effect.orElseSucceed(() => null),\n          )\n        : null);\n\n    const dirtyTrackedResult = yield* executeGit(\n      \"GitVcsDriver.getReviewDiffPreview.dirtyTracked\",\n      input.cwd,\n      [\n        \"diff\",\n        \"--patch\",\n        \"--no-color\",\n        \"--no-ext-diff\",\n        \"--no-textconv\",\n        \"--minimal\",\n        ...(input.ignoreWhitespace ? [\"--ignore-all-space\"] : []),\n        \"HEAD\",\n        \"--\",\n      ],\n      {\n        maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES,\n        appendTruncationMarker: true,\n      },\n    ).pipe(\n      Effect.orElseSucceed(() => ({\n        exitCode: 0,\n        stdout: \"\",\n        stderr: \"\",\n        stdoutTruncated: false,\n        stderrTruncated: false,\n      })),\n    );\n    const dirtyUntracked = yield* readUntrackedReviewDiffs(input.cwd).pipe(\n      Effect.orElseSucceed(() => ({ diff: \"\", truncated: false })),\n    );\n    const dirtyDiff = [dirtyTrackedResult.stdout.trimEnd(), dirtyUntracked.diff.trimEnd()]\n      .filter((diff) => diff.length > 0)\n      .join(\"\\n\");\n\n    const baseResult =\n      baseRef && branch\n        ? yield* executeGit(\n            \"GitVcsDriver.getReviewDiffPreview.base\",\n            input.cwd,\n            [\n              \"diff\",\n              \"--patch\",\n              \"--no-color\",\n              \"--no-ext-diff\",\n              \"--no-textconv\",\n              \"--minimal\",\n              ...(input.ignoreWhitespace ? [\"--ignore-all-space\"] : []),\n              `${baseRef}...HEAD`,\n            ],\n            {\n              maxOutputBytes: REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES,\n              appendTruncationMarker: true,\n            },\n          ).pipe(\n            Effect.orElseSucceed(() => ({\n              exitCode: 0,\n              stdout: \"\",\n              stderr: \"\",\n              stdoutTruncated: false,\n              stderrTruncated: false,\n            })),\n          )\n        : null;\n    const baseDiff = baseResult?.stdout ?? \"\";\n    const hashDiff = (diff: string) =>\n      crypto.digest(\"SHA-256\", new TextEncoder().encode(diff)).pipe(\n        Effect.map(Encoding.encodeHex),\n        Effect.mapError(\n          (cause) =>\n            new GitCommandError({\n              operation: \"GitVcsDriver.getReviewDiffPreview.hash\",\n              command: \"crypto.digest SHA-256\",\n              cwd: input.cwd,\n              detail: \"Failed to hash review diff.\",\n              cause,\n            }),\n        ),\n      );\n    const [dirtyDiffHash, baseDiffHash] = yield* Effect.all([\n      hashDiff(dirtyDiff),\n      hashDiff(baseDiff),\n    ]);\n\n    const sources: ReviewDiffPreviewSource[] = [\n      {\n        id: \"working-tree\",\n        kind: \"working-tree\",\n        title: \"Dirty worktree\",\n        baseRef: \"HEAD\",\n        headRef: null,\n        diff: dirtyDiff,\n        diffHash: dirtyDiffHash,\n        truncated: dirtyTrackedResult.stdoutTruncated || dirtyUntracked.truncated,\n      },\n      {\n        id: \"branch-range\",\n        kind: \"branch-range\",\n        title: baseRef ? `Against ${baseRef}` : \"Against base branch\",\n        baseRef,\n        headRef: branch ?? \"HEAD\",\n        diff: baseDiff,\n        diffHash: baseDiffHash,\n        truncated: baseResult?.stdoutTruncated ?? false,\n      },\n    ];\n\n    return {\n      cwd: input.cwd,\n      generatedAt: yield* DateTime.now,\n      sources,\n    };\n  });\n\n  const reviewDiffFileError = (\n    input: ReviewDiffFileContentsInput,\n    detail: string,\n    cause?: unknown,\n  ) =>\n    new GitCommandError({\n      operation: \"GitVcsDriver.getReviewDiffFileContents\",\n      command: \"git\",\n      cwd: input.cwd,\n      detail,\n      ...(cause === undefined ? {} : { cause }),\n    });\n\n  const isPathWithinRoot = (root: string, candidate: string) => {\n    const relative = path.relative(root, candidate);\n    return (\n      relative === \"\" ||\n      (relative !== \"..\" && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))\n    );\n  };\n\n  const readReviewFileAtRevision = Effect.fn(\"readReviewFileAtRevision\")(function* (\n    input: ReviewDiffFileContentsInput,\n    revision: string,\n    relativePath: string,\n  ) {\n    const result = yield* executeGit(\n      \"GitVcsDriver.getReviewDiffFileContents.revision\",\n      input.cwd,\n      [\"show\", `${revision}:${relativePath}`],\n      { maxOutputBytes: REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES },\n    );\n    if (result.stdout.includes(\"\\0\")) {\n      return yield* reviewDiffFileError(input, `Cannot expand binary file '${relativePath}'.`);\n    }\n    return result.stdout;\n  });\n\n  const readWorkingTreeReviewFile = Effect.fn(\"readWorkingTreeReviewFile\")(function* (\n    input: ReviewDiffFileContentsInput,\n    repositoryRoot: string,\n  ) {\n    const fileError = (stage: string, detail: string, cause?: unknown) =>\n      new GitCommandError({\n        operation: `GitVcsDriver.getReviewDiffFileContents.workingTree.${stage}`,\n        command: stage,\n        cwd: input.cwd,\n        detail,\n        ...(cause === undefined ? {} : { cause }),\n      });\n    const requestedPath = path.resolve(repositoryRoot, input.newPath);\n    if (!isPathWithinRoot(repositoryRoot, requestedPath)) {\n      return yield* fileError(\n        \"path.resolve\",\n        `Diff file '${input.newPath}' resolves outside the review workspace.`,\n      );\n    }\n\n    const [realRepositoryRoot, realTarget] = yield* Effect.all([\n      fileSystem.realPath(repositoryRoot),\n      fileSystem.realPath(requestedPath),\n    ]).pipe(\n      Effect.mapError((cause) =>\n        fileError(\"fs.realPath\", `Could not resolve diff file '${input.newPath}'.`, cause),\n      ),\n    );\n    if (!isPathWithinRoot(realRepositoryRoot, realTarget)) {\n      return yield* fileError(\n        \"fs.realPath\",\n        `Diff file '${input.newPath}' resolves outside the review workspace.`,\n      );\n    }\n\n    const info = yield* fileSystem\n      .stat(realTarget)\n      .pipe(\n        Effect.mapError((cause) =>\n          fileError(\"fs.stat\", `Could not inspect diff file '${input.newPath}'.`, cause),\n        ),\n      );\n    if (info.type !== \"File\") {\n      return yield* fileError(\"fs.stat\", `Diff path '${input.newPath}' is not a file.`);\n    }\n    if (info.size > BigInt(REVIEW_DIFF_FILE_MAX_OUTPUT_BYTES)) {\n      return yield* fileError(\n        \"fs.stat\",\n        `Diff file '${input.newPath}' exceeds the 1 MB expansion limit.`,\n      );\n    }\n\n    const bytes = yield* fileSystem\n      .readFile(realTarget)\n      .pipe(\n        Effect.mapError((cause) =>\n          fileError(\"fs.readFile\", `Could not read diff file '${input.newPath}'.`, cause),\n        ),\n      );\n    if (bytes.includes(0)) {\n      return yield* fileError(\"fs.readFile\", `Cannot expand binary file '${input.newPath}'.`);\n    }\n    return new TextDecoder(\"utf-8\").decode(bytes);\n  });\n\n  const getReviewDiffFileContents = Effect.fn(\"getReviewDiffFileContents\")(function* (\n    input: ReviewDiffFileContentsInput,\n  ) {\n    if (input.sourceKind === \"working-tree\") {\n      const repositoryRoot = yield* runGitStdout(\n        \"GitVcsDriver.getReviewDiffFileContents.repositoryRoot\",\n        input.cwd,\n        [\"rev-parse\", \"--show-toplevel\"],\n      ).pipe(Effect.map((value) => value.trim()));\n      if (repositoryRoot.length === 0) {\n        return yield* reviewDiffFileError(input, \"Could not resolve the Git repository root.\");\n      }\n      const [oldContents, newContents] = yield* Effect.all(\n        [\n          input.changeType === \"new\"\n            ? Effect.succeed(\"\")\n            : readReviewFileAtRevision(input, input.baseRef ?? \"HEAD\", input.oldPath),\n          input.changeType === \"deleted\"\n            ? Effect.succeed(\"\")\n            : readWorkingTreeReviewFile(input, repositoryRoot),\n        ],\n        { concurrency: 2 },\n      );\n      return { oldContents, newContents };\n    }\n\n    if (!input.baseRef || !input.headRef) {\n      return yield* reviewDiffFileError(\n        input,\n        \"Branch diff file expansion requires both base and head refs.\",\n      );\n    }\n    const mergeBase = yield* runGitStdout(\n      \"GitVcsDriver.getReviewDiffFileContents.mergeBase\",\n      input.cwd,\n      [\"merge-base\", input.baseRef, input.headRef],\n    ).pipe(Effect.map((value) => value.trim()));\n    if (mergeBase.length === 0) {\n      return yield* reviewDiffFileError(input, \"Could not resolve the branch comparison base.\");\n    }\n    const [oldContents, newContents] = yield* Effect.all(\n      [\n        input.changeType === \"new\"\n          ? Effect.succeed(\"\")\n          : readReviewFileAtRevision(input, mergeBase, input.oldPath),\n        input.changeType === \"deleted\"\n          ? Effect.succeed(\"\")\n          : readReviewFileAtRevision(input, input.headRef, input.newPath),\n      ],\n      { concurrency: 2 },\n    );\n    return { oldContents, newContents };\n  });\n\n  const readConfigValue: GitVcsDriver.GitVcsDriver[\"Service\"][\"readConfigValue\"] = (cwd, key) =>\n    runGitStdout(\"GitVcsDriver.readConfigValue\", cwd, [\"config\", \"--get\", key], true).pipe(\n      Effect.map((stdout) => stdout.trim()),\n      Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),\n    );\n\n  const readGitRefsSnapshot = Effect.fn(\"readGitRefsSnapshot\")(function* (gitCommonDir: string) {\n    const fetchCwd =\n      path.basename(gitCommonDir) === \".git\" ? path.dirname(gitCommonDir) : gitCommonDir;\n    const gitDirArgs = [\"--git-dir\", gitCommonDir] as const;\n    const [refsResult, defaultRefResult, worktreeListResult, remoteNamesResult] = yield* Effect.all(\n      [\n        executeGitWithStableDiagnostics(\n          \"GitVcsDriver.listRefs.snapshotRefs\",\n          fetchCwd,\n          [\n            ...gitDirArgs,\n            \"for-each-ref\",\n            \"--format=%(refname)%09%(committerdate:unix)%09%(symref)\",\n            \"refs/heads\",\n            \"refs/remotes\",\n          ],\n          {\n            timeoutMs: 30_000,\n            maxOutputBytes: 16 * 1024 * 1024,\n            fallbackErrorDetail: \"Git ref snapshot enumeration failed.\",\n          },\n        ),\n        executeGit(\n          \"GitVcsDriver.listRefs.defaultRef\",\n          fetchCwd,\n          [...gitDirArgs, \"symbolic-ref\", \"refs/remotes/origin/HEAD\"],\n          {\n            timeoutMs: 5_000,\n            allowNonZeroExit: true,\n          },\n        ),\n        executeGit(\n          \"GitVcsDriver.listRefs.worktreeList\",\n          fetchCwd,\n          [...gitDirArgs, \"worktree\", \"list\", \"--porcelain\", \"-z\"],\n          {\n            timeoutMs: 30_000,\n            allowNonZeroExit: true,\n            maxOutputBytes: 16 * 1024 * 1024,\n          },\n        ),\n        executeGit(\"GitVcsDriver.listRefs.remoteNames\", fetchCwd, [...gitDirArgs, \"remote\"], {\n          timeoutMs: 5_000,\n          allowNonZeroExit: true,\n        }),\n      ],\n      { concurrency: 2 },\n    );\n\n    const remoteNames =\n      remoteNamesResult.exitCode === 0 ? parseRemoteNames(remoteNamesResult.stdout) : [];\n    if (remoteNamesResult.exitCode !== 0 && remoteNamesResult.stderr.trim().length > 0) {\n      yield* Effect.logWarning(\n        `GitVcsDriver.listRefs: remote name lookup returned code ${remoteNamesResult.exitCode} for ${gitCommonDir}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`,\n      );\n    }\n    const defaultBranch =\n      defaultRefResult.exitCode === 0\n        ? defaultRefResult.stdout.trim().replace(/^refs\\/remotes\\/origin\\//, \"\")\n        : null;\n    const parsedWorktreeEntries =\n      worktreeListResult.exitCode === 0\n        ? [...parseWorktreeBranchPaths(worktreeListResult.stdout)].map(\n            ([branchName, worktreePath]) =>\n              [branchName, path.normalize(path.resolve(worktreePath))] as const,\n          )\n        : [];\n    const existingWorktreeEntries = yield* Effect.filter(\n      parsedWorktreeEntries,\n      ([, worktreePath]) =>\n        fileSystem.stat(worktreePath).pipe(\n          Effect.as(true),\n          Effect.orElseSucceed(() => false),\n        ),\n      { concurrency: 16 },\n    );\n    const worktreeMap = new Map(existingWorktreeEntries);\n    const localBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = [];\n    const remoteBranches: Array<{ readonly ref: VcsRef; readonly lastCommit: number }> = [];\n\n    for (const line of refsResult.stdout.split(\"\\n\")) {\n      if (line.length === 0) continue;\n      const [fullRefName, lastCommitRaw, symbolicTarget] = line.split(\"\\t\");\n      if (!fullRefName || symbolicTarget) continue;\n      const parsedLastCommit = Number.parseInt(lastCommitRaw ?? \"0\", 10);\n      const lastCommit = Number.isFinite(parsedLastCommit) ? parsedLastCommit : 0;\n\n      if (fullRefName.startsWith(\"refs/heads/\")) {\n        const name = fullRefName.slice(\"refs/heads/\".length);\n        localBranches.push({\n          ref: {\n            name,\n            current: false,\n            isRemote: false,\n            isDefault: name === defaultBranch,\n            worktreePath: worktreeMap.get(name) ?? null,\n          },\n          lastCommit,\n        });\n        continue;\n      }\n      if (!fullRefName.startsWith(\"refs/remotes/\")) continue;\n\n      const name = fullRefName.slice(\"refs/remotes/\".length);\n      const parsedRemoteRef = parseRemoteRefWithRemoteNames(name, remoteNames);\n      const remoteBranch: VcsRef = {\n        name,\n        current: false,\n        isRemote: true,\n        isDefault:\n          defaultBranch !== null &&\n          parsedRemoteRef?.remoteName === \"origin\" &&\n          parsedRemoteRef.branchName === defaultBranch,\n        worktreePath: null,\n        ...(parsedRemoteRef ? { remoteName: parsedRemoteRef.remoteName } : {}),\n      };\n      remoteBranches.push({ ref: remoteBranch, lastCommit });\n    }\n\n    const byRecencyThenName = (\n      left: { readonly ref: VcsRef; readonly lastCommit: number },\n      right: { readonly ref: VcsRef; readonly lastCommit: number },\n    ) =>\n      left.lastCommit !== right.lastCommit\n        ? right.lastCommit - left.lastCommit\n        : left.ref.name.localeCompare(right.ref.name);\n\n    return {\n      localBranches: localBranches.toSorted(byRecencyThenName).map(({ ref }) => ref),\n      remoteBranches: remoteBranches.toSorted(byRecencyThenName).map(({ ref }) => ref),\n      hasPrimaryRemote: remoteNames.includes(\"origin\"),\n    } satisfies GitRefsSnapshot;\n  });\n\n  const listRefsEpochByCommonDir = new Map<string, number>();\n  let listRefsEpochSequence = 0;\n  const bumpListRefsEpoch = (gitCommonDir: string): number => {\n    const nextEpoch = ++listRefsEpochSequence;\n    listRefsEpochByCommonDir.delete(gitCommonDir);\n    listRefsEpochByCommonDir.set(gitCommonDir, nextEpoch);\n    if (listRefsEpochByCommonDir.size > LIST_REFS_SNAPSHOT_CACHE_CAPACITY) {\n      const oldestKey = listRefsEpochByCommonDir.keys().next().value;\n      if (oldestKey !== undefined) {\n        listRefsEpochByCommonDir.delete(oldestKey);\n      }\n    }\n    return nextEpoch;\n  };\n  const listRefsGenerationByCommonDir = new Map<string, number>();\n  let listRefsGenerationSequence = 0;\n  const setListRefsGeneration = (gitCommonDir: string, generation: number): number => {\n    listRefsGenerationByCommonDir.delete(gitCommonDir);\n    listRefsGenerationByCommonDir.set(gitCommonDir, generation);\n    if (listRefsGenerationByCommonDir.size > LIST_REFS_SNAPSHOT_CACHE_CAPACITY) {\n      const oldestKey = listRefsGenerationByCommonDir.keys().next().value;\n      if (oldestKey !== undefined) {\n        listRefsGenerationByCommonDir.delete(oldestKey);\n      }\n    }\n    return generation;\n  };\n  const currentListRefsGeneration = (gitCommonDir: string): number => {\n    const current = listRefsGenerationByCommonDir.get(gitCommonDir);\n    return current === undefined\n      ? setListRefsGeneration(gitCommonDir, ++listRefsGenerationSequence)\n      : setListRefsGeneration(gitCommonDir, current);\n  };\n  const bumpListRefsGeneration = (gitCommonDir: string): number =>\n    setListRefsGeneration(gitCommonDir, ++listRefsGenerationSequence);\n  const listRefsSnapshotCache = yield* Cache.makeWith(\n    (cacheKey: GitRefsSnapshotCacheKey) => readGitRefsSnapshot(cacheKey.gitCommonDir),\n    {\n      capacity: LIST_REFS_SNAPSHOT_CACHE_CAPACITY,\n      timeToLive: (exit) => (Exit.isSuccess(exit) ? LIST_REFS_SNAPSHOT_CACHE_TTL : Duration.zero),\n    },\n  );\n  const listRefsRefreshSnapshotCache = yield* Cache.makeWith(\n    (cacheKey: GitRefsRefreshCacheKey) =>\n      Effect.suspend(() => {\n        const epoch = bumpListRefsEpoch(cacheKey.gitCommonDir);\n        return Cache.get(\n          listRefsSnapshotCache,\n          new GitRefsSnapshotCacheKey({ gitCommonDir: cacheKey.gitCommonDir, epoch }),\n        );\n      }),\n    {\n      capacity: LIST_REFS_SNAPSHOT_CACHE_CAPACITY,\n      timeToLive: (exit) =>\n        Exit.isSuccess(exit) ? LIST_REFS_REFRESH_COALESCE_TTL : LIST_REFS_REFRESH_FAILURE_COOLDOWN,\n    },\n  );\n  const resolveListRefsSnapshot = Effect.fn(\"resolveListRefsSnapshot\")(function* (\n    gitCommonDir: string,\n    refresh: boolean,\n  ) {\n    while (true) {\n      const generation = currentListRefsGeneration(gitCommonDir);\n      const currentEpoch = listRefsEpochByCommonDir.get(gitCommonDir);\n      const snapshot =\n        refresh || currentEpoch === undefined\n          ? // The refresh cache owns the complete snapshot read, rather than only the\n            // epoch bump. Slow repositories therefore remain singleflight for the\n            // entire Git scan even when more refresh requests arrive after the\n            // coalescing TTL would otherwise have elapsed.\n            yield* Cache.get(\n              listRefsRefreshSnapshotCache,\n              new GitRefsRefreshCacheKey({ gitCommonDir, generation }),\n            )\n          : yield* Cache.get(\n              listRefsSnapshotCache,\n              new GitRefsSnapshotCacheKey({ gitCommonDir, epoch: currentEpoch }),\n            );\n      if (currentListRefsGeneration(gitCommonDir) === generation) {\n        return snapshot;\n      }\n    }\n  });\n  const invalidateListRefsSnapshot = Effect.fn(\"invalidateListRefsSnapshot\")(function* (\n    cwd: string,\n  ) {\n    const repositoryPathsCacheKey = normalizeRepositoryPathsCacheKey(cwd);\n    const repositoryPaths = yield* Cache.get(repositoryPathsCache, repositoryPathsCacheKey);\n    if (repositoryPaths === null) return;\n    const previousGeneration = currentListRefsGeneration(repositoryPaths.gitCommonDir);\n    bumpListRefsGeneration(repositoryPaths.gitCommonDir);\n    bumpListRefsEpoch(repositoryPaths.gitCommonDir);\n    yield* Cache.invalidate(\n      listRefsRefreshSnapshotCache,\n      new GitRefsRefreshCacheKey({\n        gitCommonDir: repositoryPaths.gitCommonDir,\n        generation: previousGeneration,\n      }),\n    );\n    yield* Cache.invalidate(repositoryPathsRefreshCache, repositoryPathsCacheKey);\n    yield* Cache.invalidate(repositoryPathsCache, repositoryPathsCacheKey);\n  });\n\n  const listRefs: GitVcsDriver.GitVcsDriver[\"Service\"][\"listRefs\"] = Effect.fn(\"listRefs\")(\n    function* (input) {\n      const repositoryPaths = yield* resolveRepositoryPaths(input.cwd, input.refresh === true).pipe(\n        Effect.catchTags({\n          GitCommandError: (error) =>\n            isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error),\n        }),\n      );\n      if (repositoryPaths === null) {\n        return {\n          refs: [],\n          isRepo: false,\n          hasPrimaryRemote: false,\n          nextCursor: null,\n          totalCount: 0,\n        };\n      }\n\n      const snapshot = yield* resolveListRefsSnapshot(\n        repositoryPaths.gitCommonDir,\n        input.refresh === true,\n      );\n      const hasCurrentWorktreeBranch =\n        repositoryPaths.worktreeRoot !== null &&\n        snapshot.localBranches.some((ref) => ref.worktreePath === repositoryPaths.worktreeRoot);\n      const localBranches = snapshot.localBranches.map((ref) => ({\n        ...ref,\n        current: hasCurrentWorktreeBranch\n          ? ref.worktreePath === repositoryPaths.worktreeRoot\n          : ref.name === repositoryPaths.currentBranch,\n      }));\n      const combinedBranches = input.includeMatchingRemoteRefs\n        ? [...localBranches, ...snapshot.remoteBranches]\n        : dedupeRemoteBranchesWithLocalMatches([...localBranches, ...snapshot.remoteBranches]);\n      // Keep current/default refs on the first page even when the default\n      // only exists as origin/<default> (remote refs sort after all locals).\n      const allBranches = combinedBranches.toSorted((left, right) => {\n        const leftPriority = left.current ? 0 : left.isDefault ? 1 : 2;\n        const rightPriority = right.current ? 0 : right.isDefault ? 1 : 2;\n        return leftPriority - rightPriority;\n      });\n      const branchesForKind =\n        input.refKind === \"local\"\n          ? allBranches.filter((ref) => !ref.isRemote)\n          : input.refKind === \"remote\"\n            ? allBranches.filter((ref) => ref.isRemote)\n            : allBranches;\n      const refs = paginateBranches({\n        refs: filterBranchesForListQuery(branchesForKind, input.query),\n        cursor: input.cursor,\n        limit: input.limit,\n      });\n\n      return {\n        refs: [...refs.refs],\n        isRepo: true,\n        hasPrimaryRemote: snapshot.hasPrimaryRemote,\n        nextCursor: refs.nextCursor,\n        totalCount: refs.totalCount,\n      };\n    },\n  );\n\n  const createWorktree: GitVcsDriver.GitVcsDriver[\"Service\"][\"createWorktree\"] = Effect.fn(\n    \"createWorktree\",\n  )(function* (input) {\n    const targetBranch = input.newRefName ?? input.refName;\n    const sanitizedBranch = targetBranch.replace(/\\//g, \"-\");\n    const repoName = path.basename(input.cwd);\n    const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch);\n    const args = input.newRefName\n      ? [\"worktree\", \"add\", \"-b\", input.newRefName, worktreePath, input.refName]\n      : [\"worktree\", \"add\", worktreePath, input.refName];\n\n    yield* executeGit(\"GitVcsDriver.createWorktree\", input.cwd, args, {\n      fallbackErrorDetail: \"git worktree add failed\",\n    });\n\n    if (input.newRefName && input.baseRefName) {\n      const remoteNames = yield* listRemoteNames(input.cwd).pipe(Effect.orElseSucceed(() => []));\n      const parsedBaseRef = parseRemoteRefWithRemoteNames(\n        input.baseRefName,\n        remoteNames.toSorted((left, right) => right.length - left.length),\n      );\n      const baseBranch = parsedBaseRef?.branchName ?? input.baseRefName;\n      yield* runGit(\"GitVcsDriver.createWorktree.configureBaseRef\", input.cwd, [\n        \"config\",\n        `branch.${input.newRefName}.gh-merge-base`,\n        baseBranch,\n      ]);\n    }\n\n    return {\n      worktree: {\n        path: worktreePath,\n        refName: targetBranch,\n      },\n    };\n  });\n\n  const fetchPullRequestBranch: GitVcsDriver.GitVcsDriver[\"Service\"][\"fetchPullRequestBranch\"] =\n    Effect.fn(\"fetchPullRequestBranch\")(function* (input) {\n      const remoteName = yield* resolvePrimaryRemoteName(input.cwd);\n      yield* executeGit(\n        \"GitVcsDriver.fetchPullRequestBranch\",\n        input.cwd,\n        [\n          \"fetch\",\n          \"--quiet\",\n          \"--no-tags\",\n          remoteName,\n          `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`,\n        ],\n        {\n          fallbackErrorDetail: \"git fetch pull request branch failed\",\n        },\n      );\n    });\n\n  const fetchRemote: GitVcsDriver.GitVcsDriver[\"Service\"][\"fetchRemote\"] = Effect.fn(\"fetchRemote\")(\n    function* (input) {\n      yield* executeGit(\n        \"GitVcsDriver.fetchRemote\",\n        input.cwd,\n        [\"fetch\", \"--quiet\", input.remoteName],\n        {\n          env: STATUS_UPSTREAM_REFRESH_ENV,\n          fallbackErrorDetail: `git fetch ${input.remoteName} failed`,\n        },\n      );\n    },\n  );\n\n  const resolveRemoteTrackingCommit: GitVcsDriver.GitVcsDriver[\"Service\"][\"resolveRemoteTrackingCommit\"] =\n    Effect.fn(\"resolveRemoteTrackingCommit\")(function* (input) {\n      const remoteNames = yield* listRemoteNames(input.cwd);\n      const parsedRemoteRef = parseRemoteRefWithRemoteNames(\n        input.refName,\n        remoteNames.toSorted((left, right) => right.length - left.length),\n      );\n      const remoteRefName =\n        parsedRemoteRef?.remoteRef ?? `${input.fallbackRemoteName}/${input.refName}`;\n      const commitSha = yield* runGitStdout(\"GitVcsDriver.resolveRemoteTrackingCommit\", input.cwd, [\n        \"rev-parse\",\n        \"--verify\",\n        `refs/remotes/${remoteRefName}^{commit}`,\n      ]).pipe(Effect.map((stdout) => stdout.trim()));\n\n      return { commitSha, remoteRefName };\n    });\n\n  const fetchRemoteBranch: GitVcsDriver.GitVcsDriver[\"Service\"][\"fetchRemoteBranch\"] = Effect.fn(\n    \"fetchRemoteBranch\",\n  )(function* (input) {\n    yield* runGit(\"GitVcsDriver.fetchRemoteBranch.fetch\", input.cwd, [\n      \"fetch\",\n      \"--quiet\",\n      \"--no-tags\",\n      input.remoteName,\n      `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`,\n    ]);\n\n    const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch);\n    const targetRef = `${input.remoteName}/${input.remoteBranch}`;\n    yield* runGit(\n      \"GitVcsDriver.fetchRemoteBranch.materialize\",\n      input.cwd,\n      localBranchAlreadyExists\n        ? [\"branch\", \"--force\", input.localBranch, targetRef]\n        : [\"branch\", input.localBranch, targetRef],\n    );\n  });\n\n  const fetchRemoteTrackingBranch: GitVcsDriver.GitVcsDriver[\"Service\"][\"fetchRemoteTrackingBranch\"] =\n    Effect.fn(\"fetchRemoteTrackingBranch\")(function* (input) {\n      yield* runGit(\"GitVcsDriver.fetchRemoteTrackingBranch\", input.cwd, [\n        \"fetch\",\n        \"--quiet\",\n        \"--no-tags\",\n        input.remoteName,\n        `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`,\n      ]);\n    });\n\n  const setBranchUpstream: GitVcsDriver.GitVcsDriver[\"Service\"][\"setBranchUpstream\"] = (input) =>\n    runGit(\"GitVcsDriver.setBranchUpstream\", input.cwd, [\n      \"branch\",\n      \"--set-upstream-to\",\n      `${input.remoteName}/${input.remoteBranch}`,\n      input.branch,\n    ]);\n\n  const removeWorktree: GitVcsDriver.GitVcsDriver[\"Service\"][\"removeWorktree\"] = Effect.fn(\n    \"removeWorktree\",\n  )(function* (input) {\n    const args = [\"worktree\", \"remove\"];\n    if (input.force) {\n      args.push(\"--force\");\n    }\n    args.push(input.path);\n    yield* executeGit(\"GitVcsDriver.removeWorktree\", input.cwd, args, {\n      timeoutMs: 15_000,\n      fallbackErrorDetail: \"git worktree remove failed\",\n    });\n  });\n\n  const renameBranch: GitVcsDriver.GitVcsDriver[\"Service\"][\"renameBranch\"] = Effect.fn(\n    \"renameBranch\",\n  )(function* (input) {\n    if (input.oldBranch === input.newBranch) {\n      return { branch: input.newBranch };\n    }\n    const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch);\n\n    yield* executeGit(\n      \"GitVcsDriver.renameBranch\",\n      input.cwd,\n      [\"branch\", \"-m\", \"--\", input.oldBranch, targetBranch],\n      {\n        timeoutMs: 10_000,\n        fallbackErrorDetail: \"git branch rename failed\",\n      },\n    );\n\n    return { branch: targetBranch };\n  });\n\n  const switchRef: GitVcsDriver.GitVcsDriver[\"Service\"][\"switchRef\"] = Effect.fn(\"switchRef\")(\n    function* (input) {\n      const [localInputExists, remoteExists] = yield* Effect.all(\n        [\n          executeGit(\n            \"GitVcsDriver.switchRef.localInputExists\",\n            input.cwd,\n            [\"show-ref\", \"--verify\", \"--quiet\", `refs/heads/${input.refName}`],\n            {\n              timeoutMs: 5_000,\n              allowNonZeroExit: true,\n            },\n          ).pipe(Effect.map((result) => result.exitCode === 0)),\n          executeGit(\n            \"GitVcsDriver.switchRef.remoteExists\",\n            input.cwd,\n            [\"show-ref\", \"--verify\", \"--quiet\", `refs/remotes/${input.refName}`],\n            {\n              timeoutMs: 5_000,\n              allowNonZeroExit: true,\n            },\n          ).pipe(Effect.map((result) => result.exitCode === 0)),\n        ],\n        { concurrency: \"unbounded\" },\n      );\n\n      const localTrackingBranch = remoteExists\n        ? yield* executeGit(\n            \"GitVcsDriver.switchRef.localTrackingBranch\",\n            input.cwd,\n            [\"for-each-ref\", \"--format=%(refname:short)\\t%(upstream:short)\", \"refs/heads\"],\n            {\n              timeoutMs: 5_000,\n              allowNonZeroExit: true,\n            },\n          ).pipe(\n            Effect.map((result) =>\n              result.exitCode === 0\n                ? parseTrackingBranchByUpstreamRef(result.stdout, input.refName)\n                : null,\n            ),\n          )\n        : null;\n\n      const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.refName);\n      const localTrackedBranchTargetExists =\n        remoteExists && localTrackedBranchCandidate\n          ? yield* executeGit(\n              \"GitVcsDriver.switchRef.localTrackedBranchTargetExists\",\n              input.cwd,\n              [\"show-ref\", \"--verify\", \"--quiet\", `refs/heads/${localTrackedBranchCandidate}`],\n              {\n                timeoutMs: 5_000,\n                allowNonZeroExit: true,\n              },\n            ).pipe(Effect.map((result) => result.exitCode === 0))\n          : false;\n\n      const checkoutArgs = localInputExists\n        ? [\"checkout\", input.refName]\n        : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists\n          ? [\"checkout\", input.refName]\n          : remoteExists && !localTrackingBranch\n            ? [\"checkout\", \"--track\", input.refName]\n            : remoteExists && localTrackingBranch\n              ? [\"checkout\", localTrackingBranch]\n              : [\"checkout\", input.refName];\n\n      yield* executeGit(\"GitVcsDriver.switchRef.checkout\", input.cwd, checkoutArgs, {\n        timeoutMs: 10_000,\n        fallbackErrorDetail: \"git checkout failed\",\n      });\n\n      const refName = yield* runGitStdout(\"GitVcsDriver.switchRef.currentBranch\", input.cwd, [\n        \"branch\",\n        \"--show-current\",\n      ]).pipe(Effect.map((stdout) => stdout.trim() || null));\n\n      return { refName };\n    },\n  );\n\n  const createRef: GitVcsDriver.GitVcsDriver[\"Service\"][\"createRef\"] = Effect.fn(\"createRef\")(\n    function* (input) {\n      yield* executeGit(\"GitVcsDriver.createRef\", input.cwd, [\"branch\", input.refName], {\n        timeoutMs: 10_000,\n        fallbackErrorDetail: \"git branch create failed\",\n      });\n      if (input.switchRef) {\n        yield* switchRef({ cwd: input.cwd, refName: input.refName });\n      }\n\n      return { refName: input.refName };\n    },\n  );\n\n  const initRepo: GitVcsDriver.GitVcsDriver[\"Service\"][\"initRepo\"] = (input) =>\n    executeGit(\"GitVcsDriver.initRepo\", input.cwd, [\"init\"], {\n      timeoutMs: 10_000,\n      fallbackErrorDetail: \"git init failed\",\n    }).pipe(Effect.asVoid);\n\n  const listLocalBranchNames: GitVcsDriver.GitVcsDriver[\"Service\"][\"listLocalBranchNames\"] = (\n    cwd,\n  ) =>\n    runGitStdout(\"GitVcsDriver.listLocalBranchNames\", cwd, [\n      \"branch\",\n      \"--list\",\n      \"--no-column\",\n      \"--format=%(refname:short)\",\n    ]).pipe(\n      Effect.map((stdout) => {\n        const branchNames: Array<string> = [];\n        for (const line of stdout.split(\"\\n\")) {\n          const branchName = line.trim();\n          if (branchName.length > 0) {\n            branchNames.push(branchName);\n          }\n        }\n        return branchNames;\n      }),\n    );\n\n  const withListRefsInvalidation = <A, E>(\n    cwd: string,\n    effect: Effect.Effect<A, E>,\n  ): Effect.Effect<A, E> =>\n    effect.pipe(\n      Effect.ensuring(\n        Effect.all([\n          invalidateListRefsSnapshot(cwd).pipe(Effect.ignore),\n          invalidateStatusStaticCaches(cwd).pipe(Effect.ignore),\n        ]),\n      ),\n    );\n  const initRepoWithListRefsInvalidation: GitVcsDriver.GitVcsDriver[\"Service\"][\"initRepo\"] = (\n    input,\n  ) =>\n    initRepo(input).pipe(\n      Effect.ensuring(\n        Effect.gen(function* () {\n          const cacheKey = normalizeRepositoryPathsCacheKey(input.cwd);\n          yield* Cache.invalidate(repositoryPathsRefreshCache, cacheKey);\n          yield* Cache.invalidate(repositoryPathsCache, cacheKey);\n          yield* invalidateListRefsSnapshot(input.cwd).pipe(Effect.ignore);\n        }),\n      ),\n    );\n\n  return GitVcsDriver.GitVcsDriver.of({\n    execute,\n    status,\n    statusDetails,\n    statusDetailsLocal,\n    statusDetailsRemote,\n    prepareCommitContext,\n    commit: (cwd, subject, body, options) =>\n      withListRefsInvalidation(cwd, commit(cwd, subject, body, options)),\n    pushCurrentBranch: (cwd, fallbackBranch, options) =>\n      withListRefsInvalidation(cwd, pushCurrentBranch(cwd, fallbackBranch, options)),\n    pullCurrentBranch: (cwd) => withListRefsInvalidation(cwd, pullCurrentBranch(cwd)),\n    readRangeContext,\n    getReviewDiffPreview,\n    getReviewDiffFileContents,\n    readConfigValue,\n    listRefs,\n    createWorktree: (input) => withListRefsInvalidation(input.cwd, createWorktree(input)),\n    fetchPullRequestBranch: (input) =>\n      withListRefsInvalidation(input.cwd, fetchPullRequestBranch(input)),\n    ensureRemote: (input) => withListRefsInvalidation(input.cwd, ensureRemote(input)),\n    resolvePrimaryRemoteName,\n    fetchRemote: (input) => withListRefsInvalidation(input.cwd, fetchRemote(input)),\n    remoteExists,\n    resolveRemoteTrackingCommit,\n    fetchRemoteBranch: (input) => withListRefsInvalidation(input.cwd, fetchRemoteBranch(input)),\n    fetchRemoteTrackingBranch: (input) =>\n      withListRefsInvalidation(input.cwd, fetchRemoteTrackingBranch(input)),\n    setBranchUpstream: (input) => withListRefsInvalidation(input.cwd, setBranchUpstream(input)),\n    removeWorktree: (input) => withListRefsInvalidation(input.cwd, removeWorktree(input)),\n    renameBranch: (input) => withListRefsInvalidation(input.cwd, renameBranch(input)),\n    createRef: (input) => withListRefsInvalidation(input.cwd, createRef(input)),\n    switchRef: (input) => withListRefsInvalidation(input.cwd, switchRef(input)),\n    initRepo: initRepoWithListRefsInvalidation,\n    listLocalBranchNames,\n  });\n});\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Match from \"effect/Match\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport {\n  type VcsError,\n  VcsProcessExitError,\n  type VcsProcessExitFailureKind,\n  VcsProcessMissingExitCodeError,\n  VcsProcessOutputLimitError,\n  VcsProcessOutputReadError,\n  VcsProcessSpawnError,\n  VcsProcessStdinWriteError,\n  VcsProcessTimeoutError,\n} from \"@t3tools/contracts\";\nimport * as ProcessRunner from \"../processRunner.ts\";\n\nexport interface VcsProcessInput {\n  readonly operation: string;\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly cwd: string;\n  readonly spawnCwd?: string;\n  readonly stdin?: string;\n  readonly env?: NodeJS.ProcessEnv;\n  readonly allowNonZeroExit?: boolean;\n  readonly timeoutMs?: number;\n  readonly maxOutputBytes?: number;\n  readonly appendTruncationMarker?: boolean;\n}\n\nexport interface VcsProcessOutput {\n  readonly exitCode: ChildProcessSpawner.ExitCode;\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly stdoutTruncated: boolean;\n  readonly stderrTruncated: boolean;\n}\n\nexport class VcsProcess extends Context.Service<\n  VcsProcess,\n  {\n    readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;\n  }\n>()(\"t3/vcs/VcsProcess\") {}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;\nconst OUTPUT_TRUNCATED_MARKER = \"\\n\\n[truncated]\";\n\nconst classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => {\n  const normalized = stderr.toLowerCase();\n\n  if (\n    normalized.includes(\"authentication failed\") ||\n    normalized.includes(\"not logged in\") ||\n    normalized.includes(\"gh auth login\") ||\n    normalized.includes(\"glab auth login\") ||\n    normalized.includes(\"az devops login\") ||\n    normalized.includes(\"please run az login\") ||\n    normalized.includes(\"no oauth token\") ||\n    normalized.includes(\"unauthorized\")\n  ) {\n    return \"authentication\";\n  }\n\n  if (\n    (command === \"gh\" &&\n      (normalized.includes(\"could not resolve to a pullrequest\") ||\n        normalized.includes(\"repository.pullrequest\") ||\n        normalized.includes(\"no pull requests found for branch\") ||\n        normalized.includes(\"pull request not found\"))) ||\n    (command === \"glab\" &&\n      (normalized.includes(\"merge request not found\") ||\n        normalized.includes(\"not found\") ||\n        normalized.includes(\"404\"))) ||\n    (command === \"az\" &&\n      normalized.includes(\"pull request\") &&\n      (normalized.includes(\"not found\") || normalized.includes(\"does not exist\")))\n  ) {\n    return \"not-found\";\n  }\n\n  return \"command-failed\";\n};\n\nexport const make = Effect.gen(function* () {\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n\n  const run = Effect.fn(\"VcsProcess.run\")(function* (input: VcsProcessInput) {\n    const baseError = {\n      operation: input.operation,\n      command: input.command,\n      cwd: input.cwd,\n      argumentCount: input.args.length,\n    };\n\n    const result = yield* processRunner\n      .run({\n        command: input.command,\n        args: input.args,\n        cwd: input.cwd,\n        ...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),\n        ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),\n        ...(input.env !== undefined ? { env: input.env } : {}),\n        timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n        maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,\n        outputMode: \"truncate\",\n        truncatedMarker: input.appendTruncationMarker ? OUTPUT_TRUNCATED_MARKER : \"\",\n        timeoutBehavior: \"error\",\n      })\n      .pipe(\n        Effect.mapError(\n          Match.valueTags({\n            ProcessSpawnError: (error) =>\n              VcsProcessSpawnError.fromProcessSpawnError(baseError, error),\n            ProcessOutputLimitError: (error) =>\n              new VcsProcessOutputLimitError({\n                ...baseError,\n                stream: error.stream,\n                maxBytes: error.maxBytes,\n                observedBytes: error.observedBytes,\n              }),\n            ProcessTimeoutError: (error) =>\n              VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),\n            ProcessStdinError: (error) =>\n              new VcsProcessStdinWriteError({\n                ...baseError,\n                stdinBytes: error.stdinBytes,\n                cause: error.cause,\n              }),\n            ProcessReadError: (error) =>\n              new VcsProcessOutputReadError({\n                ...baseError,\n                stream: error.stream,\n                cause: error.cause,\n              }),\n          }),\n        ),\n      );\n\n    if (result.code === null) {\n      return yield* new VcsProcessMissingExitCodeError(baseError);\n    }\n\n    if (!input.allowNonZeroExit && result.code !== 0) {\n      return yield* VcsProcessExitError.fromProcessExit(\n        baseError,\n        {\n          exitCode: result.code,\n          stderr: result.stderr,\n          stderrTruncated: result.stderrTruncated,\n        },\n        classifyNonZeroExit(input.command, result.stderr),\n      );\n    }\n\n    return {\n      exitCode: result.code,\n      stdout: result.stdout,\n      stderr: result.stderr,\n      stdoutTruncated: result.stdoutTruncated,\n      stderrTruncated: result.stderrTruncated,\n    } satisfies VcsProcessOutput;\n  });\n\n  return VcsProcess.of({ run });\n});\n\nexport const layer = Layer.effect(VcsProcess, make).pipe(Layer.provide(ProcessRunner.layer));\n","import * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type {\n  VcsDriverCapabilities,\n  VcsError,\n  VcsInitInput,\n  VcsListRemotesResult,\n  VcsListWorkspaceFilesResult,\n  ReviewDiffPreviewInput,\n  ReviewDiffPreviewResult,\n  VcsRepositoryIdentity,\n} from \"@t3tools/contracts\";\nimport { CheckpointRef } from \"@t3tools/contracts\";\nimport * as VcsProcess from \"./VcsProcess.ts\";\n\nexport interface VcsCaptureCheckpointInput {\n  readonly cwd: string;\n  readonly checkpointRef: CheckpointRef;\n}\n\nexport interface VcsRestoreCheckpointInput {\n  readonly cwd: string;\n  readonly checkpointRef: CheckpointRef;\n  readonly fallbackToHead?: boolean;\n}\n\nexport interface VcsDiffCheckpointsInput {\n  readonly cwd: string;\n  readonly fromCheckpointRef: CheckpointRef;\n  readonly toCheckpointRef: CheckpointRef;\n  readonly fallbackFromToHead?: boolean;\n  readonly ignoreWhitespace: boolean;\n}\n\nexport interface VcsDeleteCheckpointRefsInput {\n  readonly cwd: string;\n  readonly checkpointRefs: ReadonlyArray<CheckpointRef>;\n}\n\nexport interface VcsCheckpointOps {\n  readonly captureCheckpoint: (input: VcsCaptureCheckpointInput) => Effect.Effect<void, VcsError>;\n  readonly hasCheckpointRef: (\n    input: Omit<VcsRestoreCheckpointInput, \"fallbackToHead\">,\n  ) => Effect.Effect<boolean, VcsError>;\n  readonly restoreCheckpoint: (\n    input: VcsRestoreCheckpointInput,\n  ) => Effect.Effect<boolean, VcsError>;\n  readonly diffCheckpoints: (input: VcsDiffCheckpointsInput) => Effect.Effect<string, VcsError>;\n  readonly deleteCheckpointRefs: (\n    input: VcsDeleteCheckpointRefsInput,\n  ) => Effect.Effect<void, VcsError>;\n}\n\nexport class VcsDriver extends Context.Service<\n  VcsDriver,\n  {\n    readonly capabilities: VcsDriverCapabilities;\n    readonly execute: (\n      input: Omit<VcsProcess.VcsProcessInput, \"command\">,\n    ) => Effect.Effect<VcsProcess.VcsProcessOutput, VcsError>;\n    readonly checkpoints?: VcsCheckpointOps;\n    readonly detectRepository: (\n      cwd: string,\n    ) => Effect.Effect<VcsRepositoryIdentity | null, VcsError>;\n    readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, VcsError>;\n    readonly listWorkspaceFiles: (\n      cwd: string,\n    ) => Effect.Effect<VcsListWorkspaceFilesResult, VcsError>;\n    readonly listRemotes: (cwd: string) => Effect.Effect<VcsListRemotesResult, VcsError>;\n    readonly filterIgnoredPaths: (\n      cwd: string,\n      relativePaths: ReadonlyArray<string>,\n    ) => Effect.Effect<ReadonlyArray<string>, VcsError>;\n    readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;\n    readonly getDiffPreview?: (\n      input: ReviewDiffPreviewInput,\n    ) => Effect.Effect<ReviewDiffPreviewResult, VcsError>;\n  }\n>()(\"t3/vcs/VcsDriver\") {}\n","import * as NodeCrypto from \"node:crypto\";\n\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport {\n  GitCommandError,\n  VcsProcessExitError,\n  type VcsSwitchRefInput,\n  type VcsSwitchRefResult,\n  type VcsCreateRefInput,\n  type VcsCreateRefResult,\n  type VcsCreateWorktreeInput,\n  type VcsCreateWorktreeResult,\n  type ReviewDiffPreviewInput,\n  type ReviewDiffPreviewResult,\n  type ReviewDiffFileContentsInput,\n  type ReviewDiffFileContentsResult,\n  type VcsInitInput,\n  type VcsListRefsInput,\n  type VcsListRefsResult,\n  type VcsPullResult,\n  type VcsRemoveWorktreeInput,\n  type VcsStatusInput,\n  type VcsStatusResult,\n} from \"@t3tools/contracts\";\nimport { makeGitVcsDriverCore } from \"./GitVcsDriverCore.ts\";\nimport * as VcsDriver from \"./VcsDriver.ts\";\nimport * as VcsProcess from \"./VcsProcess.ts\";\n\nexport interface ExecuteGitInput {\n  readonly operation: string;\n  readonly cwd: string;\n  readonly args: ReadonlyArray<string>;\n  readonly stdin?: string;\n  readonly env?: NodeJS.ProcessEnv;\n  readonly allowNonZeroExit?: boolean;\n  readonly timeoutMs?: number;\n  readonly maxOutputBytes?: number;\n  readonly appendTruncationMarker?: boolean;\n  readonly progress?: ExecuteGitProgress;\n}\n\nexport interface ExecuteGitResult {\n  readonly exitCode: ChildProcessSpawner.ExitCode;\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly stdoutTruncated: boolean;\n  readonly stderrTruncated: boolean;\n}\n\nexport interface GitStatusDetails {\n  isRepo: boolean;\n  sourceControlProvider?: VcsStatusResult[\"sourceControlProvider\"];\n  hasOriginRemote: boolean;\n  isDefaultBranch: boolean;\n  branch: string | null;\n  upstreamRef: string | null;\n  hasWorkingTreeChanges: boolean;\n  workingTree: VcsStatusResult[\"workingTree\"];\n  hasUpstream: boolean;\n  aheadCount: number;\n  behindCount: number;\n  aheadOfDefaultCount: number;\n}\n\nexport interface GitRemoteStatusDetails {\n  isRepo: boolean;\n  isDefaultBranch: boolean;\n  branch: string | null;\n  upstreamRef: string | null;\n  hasUpstream: boolean;\n  aheadCount: number;\n  behindCount: number;\n  aheadOfDefaultCount: number;\n}\n\nexport interface GitPreparedCommitContext {\n  stagedSummary: string;\n  stagedPatch: string;\n}\n\nexport interface ExecuteGitProgress {\n  readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;\n  readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;\n  readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;\n  readonly onHookFinished?: (input: {\n    hookName: string;\n    exitCode: number | null;\n    durationMs: number | null;\n  }) => Effect.Effect<void, never>;\n}\n\nexport interface GitCommitProgress {\n  readonly onOutputLine?: (input: {\n    stream: \"stdout\" | \"stderr\";\n    text: string;\n  }) => Effect.Effect<void, never>;\n  readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;\n  readonly onHookFinished?: (input: {\n    hookName: string;\n    exitCode: number | null;\n    durationMs: number | null;\n  }) => Effect.Effect<void, never>;\n}\n\nexport interface GitCommitOptions {\n  readonly timeoutMs?: number;\n  readonly progress?: GitCommitProgress;\n}\n\nexport interface GitPushResult {\n  status: \"pushed\" | \"skipped_up_to_date\";\n  branch: string;\n  upstreamBranch?: string | undefined;\n  setUpstream?: boolean | undefined;\n}\n\nexport interface GitRangeContext {\n  commitSummary: string;\n  diffSummary: string;\n  diffPatch: string;\n}\n\nexport interface GitRenameBranchInput {\n  cwd: string;\n  oldBranch: string;\n  newBranch: string;\n}\n\nexport interface GitRenameBranchResult {\n  branch: string;\n}\n\nexport interface GitFetchPullRequestBranchInput {\n  cwd: string;\n  prNumber: number;\n  branch: string;\n}\n\nexport interface GitEnsureRemoteInput {\n  cwd: string;\n  preferredName: string;\n  url: string;\n}\n\nexport interface GitFetchRemoteBranchInput {\n  cwd: string;\n  remoteName: string;\n  remoteBranch: string;\n  localBranch: string;\n}\n\nexport interface GitFetchRemoteTrackingBranchInput {\n  cwd: string;\n  remoteName: string;\n  remoteBranch: string;\n}\n\nexport interface GitFetchRemoteInput {\n  cwd: string;\n  remoteName: string;\n}\n\nexport interface GitRemoteExistsInput {\n  cwd: string;\n  remoteName: string;\n}\n\nexport interface GitResolveRemoteTrackingCommitInput {\n  cwd: string;\n  refName: string;\n  fallbackRemoteName: string;\n}\n\nexport interface GitResolveRemoteTrackingCommitResult {\n  commitSha: string;\n  remoteRefName: string;\n}\n\nexport interface GitSetBranchUpstreamInput {\n  cwd: string;\n  branch: string;\n  remoteName: string;\n  remoteBranch: string;\n}\n\nexport interface GitRemoteStatusOptions {\n  readonly refreshUpstream?: boolean;\n}\n\nexport class GitVcsDriver extends Context.Service<\n  GitVcsDriver,\n  {\n    readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;\n    readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;\n    readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;\n    readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;\n    readonly statusDetailsRemote: (\n      cwd: string,\n      options?: GitRemoteStatusOptions,\n    ) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;\n    readonly prepareCommitContext: (\n      cwd: string,\n      filePaths?: readonly string[],\n    ) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;\n    readonly commit: (\n      cwd: string,\n      subject: string,\n      body: string,\n      options?: GitCommitOptions,\n    ) => Effect.Effect<{ commitSha: string }, GitCommandError>;\n    readonly pushCurrentBranch: (\n      cwd: string,\n      fallbackBranch: string | null,\n      options?: { readonly remoteName?: string | null },\n    ) => Effect.Effect<GitPushResult, GitCommandError>;\n    readonly readRangeContext: (\n      cwd: string,\n      baseRef: string,\n    ) => Effect.Effect<GitRangeContext, GitCommandError>;\n    readonly getReviewDiffPreview: (\n      input: ReviewDiffPreviewInput,\n    ) => Effect.Effect<ReviewDiffPreviewResult, GitCommandError>;\n    readonly getReviewDiffFileContents: (\n      input: ReviewDiffFileContentsInput,\n    ) => Effect.Effect<ReviewDiffFileContentsResult, GitCommandError>;\n    readonly readConfigValue: (\n      cwd: string,\n      key: string,\n    ) => Effect.Effect<string | null, GitCommandError>;\n    readonly listRefs: (\n      input: VcsListRefsInput,\n    ) => Effect.Effect<VcsListRefsResult, GitCommandError>;\n    readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;\n    readonly createWorktree: (\n      input: VcsCreateWorktreeInput,\n    ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;\n    readonly fetchPullRequestBranch: (\n      input: GitFetchPullRequestBranchInput,\n    ) => Effect.Effect<void, GitCommandError>;\n    readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;\n    readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;\n    readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;\n    readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;\n    readonly resolveRemoteTrackingCommit: (\n      input: GitResolveRemoteTrackingCommitInput,\n    ) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;\n    readonly fetchRemoteBranch: (\n      input: GitFetchRemoteBranchInput,\n    ) => Effect.Effect<void, GitCommandError>;\n    readonly fetchRemoteTrackingBranch: (\n      input: GitFetchRemoteTrackingBranchInput,\n    ) => Effect.Effect<void, GitCommandError>;\n    readonly setBranchUpstream: (\n      input: GitSetBranchUpstreamInput,\n    ) => Effect.Effect<void, GitCommandError>;\n    readonly removeWorktree: (\n      input: VcsRemoveWorktreeInput,\n    ) => Effect.Effect<void, GitCommandError>;\n    readonly renameBranch: (\n      input: GitRenameBranchInput,\n    ) => Effect.Effect<GitRenameBranchResult, GitCommandError>;\n    readonly createRef: (\n      input: VcsCreateRefInput,\n    ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;\n    readonly switchRef: (\n      input: VcsSwitchRefInput,\n    ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;\n    readonly initRepo: (input: VcsInitInput) => Effect.Effect<void, GitCommandError>;\n    readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;\n  }\n>()(\"t3/vcs/GitVcsDriver\") {}\n\nconst WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;\nconst GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;\nconst CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;\nconst WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [\n  \"-c\",\n  \"core.fsmonitor=false\",\n  \"-c\",\n  \"core.untrackedCache=false\",\n] as const;\n\nconst nowFreshness = Effect.fn(\"GitVcsDriver.nowFreshness\")(function* () {\n  const now = yield* DateTime.now;\n  return {\n    source: \"live-local\" as const,\n    observedAt: now,\n    expiresAt: Option.none(),\n  };\n});\n\nfunction splitNullSeparatedPaths(input: string, truncated: boolean): string[] {\n  const parts = input.split(\"\\0\");\n  if (parts.length === 0) return [];\n\n  if (truncated && parts[parts.length - 1]?.length) {\n    parts.pop();\n  }\n\n  return parts.filter((value) => value.length > 0);\n}\n\nfunction chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {\n  const chunks: string[][] = [];\n  let chunk: string[] = [];\n  let chunkBytes = 0;\n\n  for (const relativePath of relativePaths) {\n    const relativePathBytes = Buffer.byteLength(relativePath) + 1;\n    if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {\n      chunks.push(chunk);\n      chunk = [];\n      chunkBytes = 0;\n    }\n\n    chunk.push(relativePath);\n    chunkBytes += relativePathBytes;\n\n    if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {\n      chunks.push(chunk);\n      chunk = [];\n      chunkBytes = 0;\n    }\n  }\n\n  if (chunk.length > 0) {\n    chunks.push(chunk);\n  }\n\n  return chunks;\n}\n\nfunction parseGitRemoteVerboseOutput(\n  output: string,\n): Map<string, { url?: string; pushUrl?: string }> {\n  const remotes = new Map<string, { url?: string; pushUrl?: string }>();\n  for (const line of output.split(\"\\n\")) {\n    const trimmed = line.trim();\n    if (trimmed.length === 0) {\n      continue;\n    }\n\n    const match = /^(\\S+)\\s+(\\S+)\\s+\\((fetch|push)\\)$/.exec(trimmed);\n    if (!match) {\n      continue;\n    }\n\n    const name = match[1];\n    const url = match[2];\n    const direction = match[3];\n    if (!name || !url || !direction) {\n      continue;\n    }\n    const remote = remotes.get(name) ?? {};\n    if (direction === \"fetch\") {\n      remote.url = url;\n    } else {\n      remote.pushUrl = url;\n    }\n    remotes.set(name, remote);\n  }\n  return remotes;\n}\n\nconst gitCommand = (\n  process: VcsProcess.VcsProcess[\"Service\"],\n  operation: string,\n  cwd: string,\n  args: ReadonlyArray<string>,\n  options?: {\n    readonly stdin?: string;\n    readonly env?: NodeJS.ProcessEnv;\n    readonly allowNonZeroExit?: boolean;\n    readonly timeoutMs?: number;\n    readonly maxOutputBytes?: number;\n    readonly appendTruncationMarker?: boolean;\n  },\n) =>\n  process.run({\n    operation,\n    command: \"git\",\n    args: [\"-C\", cwd, ...args],\n    cwd,\n    spawnCwd: globalThis.process.cwd(),\n    ...(options?.stdin !== undefined ? { stdin: options.stdin } : {}),\n    ...(options?.env !== undefined ? { env: options.env } : {}),\n    ...(options?.allowNonZeroExit !== undefined\n      ? { allowNonZeroExit: options.allowNonZeroExit }\n      : {}),\n    ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n    ...(options?.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),\n    ...(options?.appendTruncationMarker !== undefined\n      ? { appendTruncationMarker: options.appendTruncationMarker }\n      : {}),\n  });\n\nexport const makeVcsDriverShape = Effect.fn(\"makeGitVcsDriverShape\")(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const vcsProcess = yield* VcsProcess.VcsProcess;\n  const capabilities = {\n    kind: \"git\" as const,\n    supportsWorktrees: true,\n    supportsBookmarks: false,\n    supportsAtomicSnapshot: false,\n    supportsPushDefaultRemote: true,\n    ignoreClassifier: \"native\" as const,\n  };\n\n  const isInsideWorkTree: VcsDriver.VcsDriver[\"Service\"][\"isInsideWorkTree\"] = (cwd) =>\n    gitCommand(\n      vcsProcess,\n      \"GitVcsDriver.isInsideWorkTree\",\n      cwd,\n      [\"rev-parse\", \"--is-inside-work-tree\"],\n      {\n        allowNonZeroExit: true,\n        timeoutMs: 5_000,\n        maxOutputBytes: 4_096,\n      },\n    ).pipe(Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === \"true\"));\n\n  const execute: VcsDriver.VcsDriver[\"Service\"][\"execute\"] = (input) =>\n    gitCommand(vcsProcess, input.operation, input.cwd, input.args, {\n      ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),\n      ...(input.env !== undefined ? { env: input.env } : {}),\n      ...(input.allowNonZeroExit !== undefined ? { allowNonZeroExit: input.allowNonZeroExit } : {}),\n      ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),\n      ...(input.maxOutputBytes !== undefined ? { maxOutputBytes: input.maxOutputBytes } : {}),\n      ...(input.appendTruncationMarker !== undefined\n        ? { appendTruncationMarker: input.appendTruncationMarker }\n        : {}),\n    });\n\n  const detectRepository: VcsDriver.VcsDriver[\"Service\"][\"detectRepository\"] = Effect.fn(\n    \"detectRepository\",\n  )(function* (cwd) {\n    if (!(yield* isInsideWorkTree(cwd))) {\n      return null;\n    }\n\n    const root = yield* gitCommand(vcsProcess, \"GitVcsDriver.detectRepository.root\", cwd, [\n      \"rev-parse\",\n      \"--show-toplevel\",\n    ]);\n    const gitCommonDir = yield* gitCommand(\n      vcsProcess,\n      \"GitVcsDriver.detectRepository.commonDir\",\n      cwd,\n      [\"rev-parse\", \"--git-common-dir\"],\n    ).pipe(Effect.orElseSucceed(() => null));\n\n    return {\n      kind: \"git\" as const,\n      rootPath: root.stdout.trim(),\n      metadataPath: gitCommonDir?.stdout.trim() || null,\n      freshness: yield* nowFreshness(),\n    };\n  });\n\n  const listWorkspaceFiles: VcsDriver.VcsDriver[\"Service\"][\"listWorkspaceFiles\"] = (cwd) =>\n    gitCommand(\n      vcsProcess,\n      \"GitVcsDriver.listWorkspaceFiles\",\n      cwd,\n      [\n        ...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,\n        \"ls-files\",\n        \"--cached\",\n        \"--others\",\n        \"--exclude-standard\",\n        \"-z\",\n      ],\n      {\n        allowNonZeroExit: true,\n        timeoutMs: 20_000,\n        maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,\n        appendTruncationMarker: true,\n      },\n    ).pipe(\n      Effect.flatMap((result) =>\n        result.exitCode === 0\n          ? Effect.gen(function* () {\n              const freshness = yield* nowFreshness();\n              return {\n                paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),\n                truncated: result.stdoutTruncated,\n                freshness,\n              };\n            })\n          : Effect.fail(\n              new VcsProcessExitError({\n                operation: \"GitVcsDriver.listWorkspaceFiles\",\n                command: \"git ls-files\",\n                cwd,\n                exitCode: result.exitCode,\n                detail: result.stderr.trim() || \"git ls-files failed\",\n              }),\n            ),\n      ),\n    );\n\n  const listRemotes: VcsDriver.VcsDriver[\"Service\"][\"listRemotes\"] = Effect.fn(\"listRemotes\")(\n    function* (cwd) {\n      const result = yield* gitCommand(\n        vcsProcess,\n        \"GitVcsDriver.listRemotes\",\n        cwd,\n        [\"remote\", \"-v\"],\n        {\n          allowNonZeroExit: true,\n          timeoutMs: 5_000,\n          maxOutputBytes: 64 * 1024,\n        },\n      );\n\n      if (result.exitCode !== 0) {\n        return yield* new VcsProcessExitError({\n          operation: \"GitVcsDriver.listRemotes\",\n          command: \"git remote -v\",\n          cwd,\n          exitCode: result.exitCode,\n          detail: result.stderr.trim() || \"git remote -v failed\",\n        });\n      }\n\n      const parsed = parseGitRemoteVerboseOutput(result.stdout);\n      const remotes = Array.from(parsed.entries()).flatMap(([name, remote]) => {\n        if (!remote.url) {\n          return [];\n        }\n        return [\n          {\n            name,\n            url: remote.url,\n            pushUrl: remote.pushUrl ? Option.some(remote.pushUrl) : Option.none(),\n            isPrimary: name === \"origin\",\n          },\n        ];\n      });\n\n      return {\n        remotes,\n        freshness: yield* nowFreshness(),\n      };\n    },\n  );\n\n  const filterIgnoredPaths: VcsDriver.VcsDriver[\"Service\"][\"filterIgnoredPaths\"] = Effect.fn(\n    \"filterIgnoredPaths\",\n  )(function* (cwd, relativePaths) {\n    if (relativePaths.length === 0) {\n      return relativePaths;\n    }\n\n    const ignoredPaths = new Set<string>();\n    const chunks = chunkPathsForGitCheckIgnore(relativePaths);\n\n    for (const chunk of chunks) {\n      const result = yield* gitCommand(\n        vcsProcess,\n        \"GitVcsDriver.filterIgnoredPaths\",\n        cwd,\n        [...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, \"check-ignore\", \"--no-index\", \"-z\", \"--stdin\"],\n        {\n          stdin: `${chunk.join(\"\\0\")}\\0`,\n          allowNonZeroExit: true,\n          timeoutMs: 20_000,\n          maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,\n          appendTruncationMarker: true,\n        },\n      );\n\n      if (result.exitCode !== 0 && result.exitCode !== 1) {\n        return yield* new VcsProcessExitError({\n          operation: \"GitVcsDriver.filterIgnoredPaths\",\n          command: \"git check-ignore\",\n          cwd,\n          exitCode: result.exitCode,\n          detail: result.stderr.trim() || \"git check-ignore failed\",\n        });\n      }\n\n      for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {\n        ignoredPaths.add(ignoredPath);\n      }\n    }\n\n    if (ignoredPaths.size === 0) {\n      return relativePaths;\n    }\n\n    return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));\n  });\n\n  const initRepository: VcsDriver.VcsDriver[\"Service\"][\"initRepository\"] = (input) =>\n    gitCommand(vcsProcess, \"GitVcsDriver.initRepository\", input.cwd, [\"init\"], {\n      timeoutMs: 10_000,\n      maxOutputBytes: 64 * 1024,\n    }).pipe(Effect.asVoid);\n\n  const resolveHeadCommit = (cwd: string) =>\n    execute({\n      operation: \"GitVcsDriver.checkpoints.resolveHeadCommit\",\n      cwd,\n      args: [\"rev-parse\", \"--verify\", \"--quiet\", \"HEAD^{commit}\"],\n      allowNonZeroExit: true,\n    }).pipe(\n      Effect.map((result) => {\n        if (result.exitCode !== 0) {\n          return null;\n        }\n        const commit = result.stdout.trim();\n        return commit.length > 0 ? commit : null;\n      }),\n    );\n\n  const hasHeadCommit = (cwd: string) =>\n    execute({\n      operation: \"GitVcsDriver.checkpoints.hasHeadCommit\",\n      cwd,\n      args: [\"rev-parse\", \"--verify\", \"HEAD\"],\n      allowNonZeroExit: true,\n    }).pipe(Effect.map((result) => result.exitCode === 0));\n\n  const resolveCheckpointCommit = (cwd: string, checkpointRef: string) =>\n    execute({\n      operation: \"GitVcsDriver.checkpoints.resolveCheckpointCommit\",\n      cwd,\n      args: [\"rev-parse\", \"--verify\", \"--quiet\", `${checkpointRef}^{commit}`],\n      allowNonZeroExit: true,\n    }).pipe(\n      Effect.map((result) => {\n        if (result.exitCode !== 0) {\n          return null;\n        }\n        const commit = result.stdout.trim();\n        return commit.length > 0 ? commit : null;\n      }),\n    );\n\n  const resolveGitCommonDir = (cwd: string) =>\n    Effect.gen(function* () {\n      const result = yield* execute({\n        operation: \"GitVcsDriver.checkpoints.resolveGitCommonDir\",\n        cwd,\n        args: [\"rev-parse\", \"--git-common-dir\"],\n      });\n      const gitCommonDir = result.stdout.trim();\n      return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);\n    });\n\n  const checkpoints: VcsDriver.VcsCheckpointOps = {\n    captureCheckpoint: Effect.fn(\"GitVcsDriver.checkpoints.captureCheckpoint\")(function* (input) {\n      const operation = \"GitVcsDriver.checkpoints.captureCheckpoint\";\n      const gitCommonDir = yield* resolveGitCommonDir(input.cwd);\n      const tempIndexPath = path.join(\n        gitCommonDir,\n        `t3-checkpoint-index-${NodeCrypto.randomUUID()}`,\n      );\n      const commitEnv: NodeJS.ProcessEnv = {\n        ...process.env,\n        GIT_INDEX_FILE: tempIndexPath,\n        GIT_AUTHOR_NAME: \"Synaptic Code\",\n        GIT_AUTHOR_EMAIL: \"noreply@dmccore.ai\",\n        GIT_COMMITTER_NAME: \"Synaptic Code\",\n        GIT_COMMITTER_EMAIL: \"noreply@dmccore.ai\",\n      };\n\n      const cleanupTempIndex = fileSystem\n        .remove(tempIndexPath, { force: true })\n        .pipe(Effect.ignore);\n\n      yield* Effect.gen(function* () {\n        const headExists = yield* hasHeadCommit(input.cwd);\n        if (headExists) {\n          yield* execute({\n            operation,\n            cwd: input.cwd,\n            args: [\"read-tree\", \"HEAD\"],\n            env: commitEnv,\n          });\n        }\n\n        yield* execute({\n          operation,\n          cwd: input.cwd,\n          args: [\"add\", \"-A\", \"--\", \".\"],\n          env: commitEnv,\n        });\n\n        const writeTreeResult = yield* execute({\n          operation,\n          cwd: input.cwd,\n          args: [\"write-tree\"],\n          env: commitEnv,\n        });\n        const treeOid = writeTreeResult.stdout.trim();\n        if (treeOid.length === 0) {\n          return yield* new VcsProcessExitError({\n            operation,\n            command: \"git write-tree\",\n            cwd: input.cwd,\n            exitCode: 0,\n            detail: \"git write-tree returned an empty tree oid.\",\n          });\n        }\n\n        const message = `t3 checkpoint ref=${input.checkpointRef}`;\n        const commitTreeResult = yield* execute({\n          operation,\n          cwd: input.cwd,\n          args: [\"commit-tree\", treeOid, \"-m\", message],\n          env: commitEnv,\n        });\n        const commitOid = commitTreeResult.stdout.trim();\n        if (commitOid.length === 0) {\n          return yield* new VcsProcessExitError({\n            operation,\n            command: \"git commit-tree\",\n            cwd: input.cwd,\n            exitCode: 0,\n            detail: \"git commit-tree returned an empty commit oid.\",\n          });\n        }\n\n        yield* execute({\n          operation,\n          cwd: input.cwd,\n          args: [\"update-ref\", input.checkpointRef, commitOid],\n        });\n      }).pipe(Effect.ensuring(cleanupTempIndex));\n    }),\n\n    hasCheckpointRef: (input) =>\n      resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(\n        Effect.map((commit) => commit !== null),\n      ),\n\n    restoreCheckpoint: Effect.fn(\"GitVcsDriver.checkpoints.restoreCheckpoint\")(function* (input) {\n      const operation = \"GitVcsDriver.checkpoints.restoreCheckpoint\";\n\n      let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);\n\n      if (!commitOid && input.fallbackToHead === true) {\n        commitOid = yield* resolveHeadCommit(input.cwd);\n      }\n\n      if (!commitOid) {\n        return false;\n      }\n\n      yield* execute({\n        operation,\n        cwd: input.cwd,\n        args: [\"restore\", \"--source\", commitOid, \"--worktree\", \"--staged\", \"--\", \".\"],\n      });\n      yield* execute({\n        operation,\n        cwd: input.cwd,\n        args: [\"clean\", \"-fd\", \"--\", \".\"],\n      });\n\n      const headExists = yield* hasHeadCommit(input.cwd);\n      if (headExists) {\n        yield* execute({\n          operation,\n          cwd: input.cwd,\n          args: [\"reset\", \"--quiet\", \"--\", \".\"],\n        });\n      }\n\n      return true;\n    }),\n\n    diffCheckpoints: Effect.fn(\"GitVcsDriver.checkpoints.diffCheckpoints\")(function* (input) {\n      const operation = \"GitVcsDriver.checkpoints.diffCheckpoints\";\n      yield* Effect.annotateCurrentSpan({\n        \"checkpoint.cwd\": input.cwd,\n        \"checkpoint.from_ref\": input.fromCheckpointRef,\n        \"checkpoint.to_ref\": input.toCheckpointRef,\n        \"checkpoint.ignore_whitespace\": input.ignoreWhitespace,\n        \"checkpoint.fallback_from_to_head\": input.fallbackFromToHead,\n      });\n\n      let fromRevision: string = input.fromCheckpointRef;\n      if (input.fallbackFromToHead === true) {\n        const resolvedFromCommit = yield* resolveCheckpointCommit(\n          input.cwd,\n          input.fromCheckpointRef,\n        );\n        if (resolvedFromCommit) {\n          fromRevision = resolvedFromCommit;\n        } else {\n          const headCommit = yield* resolveHeadCommit(input.cwd);\n          if (!headCommit) {\n            return yield* new VcsProcessExitError({\n              operation,\n              command: \"git diff\",\n              cwd: input.cwd,\n              exitCode: 1,\n              detail: \"Checkpoint ref is unavailable for diff operation.\",\n            });\n          }\n          fromRevision = headCommit;\n        }\n      }\n\n      const result = yield* execute({\n        operation,\n        cwd: input.cwd,\n        args: [\n          \"diff\",\n          \"--patch\",\n          \"--no-color\",\n          \"--no-ext-diff\",\n          \"--no-textconv\",\n          ...(input.ignoreWhitespace ? [\"--ignore-all-space\"] : []),\n          `${fromRevision}^{commit}`,\n          `${input.toCheckpointRef}^{commit}`,\n        ],\n        allowNonZeroExit: true,\n        maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,\n      });\n\n      if (result.exitCode !== 0) {\n        return yield* new VcsProcessExitError({\n          operation,\n          command: \"git diff\",\n          cwd: input.cwd,\n          exitCode: result.exitCode,\n          detail: result.stderr.trim() || \"Checkpoint ref is unavailable for diff operation.\",\n        });\n      }\n\n      return result.stdout;\n    }),\n\n    deleteCheckpointRefs: Effect.fn(\"GitVcsDriver.checkpoints.deleteCheckpointRefs\")(\n      function* (input) {\n        yield* Effect.forEach(\n          input.checkpointRefs,\n          (checkpointRef) =>\n            execute({\n              operation: \"GitVcsDriver.checkpoints.deleteCheckpointRefs\",\n              cwd: input.cwd,\n              args: [\"update-ref\", \"-d\", checkpointRef],\n              allowNonZeroExit: true,\n            }),\n          { discard: true },\n        );\n      },\n    ),\n  };\n\n  return {\n    capabilities,\n    execute,\n    checkpoints,\n    detectRepository,\n    isInsideWorkTree,\n    listWorkspaceFiles,\n    listRemotes,\n    filterIgnoredPaths,\n    initRepository,\n  };\n});\n\nexport const makeVcsDriver = Effect.gen(function* () {\n  const driver = yield* makeVcsDriverShape();\n  return VcsDriver.VcsDriver.of(driver);\n});\n\nexport const make = Effect.gen(function* () {\n  const git = yield* makeGitVcsDriverCore();\n  return GitVcsDriver.of(git);\n});\n\nexport const vcsLayer = Layer.effect(VcsDriver.VcsDriver, makeVcsDriver);\nexport const layer = Layer.effect(GitVcsDriver, make);\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport { VcsDriverKind, type VcsDriverKind as VcsDriverKindType } from \"@t3tools/contracts\";\nimport { fromLenientJson } from \"@t3tools/shared/schemaJson\";\n\nconst ProjectVcsConfig = Schema.Struct({\n  vcs: Schema.optional(\n    Schema.Struct({\n      kind: Schema.optional(VcsDriverKind),\n    }),\n  ),\n  vcsKind: Schema.optional(VcsDriverKind),\n});\nconst ProjectVcsConfigJson = fromLenientJson(ProjectVcsConfig);\nconst decodeProjectVcsConfigJson = Schema.decodeUnknownEffect(ProjectVcsConfigJson);\n\ntype ProjectVcsConfigFile = typeof ProjectVcsConfig.Type;\n\nexport interface VcsProjectConfigResolveInput {\n  readonly cwd: string;\n  readonly requestedKind?: VcsDriverKindType | \"auto\";\n}\n\nexport class VcsProjectConfigError extends Schema.TaggedErrorClass<VcsProjectConfigError>()(\n  \"VcsProjectConfigError\",\n  {\n    operation: Schema.Literals([\"inspect\", \"read\", \"decode\"]),\n    cwd: Schema.String,\n    configPath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to ${this.operation} VCS project config at ${this.configPath}.`;\n  }\n}\n\nexport class VcsProjectConfig extends Context.Service<\n  VcsProjectConfig,\n  {\n    readonly resolveKind: (\n      input: VcsProjectConfigResolveInput,\n    ) => Effect.Effect<VcsDriverKindType | \"auto\">;\n  }\n>()(\"t3/vcs/VcsProjectConfig\") {}\n\nfunction configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | \"auto\" {\n  return config.vcs?.kind ?? config.vcsKind ?? \"auto\";\n}\n\nconst logVcsProjectConfigError = (error: VcsProjectConfigError) =>\n  Effect.logWarning(error).pipe(\n    Effect.annotateLogs({\n      operation: error.operation,\n      cwd: error.cwd,\n      configPath: error.configPath,\n      errorTag: error._tag,\n    }),\n  );\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const findConfigPath = Effect.fn(\"VcsProjectConfig.findConfigPath\")(function* (cwd: string) {\n    let current = cwd;\n    while (true) {\n      const candidate = path.join(current, \".synaptic\", \"vcs.json\");\n      const exists = yield* fileSystem.exists(candidate).pipe(\n        Effect.mapError(\n          (cause) =>\n            new VcsProjectConfigError({\n              operation: \"inspect\",\n              cwd,\n              configPath: candidate,\n              cause,\n            }),\n        ),\n        Effect.catchTags({\n          VcsProjectConfigError: (error) => logVcsProjectConfigError(error).pipe(Effect.as(false)),\n        }),\n      );\n      if (exists) {\n        return Option.some(candidate);\n      }\n\n      const parent = path.dirname(current);\n      if (parent === current) {\n        return Option.none();\n      }\n      current = parent;\n    }\n  });\n\n  const readConfiguredKind = Effect.fn(\"VcsProjectConfig.readConfiguredKind\")(function* (\n    cwd: string,\n    configPath: string,\n  ) {\n    const raw = yield* fileSystem.readFileString(configPath).pipe(\n      Effect.mapError(\n        (cause) =>\n          new VcsProjectConfigError({\n            operation: \"read\",\n            cwd,\n            configPath,\n            cause,\n          }),\n      ),\n    );\n    const parsed = yield* decodeProjectVcsConfigJson(raw).pipe(\n      Effect.mapError(\n        (cause) =>\n          new VcsProjectConfigError({\n            operation: \"decode\",\n            cwd,\n            configPath,\n            cause,\n          }),\n      ),\n    );\n    return configuredKind(parsed);\n  });\n\n  const resolveKind: VcsProjectConfig[\"Service\"][\"resolveKind\"] = Effect.fn(\n    \"VcsProjectConfig.resolveKind\",\n  )(function* (input) {\n    if (input.requestedKind !== undefined && input.requestedKind !== \"auto\") {\n      return input.requestedKind;\n    }\n\n    return yield* findConfigPath(input.cwd).pipe(\n      Effect.flatMap(\n        Option.match({\n          onNone: () => Effect.succeed(\"auto\" as const),\n          onSome: (configPath) => readConfiguredKind(input.cwd, configPath),\n        }),\n      ),\n      Effect.catchTags({\n        VcsProjectConfigError: (error) =>\n          logVcsProjectConfigError(error).pipe(Effect.as(\"auto\" as const)),\n      }),\n    );\n  });\n\n  return VcsProjectConfig.of({\n    resolveKind,\n  });\n});\n\nexport const layer = Layer.effect(VcsProjectConfig, make);\n","import * as Cache from \"effect/Cache\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\n\nimport type { VcsDriverKind, VcsError, VcsRepositoryIdentity } from \"@t3tools/contracts\";\nimport { VcsUnsupportedOperationError } from \"@t3tools/contracts\";\nimport * as GitVcsDriver from \"./GitVcsDriver.ts\";\nimport * as VcsProjectConfig from \"./VcsProjectConfig.ts\";\nimport * as VcsDriver from \"./VcsDriver.ts\";\n\nconst DETECTION_CACHE_CAPACITY = 2_048;\nconst DETECTION_CACHE_TTL = Duration.seconds(2);\n\nexport interface VcsDriverResolveInput {\n  readonly cwd: string;\n  readonly requestedKind?: VcsDriverKind | \"auto\";\n}\n\nexport interface VcsDriverHandle {\n  readonly kind: VcsDriverKind;\n  readonly repository: VcsRepositoryIdentity;\n  readonly driver: VcsDriver.VcsDriver[\"Service\"];\n}\n\nexport class VcsDriverRegistry extends Context.Service<\n  VcsDriverRegistry,\n  {\n    readonly get: (kind: VcsDriverKind) => Effect.Effect<VcsDriver.VcsDriver[\"Service\"], VcsError>;\n    readonly detect: (\n      input: VcsDriverResolveInput,\n    ) => Effect.Effect<VcsDriverHandle | null, VcsError>;\n    readonly resolve: (input: VcsDriverResolveInput) => Effect.Effect<VcsDriverHandle, VcsError>;\n  }\n>()(\"t3/vcs/VcsDriverRegistry\") {}\n\nfunction detectionCacheKey(input: {\n  readonly cwd: string;\n  readonly requestedKind: VcsDriverKind | \"auto\";\n}): string {\n  return `${input.requestedKind}\\0${input.cwd}`;\n}\n\nfunction parseDetectionCacheKey(key: string): {\n  readonly cwd: string;\n  readonly requestedKind: VcsDriverKind | \"auto\";\n} {\n  const separatorIndex = key.indexOf(\"\\0\");\n  if (separatorIndex === -1) {\n    return {\n      cwd: key,\n      requestedKind: \"auto\",\n    };\n  }\n  return {\n    requestedKind: key.slice(0, separatorIndex) as VcsDriverKind | \"auto\",\n    cwd: key.slice(separatorIndex + 1),\n  };\n}\n\nexport const make = Effect.gen(function* () {\n  const projectConfig = yield* VcsProjectConfig.VcsProjectConfig;\n  const git = yield* GitVcsDriver.makeVcsDriver;\n  const drivers: Partial<Record<VcsDriverKind, VcsDriver.VcsDriver[\"Service\"]>> = {\n    git,\n  };\n\n  const get: VcsDriverRegistry[\"Service\"][\"get\"] = (kind) => {\n    const driver = drivers[kind];\n    if (!driver) {\n      return Effect.fail(\n        new VcsUnsupportedOperationError({\n          operation: \"VcsDriverRegistry.get\",\n          kind,\n          detail: `No ${kind} VCS driver is registered.`,\n        }),\n      );\n    }\n    return Effect.succeed(driver);\n  };\n\n  const detectWithDriver = Effect.fn(\"VcsDriverRegistry.detectWithDriver\")(function* (\n    kind: VcsDriverKind,\n    driver: VcsDriver.VcsDriver[\"Service\"],\n    cwd: string,\n  ) {\n    const repository = yield* driver.detectRepository(cwd);\n    if (!repository) {\n      return null;\n    }\n    return {\n      kind,\n      repository,\n      driver,\n    } satisfies VcsDriverHandle;\n  });\n\n  const detectResolvedKind = Effect.fn(\"VcsDriverRegistry.detectResolvedKind\")(function* (input: {\n    readonly cwd: string;\n    readonly requestedKind: VcsDriverKind | \"auto\";\n  }) {\n    const requestedKind = input.requestedKind;\n\n    if (requestedKind !== \"auto\" && requestedKind !== \"unknown\") {\n      const driver = yield* get(requestedKind);\n      return yield* detectWithDriver(requestedKind, driver, input.cwd);\n    }\n\n    return yield* detectWithDriver(\"git\", git, input.cwd);\n  });\n\n  const detectionCache = yield* Cache.makeWith<string, VcsDriverHandle | null, VcsError>(\n    (key) => detectResolvedKind(parseDetectionCacheKey(key)),\n    {\n      capacity: DETECTION_CACHE_CAPACITY,\n      timeToLive: Exit.match({\n        onSuccess: (detected) => (detected === null ? Duration.zero : DETECTION_CACHE_TTL),\n        onFailure: () => Duration.zero,\n      }),\n    },\n  );\n\n  const detect: VcsDriverRegistry[\"Service\"][\"detect\"] = Effect.fn(\"VcsDriverRegistry.detect\")(\n    function* (input) {\n      const requestedKind = yield* projectConfig.resolveKind(input);\n      return yield* Cache.get(detectionCache, detectionCacheKey({ cwd: input.cwd, requestedKind }));\n    },\n  );\n\n  const resolve: VcsDriverRegistry[\"Service\"][\"resolve\"] = Effect.fn(\"VcsDriverRegistry.resolve\")(\n    function* (input) {\n      const detected = yield* detect(input);\n      if (detected) {\n        return detected;\n      }\n\n      const requestedKind = input.requestedKind ?? \"auto\";\n      return yield* new VcsUnsupportedOperationError({\n        operation: \"VcsDriverRegistry.resolve\",\n        kind: requestedKind === \"auto\" ? \"unknown\" : requestedKind,\n        detail:\n          requestedKind === \"auto\"\n            ? `No supported VCS repository was detected at ${input.cwd}.`\n            : `No ${requestedKind} repository was detected at ${input.cwd}.`,\n      });\n    },\n  );\n\n  return VcsDriverRegistry.of({\n    get,\n    detect,\n    resolve,\n  });\n});\n\nexport const layer = Layer.effect(VcsDriverRegistry, make).pipe(\n  Layer.provide(VcsProjectConfig.layer),\n);\n","/**\n * CheckpointStore - Repository interface for filesystem-backed workspace checkpoints.\n *\n * Owns hidden Git-ref checkpoint capture/restore and diff computation for a\n * workspace thread timeline. It does not store user-facing checkpoint metadata\n * and does not coordinate provider conversation rollback.\n *\n * The live adapter resolves the active VCS driver once per checkpoint operation\n * and delegates to the driver's optional checkpoint capability.\n *\n * Uses Effect `Context.Service` for dependency injection and exposes typed\n * domain errors for checkpoint storage operations.\n *\n * @module CheckpointStore\n */\nimport { VcsUnsupportedOperationError, type CheckpointRef } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport type { CheckpointStoreError } from \"./Errors.ts\";\nimport type { VcsCheckpointOps } from \"../vcs/VcsDriver.ts\";\nimport * as VcsDriverRegistry from \"../vcs/VcsDriverRegistry.ts\";\n\nexport interface CaptureCheckpointInput {\n  readonly cwd: string;\n  readonly checkpointRef: CheckpointRef;\n}\n\nexport interface RestoreCheckpointInput {\n  readonly cwd: string;\n  readonly checkpointRef: CheckpointRef;\n  readonly fallbackToHead?: boolean;\n}\n\nexport interface DiffCheckpointsInput {\n  readonly cwd: string;\n  readonly fromCheckpointRef: CheckpointRef;\n  readonly toCheckpointRef: CheckpointRef;\n  readonly fallbackFromToHead?: boolean;\n  readonly ignoreWhitespace: boolean;\n}\n\nexport interface DeleteCheckpointRefsInput {\n  readonly cwd: string;\n  readonly checkpointRefs: ReadonlyArray<CheckpointRef>;\n}\n\n/** Service tag for checkpoint persistence and restore operations. */\nexport class CheckpointStore extends Context.Service<\n  CheckpointStore,\n  {\n    /** Check whether cwd is inside a Git worktree. */\n    readonly isGitRepository: (cwd: string) => Effect.Effect<boolean, CheckpointStoreError>;\n\n    /**\n     * Capture a checkpoint commit and store it at the provided checkpoint ref.\n     *\n     * Uses an isolated temporary Git index and writes a hidden ref.\n     */\n    readonly captureCheckpoint: (\n      input: CaptureCheckpointInput,\n    ) => Effect.Effect<void, CheckpointStoreError>;\n\n    /** Check whether a checkpoint ref exists. */\n    readonly hasCheckpointRef: (\n      input: Omit<RestoreCheckpointInput, \"fallbackToHead\">,\n    ) => Effect.Effect<boolean, CheckpointStoreError>;\n\n    /**\n     * Restore workspace and staging state to a checkpoint.\n     *\n     * Optionally falls back to current `HEAD` when the checkpoint ref is missing.\n     */\n    readonly restoreCheckpoint: (\n      input: RestoreCheckpointInput,\n    ) => Effect.Effect<boolean, CheckpointStoreError>;\n\n    /**\n     * Compute a patch diff between two checkpoint refs.\n     *\n     * Can optionally treat a missing \"from\" ref as `HEAD`.\n     */\n    readonly diffCheckpoints: (\n      input: DiffCheckpointsInput,\n    ) => Effect.Effect<string, CheckpointStoreError>;\n\n    /**\n     * Delete the provided checkpoint refs.\n     *\n     * Best-effort delete: missing refs are tolerated.\n     */\n    readonly deleteCheckpointRefs: (\n      input: DeleteCheckpointRefsInput,\n    ) => Effect.Effect<void, CheckpointStoreError>;\n  }\n>()(\"t3/checkpointing/CheckpointStore\") {}\n\nexport const make = Effect.gen(function* () {\n  const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;\n\n  const resolveCheckpoints = Effect.fn(\"CheckpointStore.resolveCheckpoints\")(function* (\n    operation: string,\n    cwd: string,\n  ) {\n    const handle = yield* vcsRegistry.resolve({ cwd });\n    if (!handle.driver.checkpoints) {\n      return yield* new VcsUnsupportedOperationError({\n        operation,\n        kind: handle.kind,\n        detail: `${handle.kind} driver does not implement checkpoint operations.`,\n      });\n    }\n    return handle.driver.checkpoints satisfies VcsCheckpointOps;\n  });\n\n  const isGitRepository: CheckpointStore[\"Service\"][\"isGitRepository\"] = (cwd) =>\n    vcsRegistry\n      .detect({ cwd, requestedKind: \"git\" })\n      .pipe(Effect.map((repository) => repository !== null));\n\n  const captureCheckpoint: CheckpointStore[\"Service\"][\"captureCheckpoint\"] = Effect.fn(\n    \"captureCheckpoint\",\n  )(function* (input) {\n    const checkpoints = yield* resolveCheckpoints(\"CheckpointStore.captureCheckpoint\", input.cwd);\n    return yield* checkpoints.captureCheckpoint(input);\n  });\n\n  const hasCheckpointRef: CheckpointStore[\"Service\"][\"hasCheckpointRef\"] = Effect.fn(\n    \"hasCheckpointRef\",\n  )(function* (input) {\n    const checkpoints = yield* resolveCheckpoints(\"CheckpointStore.hasCheckpointRef\", input.cwd);\n    return yield* checkpoints.hasCheckpointRef(input);\n  });\n\n  const restoreCheckpoint: CheckpointStore[\"Service\"][\"restoreCheckpoint\"] = Effect.fn(\n    \"restoreCheckpoint\",\n  )(function* (input) {\n    const checkpoints = yield* resolveCheckpoints(\"CheckpointStore.restoreCheckpoint\", input.cwd);\n    return yield* checkpoints.restoreCheckpoint(input);\n  });\n\n  const diffCheckpoints: CheckpointStore[\"Service\"][\"diffCheckpoints\"] = Effect.fn(\n    \"diffCheckpoints\",\n  )(function* (input) {\n    const checkpoints = yield* resolveCheckpoints(\"CheckpointStore.diffCheckpoints\", input.cwd);\n    return yield* checkpoints.diffCheckpoints(input);\n  });\n\n  const deleteCheckpointRefs: CheckpointStore[\"Service\"][\"deleteCheckpointRefs\"] = Effect.fn(\n    \"deleteCheckpointRefs\",\n  )(function* (input) {\n    const checkpoints = yield* resolveCheckpoints(\n      \"CheckpointStore.deleteCheckpointRefs\",\n      input.cwd,\n    );\n    return yield* checkpoints.deleteCheckpointRefs(input);\n  });\n\n  return CheckpointStore.of({\n    isGitRepository,\n    captureCheckpoint,\n    hasCheckpointRef,\n    restoreCheckpoint,\n    diffCheckpoints,\n    deleteCheckpointRefs,\n  });\n});\n\nexport const layer = Layer.effect(CheckpointStore, make);\n","/**\n * CheckpointDiffQuery - Query interface for computed checkpoint diffs.\n *\n * Provides read-only diff operations across checkpoint snapshots used by\n * orchestration APIs.\n *\n * @module CheckpointDiffQuery\n */\nimport {\n  type CheckpointRef,\n  OrchestrationGetTurnDiffResult,\n  type OrchestrationGetFullThreadDiffInput,\n  type OrchestrationGetFullThreadDiffResult,\n  type OrchestrationGetTurnDiffInput,\n  type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,\n  type ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ProjectionSnapshotQuery from \"../orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport {\n  CheckpointDiffResultInvalidError,\n  CheckpointRefUnavailableError,\n  CheckpointThreadNotFoundError,\n  CheckpointTurnRangeUnavailableError,\n  CheckpointWorkspacePathMissingError,\n} from \"./Errors.ts\";\nimport type { CheckpointServiceError } from \"./Errors.ts\";\nimport { checkpointRefForThreadTurn } from \"./Utils.ts\";\nimport * as CheckpointStore from \"./CheckpointStore.ts\";\n\n/** Service tag for checkpoint diff queries. */\nexport class CheckpointDiffQuery extends Context.Service<\n  CheckpointDiffQuery,\n  {\n    /**\n     * Read the patch diff for a single turn checkpoint transition.\n     *\n     * Verifies checkpoint availability in both projection state and filesystem.\n     */\n    readonly getTurnDiff: (\n      input: OrchestrationGetTurnDiffInput,\n    ) => Effect.Effect<OrchestrationGetTurnDiffResultType, CheckpointServiceError>;\n\n    /**\n     * Read the full patch diff across a thread range of checkpoints.\n     *\n     * Uses turn-diff semantics with `fromTurnCount = 0`.\n     */\n    readonly getFullThreadDiff: (\n      input: OrchestrationGetFullThreadDiffInput,\n    ) => Effect.Effect<OrchestrationGetFullThreadDiffResult, CheckpointServiceError>;\n  }\n>()(\"t3/checkpointing/CheckpointDiffQuery\") {}\n\nconst isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);\n\nfunction buildTurnDiffResult(\n  input: {\n    readonly threadId: ThreadId;\n    readonly fromTurnCount: number;\n    readonly toTurnCount: number;\n  },\n  diff: string,\n): OrchestrationGetTurnDiffResultType {\n  return {\n    threadId: input.threadId,\n    fromTurnCount: input.fromTurnCount,\n    toTurnCount: input.toTurnCount,\n    diff,\n  };\n}\n\nexport const make = Effect.gen(function* () {\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n  const checkpointStore = yield* CheckpointStore.CheckpointStore;\n\n  const getTurnDiff: CheckpointDiffQuery[\"Service\"][\"getTurnDiff\"] = Effect.fn(\"getTurnDiff\")(\n    function* (input) {\n      const operation = \"CheckpointDiffQuery.getTurnDiff\";\n      const ignoreWhitespace = input.ignoreWhitespace ?? true;\n      yield* Effect.annotateCurrentSpan({\n        \"checkpoint.thread_id\": input.threadId,\n        \"checkpoint.from_turn_count\": input.fromTurnCount,\n        \"checkpoint.to_turn_count\": input.toTurnCount,\n        \"checkpoint.ignore_whitespace\": ignoreWhitespace,\n      });\n\n      if (input.fromTurnCount === input.toTurnCount) {\n        const emptyDiff: OrchestrationGetTurnDiffResultType = {\n          threadId: input.threadId,\n          fromTurnCount: input.fromTurnCount,\n          toTurnCount: input.toTurnCount,\n          diff: \"\",\n        };\n        if (!isTurnDiffResult(emptyDiff)) {\n          return yield* new CheckpointDiffResultInvalidError({\n            operation,\n            threadId: input.threadId,\n          });\n        }\n        return emptyDiff;\n      }\n\n      const threadContext = yield* projectionSnapshotQuery\n        .getThreadCheckpointContext(input.threadId)\n        .pipe(Effect.withSpan(\"checkpoint.turnDiff.lookupContext\"));\n      if (Option.isNone(threadContext)) {\n        return yield* new CheckpointThreadNotFoundError({\n          operation,\n          threadId: input.threadId,\n        });\n      }\n\n      const maxTurnCount = threadContext.value.checkpoints.reduce(\n        (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),\n        0,\n      );\n      if (input.toTurnCount > maxTurnCount) {\n        return yield* new CheckpointTurnRangeUnavailableError({\n          operation,\n          threadId: input.threadId,\n          requestedTurnCount: input.toTurnCount,\n          availableTurnCount: maxTurnCount,\n        });\n      }\n\n      const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;\n      if (!workspaceCwd) {\n        return yield* new CheckpointWorkspacePathMissingError({\n          operation,\n          threadId: input.threadId,\n        });\n      }\n\n      const fromCheckpointRef =\n        input.fromTurnCount === 0\n          ? checkpointRefForThreadTurn(input.threadId, 0)\n          : threadContext.value.checkpoints.find(\n              (checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,\n            )?.checkpointRef;\n      if (!fromCheckpointRef) {\n        return yield* new CheckpointRefUnavailableError({\n          operation,\n          threadId: input.threadId,\n          turnCount: input.fromTurnCount,\n          checkpoint: \"from\",\n        });\n      }\n\n      const toCheckpointRef = threadContext.value.checkpoints.find(\n        (checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,\n      )?.checkpointRef;\n      if (!toCheckpointRef) {\n        return yield* new CheckpointRefUnavailableError({\n          operation,\n          threadId: input.threadId,\n          turnCount: input.toTurnCount,\n          checkpoint: \"to\",\n        });\n      }\n\n      const diff = yield* checkpointStore\n        .diffCheckpoints({\n          cwd: workspaceCwd,\n          fromCheckpointRef,\n          toCheckpointRef,\n          fallbackFromToHead: false,\n          ignoreWhitespace,\n        })\n        .pipe(Effect.withSpan(\"checkpoint.turnDiff.diffCheckpoints\"));\n\n      const turnDiff = buildTurnDiffResult(input, diff);\n      if (!isTurnDiffResult(turnDiff)) {\n        return yield* new CheckpointDiffResultInvalidError({\n          operation,\n          threadId: input.threadId,\n        });\n      }\n\n      return turnDiff;\n    },\n  );\n\n  const getFullThreadDiff: CheckpointDiffQuery[\"Service\"][\"getFullThreadDiff\"] = Effect.fn(\n    \"CheckpointDiffQuery.getFullThreadDiff\",\n  )(function* (input) {\n    const operation = \"CheckpointDiffQuery.getFullThreadDiff\";\n    const ignoreWhitespace = input.ignoreWhitespace ?? true;\n    yield* Effect.annotateCurrentSpan({\n      \"checkpoint.thread_id\": input.threadId,\n      \"checkpoint.from_turn_count\": 0,\n      \"checkpoint.to_turn_count\": input.toTurnCount,\n      \"checkpoint.ignore_whitespace\": ignoreWhitespace,\n      \"checkpoint.diff_kind\": \"full-thread\",\n    });\n\n    if (input.toTurnCount === 0) {\n      const emptyDiff = buildTurnDiffResult(\n        {\n          threadId: input.threadId,\n          fromTurnCount: 0,\n          toTurnCount: 0,\n        },\n        \"\",\n      );\n      if (!isTurnDiffResult(emptyDiff)) {\n        return yield* new CheckpointDiffResultInvalidError({\n          operation,\n          threadId: input.threadId,\n        });\n      }\n      return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;\n    }\n\n    const threadContext = yield* projectionSnapshotQuery\n      .getFullThreadDiffContext(input.threadId, input.toTurnCount)\n      .pipe(Effect.withSpan(\"checkpoint.fullThread.lookupContext\"));\n\n    if (Option.isNone(threadContext)) {\n      return yield* new CheckpointThreadNotFoundError({\n        operation,\n        threadId: input.threadId,\n      });\n    }\n\n    if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {\n      return yield* new CheckpointTurnRangeUnavailableError({\n        operation,\n        threadId: input.threadId,\n        requestedTurnCount: input.toTurnCount,\n        availableTurnCount: threadContext.value.latestCheckpointTurnCount,\n      });\n    }\n\n    const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;\n    if (!workspaceCwd) {\n      return yield* new CheckpointWorkspacePathMissingError({\n        operation,\n        threadId: input.threadId,\n      });\n    }\n\n    if (!threadContext.value.toCheckpointRef) {\n      return yield* new CheckpointRefUnavailableError({\n        operation,\n        threadId: input.threadId,\n        turnCount: input.toTurnCount,\n        checkpoint: \"to\",\n      });\n    }\n\n    const diff = yield* checkpointStore\n      .diffCheckpoints({\n        cwd: workspaceCwd,\n        fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),\n        toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,\n        fallbackFromToHead: false,\n        ignoreWhitespace,\n      })\n      .pipe(Effect.withSpan(\"checkpoint.fullThread.diffCheckpoints\"));\n\n    const turnDiff = buildTurnDiffResult(\n      {\n        threadId: input.threadId,\n        fromTurnCount: 0,\n        toTurnCount: input.toTurnCount,\n      },\n      diff,\n    );\n    if (!isTurnDiffResult(turnDiff)) {\n      return yield* new CheckpointDiffResultInvalidError({\n        operation,\n        threadId: input.threadId,\n      });\n    }\n\n    return turnDiff satisfies OrchestrationGetFullThreadDiffResult;\n  });\n\n  return CheckpointDiffQuery.of({\n    getTurnDiff,\n    getFullThreadDiff,\n  });\n});\n\nexport const layer = Layer.effect(CheckpointDiffQuery, make);\n","import type {\n  OrchestrationEvent,\n  OrchestrationThreadActivity,\n  OrchestrationThreadDetailSnapshot,\n} from \"@t3tools/contracts\";\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value)\n    ? (value as Record<string, unknown>)\n    : null;\n}\n\nfunction asTrimmedString(value: unknown): string | null {\n  if (typeof value !== \"string\") {\n    return null;\n  }\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction pushChangedFile(target: string[], seen: Set<string>, value: unknown): void {\n  const normalized = asTrimmedString(value);\n  if (!normalized || seen.has(normalized)) {\n    return;\n  }\n  seen.add(normalized);\n  target.push(normalized);\n}\n\nfunction collectChangedFiles(\n  value: unknown,\n  target: string[],\n  seen: Set<string>,\n  depth: number,\n): void {\n  if (depth > 4 || target.length >= 12) {\n    return;\n  }\n  if (Array.isArray(value)) {\n    for (const entry of value) {\n      collectChangedFiles(entry, target, seen, depth + 1);\n      if (target.length >= 12) {\n        return;\n      }\n    }\n    return;\n  }\n\n  const record = asRecord(value);\n  if (!record) {\n    return;\n  }\n\n  pushChangedFile(target, seen, record.path);\n  pushChangedFile(target, seen, record.filePath);\n  pushChangedFile(target, seen, record.relativePath);\n  pushChangedFile(target, seen, record.filename);\n  pushChangedFile(target, seen, record.newPath);\n  pushChangedFile(target, seen, record.oldPath);\n\n  for (const nestedKey of [\n    \"item\",\n    \"result\",\n    \"input\",\n    \"data\",\n    \"changes\",\n    \"files\",\n    \"edits\",\n    \"patch\",\n    \"patches\",\n    \"operations\",\n  ]) {\n    if (!(nestedKey in record)) {\n      continue;\n    }\n    collectChangedFiles(record[nestedKey], target, seen, depth + 1);\n    if (target.length >= 12) {\n      return;\n    }\n  }\n}\n\nfunction projectCommandData(data: Record<string, unknown>): Record<string, unknown> | undefined {\n  const item = asRecord(data.item);\n  if (!item) {\n    return undefined;\n  }\n\n  const projectedItem: Record<string, unknown> = {};\n  if (\"command\" in item) {\n    projectedItem.command = item.command;\n  }\n\n  const input = asRecord(item.input);\n  if (input && \"command\" in input) {\n    projectedItem.input = { command: input.command };\n  }\n\n  const result = asRecord(item.result);\n  if (result && \"command\" in result) {\n    projectedItem.result = { command: result.command };\n  }\n\n  return Object.keys(projectedItem).length > 0 ? projectedItem : undefined;\n}\n\nfunction summarizeToolTextOutput(value: string): string | null {\n  const lines: string[] = [];\n  for (const rawLine of value.split(/\\r?\\n/u)) {\n    const line = rawLine.replace(/\\s+/g, \" \").trim();\n    if (line.length > 0) {\n      lines.push(line);\n    }\n  }\n\n  const firstLine = lines.find((line) => line !== \"```\");\n  if (firstLine) {\n    return firstLine.length <= 84 ? firstLine : `${firstLine.slice(0, 83).trimEnd()}…`;\n  }\n  if (lines.length > 1) {\n    return `${lines.length.toLocaleString()} lines`;\n  }\n  return null;\n}\n\n/**\n * Fields of an MCP tool-call item both clients render in the expanded\n * work-log row. Everything else — notably `result`, which carries the full\n * tool output and dominates wire size on MCP-heavy threads — is summarized\n * or dropped. Full payloads remain in persistence.\n */\nconst MCP_ITEM_KEPT_FIELDS = [\n  \"type\",\n  \"id\",\n  \"tool\",\n  \"server\",\n  \"status\",\n  \"arguments\",\n  \"appContext\",\n  \"error\",\n  \"durationMs\",\n] as const;\n\n/**\n * Pulls renderable text out of an MCP tool result: either a Codex-style\n * `{content: [{type: \"text\", text}, ...]}` record or a raw Claude\n * `tool_result` block whose `content` is a string or block array.\n */\nfunction extractMcpResultText(result: unknown): string | null {\n  const record = asRecord(result);\n  if (!record) {\n    return typeof result === \"string\" ? result : null;\n  }\n  if (typeof record.content === \"string\") {\n    return record.content;\n  }\n  if (Array.isArray(record.content)) {\n    const texts: string[] = [];\n    for (const entry of record.content) {\n      const text = asRecord(entry)?.text;\n      if (typeof text === \"string\" && text.trim().length > 0) {\n        texts.push(text);\n      }\n    }\n    if (texts.length > 0) {\n      return texts.join(\"\\n\");\n    }\n  }\n  return null;\n}\n\nfunction summarizeMcpResult(result: unknown): Record<string, unknown> | undefined {\n  if (result === undefined || result === null) {\n    return undefined;\n  }\n  const text = extractMcpResultText(result);\n  const summary = text ? summarizeToolTextOutput(text) : null;\n  return summary ? { content: summary } : undefined;\n}\n\n/**\n * MCP tool calls carry full tool results (`data.item.result` on Codex,\n * `data.result` on Claude/OpenCode) that used to bypass slimming entirely to\n * keep the expanded-row UI working. Keep the fields the UI actually renders\n * and summarize the result like regular tool output.\n */\nfunction projectMcpToolCallData(data: Record<string, unknown>): Record<string, unknown> {\n  const projectedData: Record<string, unknown> = {};\n\n  const item = asRecord(data.item);\n  if (item) {\n    const projectedItem: Record<string, unknown> = {};\n    for (const key of MCP_ITEM_KEPT_FIELDS) {\n      if (key in item) {\n        projectedItem[key] = item[key];\n      }\n    }\n    const result = summarizeMcpResult(item.result);\n    if (result) {\n      projectedItem.result = result;\n    }\n    projectedData.item = projectedItem;\n  }\n\n  if (\"toolName\" in data) {\n    projectedData.toolName = data.toolName;\n  }\n  if (\"input\" in data) {\n    projectedData.input = data.input;\n  }\n  if (!item) {\n    const result = summarizeMcpResult(data.result);\n    if (result) {\n      projectedData.result = result;\n    }\n  }\n\n  if (\"toolCallId\" in data) {\n    projectedData.toolCallId = data.toolCallId;\n  }\n  if (\"kind\" in data) {\n    projectedData.kind = data.kind;\n  }\n\n  const changedFiles: string[] = [];\n  collectChangedFiles(data, changedFiles, new Set<string>(), 0);\n  if (changedFiles.length > 0) {\n    projectedData.files = changedFiles.map((path) => ({ path }));\n  }\n\n  return projectedData;\n}\n\nfunction projectRawOutput(value: unknown): Record<string, unknown> | undefined {\n  const rawOutput = asRecord(value);\n  if (!rawOutput) {\n    return undefined;\n  }\n\n  if (typeof rawOutput.totalFiles === \"number\" && Number.isFinite(rawOutput.totalFiles)) {\n    return {\n      totalFiles: rawOutput.totalFiles,\n      ...(rawOutput.truncated === true ? { truncated: true } : {}),\n    };\n  }\n\n  const content = asTrimmedString(rawOutput.content);\n  if (content) {\n    const summary = summarizeToolTextOutput(content);\n    return summary ? { content: summary } : undefined;\n  }\n\n  const stdout = asTrimmedString(rawOutput.stdout);\n  if (stdout) {\n    const summary = summarizeToolTextOutput(stdout);\n    return summary ? { content: summary } : undefined;\n  }\n\n  return undefined;\n}\n\n/**\n * Removes activity payload fields that no current client reads while retaining\n * the full payload in persistence and the event store.\n */\nexport function projectActivityPayload(\n  activity: OrchestrationThreadActivity,\n): OrchestrationThreadActivity {\n  const payload = asRecord(activity.payload);\n  const data = asRecord(payload?.data);\n  if (!payload || !data) {\n    return activity;\n  }\n\n  if (payload.itemType === \"mcp_tool_call\") {\n    return {\n      ...activity,\n      payload: {\n        ...payload,\n        data: projectMcpToolCallData(data),\n      },\n    };\n  }\n\n  const projectedData: Record<string, unknown> = {};\n  const item = projectCommandData(data);\n  if (item) {\n    projectedData.item = item;\n  }\n  if (\"command\" in data) {\n    projectedData.command = data.command;\n  }\n\n  const changedFiles: string[] = [];\n  collectChangedFiles(data, changedFiles, new Set<string>(), 0);\n  if (changedFiles.length > 0) {\n    // Both clients discover file names by walking objects with path-like keys.\n    projectedData.files = changedFiles.map((path) => ({ path }));\n  }\n\n  if (\"toolCallId\" in data) {\n    projectedData.toolCallId = data.toolCallId;\n  }\n  if (\"kind\" in data) {\n    projectedData.kind = data.kind;\n  }\n\n  const rawOutput = projectRawOutput(data.rawOutput);\n  if (rawOutput) {\n    projectedData.rawOutput = rawOutput;\n  }\n\n  return {\n    ...activity,\n    payload: {\n      ...payload,\n      data: projectedData,\n    },\n  };\n}\n\n/**\n * Matches the validity rule in the web client's\n * `deriveLatestContextWindowSnapshot`: rows without a finite, non-negative\n * `usedTokens` are skipped during its backward walk, so they must not shadow\n * an earlier resolvable row here.\n */\nfunction isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean {\n  if (activity.kind !== \"context-window.updated\") {\n    return false;\n  }\n  const payload = asRecord(activity.payload);\n  const usedTokens = payload?.usedTokens;\n  return typeof usedTokens === \"number\" && Number.isFinite(usedTokens) && usedTokens >= 0;\n}\n\n/**\n * Drops all but the last resolvable context-window activity per turn from a\n * snapshot. Clients only ever read the latest usage value (walking the array\n * backwards), so shipping the full history — often thousands of rows on long\n * threads — buys nothing. Retention is per turn rather than per thread because\n * a live `thread.reverted` makes the client discard whole turns; keeping each\n * turn's latest row means the meter can still resolve a value from the turns\n * that survive. Malformed rows pass through untouched rather than shadowing a\n * valid earlier row. Live `thread.activity-appended` events are untouched:\n * newer updates still stream through and supersede the retained rows on the\n * client.\n */\nfunction dropStaleContextWindowActivities(\n  activities: ReadonlyArray<OrchestrationThreadActivity>,\n): ReadonlyArray<OrchestrationThreadActivity> {\n  const latestIndexByTurn = new Map<string | null, number>();\n  for (let index = 0; index < activities.length; index += 1) {\n    if (isResolvableContextWindowActivity(activities[index]!)) {\n      latestIndexByTurn.set(activities[index]!.turnId, index);\n    }\n  }\n  if (latestIndexByTurn.size === 0) {\n    return activities;\n  }\n  return activities.filter(\n    (activity, index) =>\n      !isResolvableContextWindowActivity(activity) ||\n      latestIndexByTurn.get(activity.turnId) === index,\n  );\n}\n\n/**\n * Identity both clients use to fold a tool lifecycle row into the call it\n * belongs to (`deriveToolLifecycleCollapseKey` in web's `session-logic` and\n * mobile's `threadActivity`): an explicit `data.toolCallId` when the adapter\n * emits one, otherwise the itemType/title/detail triple. Returns null for rows\n * with no identity at all — those never collapse on the client either, so they\n * must not be dropped here.\n */\nfunction toolLifecycleIdentity(activity: OrchestrationThreadActivity): string | null {\n  const payload = asRecord(activity.payload);\n  if (!payload) {\n    return null;\n  }\n\n  const toolCallId = asTrimmedString(asRecord(payload.data)?.toolCallId);\n  if (toolCallId) {\n    return `id:${toolCallId}`;\n  }\n\n  const itemType = asTrimmedString(payload.itemType) ?? \"\";\n  // Mirrors the clients' `normalizeCompactToolLabel`: a completion's title may\n  // gain a trailing \"complete\"/\"completed\" the in-flight updates lack.\n  const label = (asTrimmedString(payload.title) ?? activity.summary)\n    .replace(/\\s+(?:complete|completed)\\s*$/iu, \"\")\n    .trim();\n  const detail = asTrimmedString(payload.detail) ?? \"\";\n  if (itemType.length === 0 && label.length === 0 && detail.length === 0) {\n    return null;\n  }\n  return [itemType, label, detail].join(\"\u001f\");\n}\n\n/**\n * Drops `tool.updated` rows a `tool.completed` row already supersedes. An\n * update is the in-flight snapshot of a call; once the call completes, the\n * completion carries the final state and the clients fold every matching\n * update into it, so shipping the updates buys nothing — 47k such rows exist\n * in one real database, and a single thread carries 2,291 of them totalling\n * ~1MB post-slimming.\n *\n * Matching is per turn for the same reason `dropStaleContextWindowActivities`\n * retains per turn: a live `thread.reverted` makes the client discard whole\n * turns, so a completion in a different turn could vanish and leave the\n * dropped update unrepresented. The completion must also come *after* the\n * update within the turn — a later update belongs to a subsequent call that\n * reuses the same identity and is still in flight. Rows without a lifecycle\n * identity pass through, matching the clients, which never collapse them.\n * Live `thread.activity-appended` events are untouched: updates still stream\n * in real time and the completion supersedes them on the client as before.\n *\n * Deliberate divergence from client collapse: clients fold only *adjacent*\n * lifecycle rows, so a superseded update separated from its completion by an\n * interleaved parallel call renders as its own row today, and this drop\n * removes it. Measured against a real database, that affects 1.5% of dropped\n * rows (553 of 36,581), all pure in-flight state whose final result the\n * retained completion still shows. Dropping them is intentional; matching\n * adjacency server-side would forfeit most of the win for parallel-heavy\n * threads, which are exactly the heavy ones. Superseding completions always\n * carry a payload superset of their updates (verified across all 49,515\n * update rows: zero dropped rows held a client-merged field — detail, title,\n * command, item, kind, files — their completion lacked), so no expanded-row\n * content is lost.\n */\nfunction dropSupersededToolUpdatedActivities(\n  activities: ReadonlyArray<OrchestrationThreadActivity>,\n): ReadonlyArray<OrchestrationThreadActivity> {\n  const completionIndicesByKey = new Map<string, number[]>();\n  for (let index = 0; index < activities.length; index += 1) {\n    const activity = activities[index]!;\n    if (activity.kind !== \"tool.completed\") {\n      continue;\n    }\n    const identity = toolLifecycleIdentity(activity);\n    if (!identity) {\n      continue;\n    }\n    const key = `${activity.turnId ?? \"\"}\u0000${identity}`;\n    const indices = completionIndicesByKey.get(key);\n    if (indices) {\n      indices.push(index);\n    } else {\n      completionIndicesByKey.set(key, [index]);\n    }\n  }\n  if (completionIndicesByKey.size === 0) {\n    return activities;\n  }\n\n  return activities.filter((activity, index) => {\n    if (activity.kind !== \"tool.updated\") {\n      return true;\n    }\n    const identity = toolLifecycleIdentity(activity);\n    if (!identity) {\n      return true;\n    }\n    const indices = completionIndicesByKey.get(`${activity.turnId ?? \"\"}\u0000${identity}`);\n    return !indices?.some((completionIndex) => completionIndex > index);\n  });\n}\n\nexport function projectThreadDetailSnapshot(\n  snapshot: OrchestrationThreadDetailSnapshot,\n): OrchestrationThreadDetailSnapshot {\n  return {\n    ...snapshot,\n    thread: {\n      ...snapshot.thread,\n      activities: dropSupersededToolUpdatedActivities(\n        dropStaleContextWindowActivities(snapshot.thread.activities),\n      ).map(projectActivityPayload),\n    },\n  };\n}\n\nexport function projectActivityEvent(event: OrchestrationEvent): OrchestrationEvent {\n  if (event.type !== \"thread.activity-appended\") {\n    return event;\n  }\n  return {\n    ...event,\n    payload: {\n      ...event.payload,\n      activity: projectActivityPayload(event.payload.activity),\n    },\n  };\n}\n","import * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport {\n  type ClientOrchestrationCommand,\n  type IsoDateTime,\n  type OrchestrationCommand,\n  OrchestrationDispatchCommandError,\n  PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,\n} from \"@t3tools/contracts\";\n\nimport { createAttachmentId, resolveAttachmentPath } from \"../attachmentStore.ts\";\nimport { ServerConfig } from \"../config.ts\";\nimport { parseBase64DataUrl } from \"../imageMime.ts\";\nimport * as WorkspacePaths from \"../workspace/WorkspacePaths.ts\";\n\nexport const canonicalizeClientCommandTimestamps = (\n  command: ClientOrchestrationCommand,\n  receivedAt: IsoDateTime,\n): ClientOrchestrationCommand => {\n  const canonicalCommand =\n    \"createdAt\" in command\n      ? {\n          ...command,\n          createdAt: receivedAt,\n        }\n      : command;\n\n  if (canonicalCommand.type !== \"thread.turn.start\" || !canonicalCommand.bootstrap?.createThread) {\n    return canonicalCommand;\n  }\n\n  return {\n    ...canonicalCommand,\n    bootstrap: {\n      ...canonicalCommand.bootstrap,\n      createThread: {\n        ...canonicalCommand.bootstrap.createThread,\n        createdAt: receivedAt,\n      },\n    },\n  };\n};\n\nexport const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>\n  Effect.gen(function* () {\n    const receivedAt = DateTime.formatIso(yield* DateTime.now);\n    const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const serverConfig = yield* ServerConfig;\n    const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n\n    const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>\n      workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(\n        Effect.mapError(\n          (cause) =>\n            new OrchestrationDispatchCommandError({\n              message: cause.message,\n            }),\n        ),\n      );\n\n    const normalizeProjectWorkspaceRootForCreate = (\n      workspaceRoot: string,\n      createIfMissing: boolean | undefined,\n    ) =>\n      workspacePaths\n        .normalizeWorkspaceRoot(workspaceRoot, {\n          createIfMissing: createIfMissing === true,\n        })\n        .pipe(\n          Effect.mapError(\n            (cause) =>\n              new OrchestrationDispatchCommandError({\n                message: cause.message,\n              }),\n          ),\n        );\n\n    if (canonicalCommand.type === \"project.create\") {\n      return {\n        ...canonicalCommand,\n        workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(\n          canonicalCommand.workspaceRoot,\n          canonicalCommand.createWorkspaceRootIfMissing,\n        ),\n        createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,\n      } satisfies OrchestrationCommand;\n    }\n\n    if (\n      canonicalCommand.type === \"project.meta.update\" &&\n      canonicalCommand.workspaceRoot !== undefined\n    ) {\n      return {\n        ...canonicalCommand,\n        workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot),\n      } satisfies OrchestrationCommand;\n    }\n\n    if (canonicalCommand.type !== \"thread.turn.start\") {\n      return canonicalCommand as OrchestrationCommand;\n    }\n\n    const normalizedAttachments = yield* Effect.forEach(\n      canonicalCommand.message.attachments,\n      (attachment) =>\n        Effect.gen(function* () {\n          const parsed = parseBase64DataUrl(attachment.dataUrl);\n          if (!parsed || !parsed.mimeType.startsWith(\"image/\")) {\n            return yield* new OrchestrationDispatchCommandError({\n              message: `Invalid image attachment payload for '${attachment.name}'.`,\n            });\n          }\n\n          const bytes = Buffer.from(parsed.base64, \"base64\");\n          if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {\n            return yield* new OrchestrationDispatchCommandError({\n              message: `Image attachment '${attachment.name}' is empty or too large.`,\n            });\n          }\n\n          const attachmentId = createAttachmentId(canonicalCommand.threadId);\n          if (!attachmentId) {\n            return yield* new OrchestrationDispatchCommandError({\n              message: \"Failed to create a safe attachment id.\",\n            });\n          }\n\n          const persistedAttachment = {\n            type: \"image\" as const,\n            id: attachmentId,\n            name: attachment.name,\n            mimeType: parsed.mimeType.toLowerCase(),\n            sizeBytes: bytes.byteLength,\n          };\n\n          const attachmentPath = resolveAttachmentPath({\n            attachmentsDir: serverConfig.attachmentsDir,\n            attachment: persistedAttachment,\n          });\n          if (!attachmentPath) {\n            return yield* new OrchestrationDispatchCommandError({\n              message: `Failed to resolve persisted path for '${attachment.name}'.`,\n            });\n          }\n\n          yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(\n            Effect.mapError(\n              () =>\n                new OrchestrationDispatchCommandError({\n                  message: `Failed to create attachment directory for '${attachment.name}'.`,\n                }),\n            ),\n          );\n          yield* fileSystem.writeFile(attachmentPath, bytes).pipe(\n            Effect.mapError(\n              () =>\n                new OrchestrationDispatchCommandError({\n                  message: `Failed to persist attachment '${attachment.name}'.`,\n                }),\n            ),\n          );\n\n          return persistedAttachment;\n        }),\n      { concurrency: 1 },\n    );\n\n    return {\n      ...canonicalCommand,\n      message: {\n        ...canonicalCommand.message,\n        attachments: normalizedAttachments,\n      },\n    } satisfies OrchestrationCommand;\n  });\n","import { WS_METHODS } from \"@t3tools/contracts\";\nimport * as Clock from \"effect/Clock\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Metric from \"effect/Metric\";\nimport * as References from \"effect/References\";\nimport * as Stream from \"effect/Stream\";\n\nimport { outcomeFromExit } from \"./Attributes.ts\";\nimport { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from \"./Metrics.ts\";\n\nconst RPC_SPAN_PREFIX = \"ws.rpc\";\nconst DEFAULT_RPC_SPAN_ATTRIBUTES = {\n  \"rpc.transport\": \"websocket\",\n  \"rpc.system\": \"effect-rpc\",\n} as const;\nconst RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([\n  WS_METHODS.serverGetTraceDiagnostics,\n  WS_METHODS.serverGetProcessDiagnostics,\n  WS_METHODS.serverGetProcessResourceHistory,\n  WS_METHODS.serverSignalProcess,\n]);\n\nfunction shouldTraceRpc(method: string): boolean {\n  return !RPC_METHODS_WITH_TRACING_DISABLED.has(method);\n}\n\nconst rpcSpanAttributes = (\n  method: string,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Record<string, unknown> => ({\n  ...DEFAULT_RPC_SPAN_ATTRIBUTES,\n  \"rpc.method\": method,\n  ...traceAttributes,\n});\n\nconst withRpcEffectTracing = <A, E, R>(\n  method: string,\n  effect: Effect.Effect<A, E, R>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Effect.Effect<A, E, R> =>\n  shouldTraceRpc(method)\n    ? effect.pipe(\n        Effect.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {\n          attributes: rpcSpanAttributes(method, traceAttributes),\n        }),\n      )\n    : effect.pipe(Effect.provideService(References.TracerEnabled, false));\n\nconst withRpcStreamTracing = <A, E, R>(\n  method: string,\n  stream: Stream.Stream<A, E, R>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Stream.Stream<A, E, R> =>\n  shouldTraceRpc(method)\n    ? stream.pipe(\n        Stream.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {\n          attributes: rpcSpanAttributes(method, traceAttributes),\n        }),\n      )\n    : stream.pipe(Stream.provideService(References.TracerEnabled, false));\n\nconst recordRpcStreamMetrics = <E>(\n  method: string,\n  startedAt: bigint,\n  exit: Exit.Exit<unknown, E>,\n): Effect.Effect<void, never, never> =>\n  Effect.gen(function* () {\n    const endedAt = yield* Clock.currentTimeNanos;\n    const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;\n\n    yield* Metric.update(\n      Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),\n      Duration.nanos(elapsedNanos),\n    );\n    yield* Metric.update(\n      Metric.withAttributes(\n        rpcRequestsTotal,\n        metricAttributes({\n          method,\n          outcome: outcomeFromExit(exit),\n        }),\n      ),\n      1,\n    );\n  });\n\nexport const observeRpcEffect = <A, E, R>(\n  method: string,\n  effect: Effect.Effect<A, E, R>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Effect.Effect<A, E, R> => {\n  const instrumented = effect.pipe(\n    withMetrics({\n      counter: rpcRequestsTotal,\n      timer: rpcRequestDuration,\n      attributes: {\n        method,\n      },\n    }),\n  );\n\n  return withRpcEffectTracing(method, instrumented, traceAttributes);\n};\n\nexport const observeRpcStream = <A, E, R>(\n  method: string,\n  stream: Stream.Stream<A, E, R>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Stream.Stream<A, E, R> => {\n  const instrumented = Stream.unwrap(\n    Effect.gen(function* () {\n      const startedAt = yield* Clock.currentTimeNanos;\n      return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));\n    }),\n  );\n\n  return withRpcStreamTracing(method, instrumented, traceAttributes);\n};\n\nexport const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(\n  method: string,\n  effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,\n  traceAttributes?: Readonly<Record<string, unknown>>,\n): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> => {\n  const instrumented = Stream.unwrap(\n    Effect.gen(function* () {\n      const startedAt = yield* Clock.currentTimeNanos;\n      const exit = yield* Effect.exit(effect);\n\n      if (Exit.isFailure(exit)) {\n        yield* recordRpcStreamMetrics(method, startedAt, exit);\n        return yield* Effect.failCause(exit.cause);\n      }\n\n      return exit.value.pipe(\n        Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)),\n      );\n    }),\n  );\n\n  return withRpcStreamTracing(method, instrumented, traceAttributes);\n};\n","/**\n * ProviderRegistry - Provider snapshot service.\n *\n * Owns provider install/auth/version/model snapshots and exposes the latest\n * provider state to transport layers.\n *\n * @module ProviderRegistry\n */\nimport type {\n  ProviderInstanceId,\n  ProviderDriverKind,\n  ServerProvider,\n  ServerProviderUpdateState,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\nimport type { ProviderMaintenanceCapabilities } from \"../providerMaintenance.ts\";\n\nexport type ProviderMaintenanceActionKind = \"update\";\n\nexport interface ProviderRegistryShape {\n  /**\n   * Read the latest provider snapshots for every configured instance.\n   * Multiple snapshots may share the same `provider` kind (multiple\n   * instances of the same driver) and disambiguate via `instanceId`.\n   */\n  readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;\n\n  /**\n   * Refresh all providers, or the default instance of the specified\n   * kind when supplied.\n   *\n   * Retained for back-compat with legacy call sites (WS refresh RPC,\n   * orchestration metrics). New code should prefer `refreshInstance`.\n   *\n   * @deprecated prefer `refreshInstance` for new call sites.\n   */\n  readonly refresh: (provider?: ProviderDriverKind) => Effect.Effect<ReadonlyArray<ServerProvider>>;\n\n  /**\n   * Refresh the specific configured instance. Returns the updated snapshot\n   * list. When the instance id is unknown the call resolves with the\n   * currently cached list (no error) — matching the legacy `refresh` shim\n   * behaviour so transport layers don't have to special-case unknowns.\n   */\n  readonly refreshInstance: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ReadonlyArray<ServerProvider>>;\n\n  /**\n   * Resolve the maintenance capabilities owned by one live provider instance.\n   * Falls back to manual-only capabilities when the instance is not live.\n   */\n  readonly getProviderMaintenanceCapabilitiesForInstance: (\n    instanceId: ProviderInstanceId,\n    provider: ProviderDriverKind,\n  ) => Effect.Effect<ProviderMaintenanceCapabilities>;\n\n  /**\n   * Apply volatile maintenance-action state to one configured instance.\n   * This state is never persisted to disk. Today only update actions are\n   * projected onto `ServerProvider.updateState`; install/auth actions can\n   * extend this action map without adding driver-scoped APIs.\n   */\n  readonly setProviderMaintenanceActionState: (input: {\n    readonly instanceId: ProviderInstanceId;\n    readonly action: ProviderMaintenanceActionKind;\n    readonly state: ServerProviderUpdateState | null;\n  }) => Effect.Effect<ReadonlyArray<ServerProvider>>;\n\n  /**\n   * Stream of provider snapshot updates — one emission per aggregated\n   * change. The array contains the full current state.\n   */\n  readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;\n}\n\nexport class ProviderRegistry extends Context.Service<ProviderRegistry, ProviderRegistryShape>()(\n  \"t3/provider/Services/ProviderRegistry\",\n) {}\n","import * as Effect from \"effect/Effect\";\nimport * as Ref from \"effect/Ref\";\nimport * as Semaphore from \"effect/Semaphore\";\n\nexport interface ProviderMaintenanceCommandCoordinatorShape<E> {\n  readonly withCommandLock: <A, R>(input: {\n    readonly targetKey: string;\n    readonly lockKey: string;\n    readonly onQueued?: Effect.Effect<void, E, R>;\n    readonly run: Effect.Effect<A, E, R>;\n  }) => Effect.Effect<A, E, R>;\n}\n\nexport const makeProviderMaintenanceCommandCoordinator = Effect.fn(\n  \"makeProviderMaintenanceCommandCoordinator\",\n)(function* <E>(input: { readonly makeAlreadyRunningError: (targetKey: string) => E }) {\n  const runningTargetsRef = yield* Ref.make<ReadonlySet<string>>(new Set());\n  const locksRef = yield* Ref.make<ReadonlyMap<string, Semaphore.Semaphore>>(new Map());\n\n  const acquireTarget = Effect.fn(\"acquireTarget\")(function* (targetKey: string) {\n    return yield* Ref.modify(runningTargetsRef, (runningTargets) => {\n      if (runningTargets.has(targetKey)) {\n        return [false, runningTargets] as const;\n      }\n      const next = new Set(runningTargets);\n      next.add(targetKey);\n      return [true, next] as const;\n    });\n  });\n\n  const releaseTarget = (targetKey: string) =>\n    Ref.update(runningTargetsRef, (runningTargets) => {\n      const next = new Set(runningTargets);\n      next.delete(targetKey);\n      return next;\n    });\n\n  const getLock = Effect.fn(\"getProviderMaintenanceCommandLock\")(function* (lockKey: string) {\n    const existing = (yield* Ref.get(locksRef)).get(lockKey);\n    if (existing) {\n      return existing;\n    }\n\n    const lock = yield* Semaphore.make(1);\n    return yield* Ref.modify(locksRef, (locks) => {\n      const current = locks.get(lockKey);\n      if (current) {\n        return [current, locks] as const;\n      }\n      const next = new Map(locks);\n      next.set(lockKey, lock);\n      return [lock, next] as const;\n    });\n  });\n\n  const withCommandLock: ProviderMaintenanceCommandCoordinatorShape<E>[\"withCommandLock\"] = ({\n    targetKey,\n    lockKey,\n    onQueued,\n    run,\n  }) =>\n    Effect.gen(function* () {\n      const acquired = yield* acquireTarget(targetKey);\n      if (!acquired) {\n        return yield* Effect.fail(input.makeAlreadyRunningError(targetKey));\n      }\n\n      return yield* Effect.gen(function* () {\n        const lock = yield* getLock(lockKey);\n        if (onQueued) {\n          yield* onQueued;\n        }\n        return yield* lock.withPermits(1)(run);\n      }).pipe(Effect.ensuring(releaseTarget(targetKey)));\n    });\n\n  return {\n    withCommandLock,\n  } satisfies ProviderMaintenanceCommandCoordinatorShape<E>;\n});\n","interface ParsedSemver {\n  readonly major: number;\n  readonly minor: number;\n  readonly patch: number;\n  readonly prerelease: ReadonlyArray<string>;\n}\n\nconst SEMVER_NUMBER_SEGMENT = /^\\d+$/;\n\nexport function normalizeSemverVersion(version: string): string {\n  const [main, prerelease] = version.trim().split(\"-\", 2);\n  const segments: string[] = [];\n  for (const segment of (main ?? \"\").split(\".\")) {\n    const trimmed = segment.trim();\n    if (trimmed.length > 0) {\n      segments.push(trimmed);\n    }\n  }\n\n  // Pad shorthand versions (\"20\" or \"20.1\") up to three segments so major-only\n  // and minor-only inputs parse and compare numerically. This matches\n  // satisfiesSemverRange, which already treats a missing minor/patch as 0. The\n  // length > 0 guard keeps empty/garbage input empty (parseSemver still\n  // rejects it), and inputs with more than three segments are left untouched.\n  while (segments.length > 0 && segments.length < 3) {\n    segments.push(\"0\");\n  }\n\n  return prerelease ? `${segments.join(\".\")}-${prerelease}` : segments.join(\".\");\n}\n\nexport function parseSemver(value: string): ParsedSemver | null {\n  const normalized = normalizeSemverVersion(value).replace(/^v/, \"\");\n  const [main = \"\", prerelease] = normalized.split(\"-\", 2);\n  const segments = main.split(\".\");\n  if (segments.length !== 3) {\n    return null;\n  }\n\n  const [majorSegment, minorSegment, patchSegment] = segments;\n  if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {\n    return null;\n  }\n  if (\n    !SEMVER_NUMBER_SEGMENT.test(majorSegment) ||\n    !SEMVER_NUMBER_SEGMENT.test(minorSegment) ||\n    !SEMVER_NUMBER_SEGMENT.test(patchSegment)\n  ) {\n    return null;\n  }\n\n  const major = Number.parseInt(majorSegment, 10);\n  const minor = Number.parseInt(minorSegment, 10);\n  const patch = Number.parseInt(patchSegment, 10);\n  if (![major, minor, patch].every(Number.isInteger)) {\n    return null;\n  }\n\n  return {\n    major,\n    minor,\n    patch,\n    prerelease: parsePrereleaseSegments(prerelease),\n  };\n}\n\nfunction parsePrereleaseSegments(prerelease: string | undefined): ReadonlyArray<string> {\n  if (prerelease === undefined) {\n    return [];\n  }\n  const segments: string[] = [];\n  for (const segment of prerelease.split(\".\")) {\n    const trimmed = segment.trim();\n    if (trimmed.length > 0) {\n      segments.push(trimmed);\n    }\n  }\n  return segments;\n}\n\nfunction comparePrereleaseIdentifier(left: string, right: string): number {\n  const leftNumeric = SEMVER_NUMBER_SEGMENT.test(left);\n  const rightNumeric = SEMVER_NUMBER_SEGMENT.test(right);\n\n  if (leftNumeric && rightNumeric) {\n    return Number.parseInt(left, 10) - Number.parseInt(right, 10);\n  }\n  if (leftNumeric) {\n    return -1;\n  }\n  if (rightNumeric) {\n    return 1;\n  }\n  return left.localeCompare(right);\n}\n\nexport function compareSemverVersions(left: string, right: string): number {\n  const parsedLeft = parseSemver(left);\n  const parsedRight = parseSemver(right);\n  if (!parsedLeft || !parsedRight) {\n    return left.localeCompare(right);\n  }\n\n  if (parsedLeft.major !== parsedRight.major) {\n    return parsedLeft.major - parsedRight.major;\n  }\n  if (parsedLeft.minor !== parsedRight.minor) {\n    return parsedLeft.minor - parsedRight.minor;\n  }\n  if (parsedLeft.patch !== parsedRight.patch) {\n    return parsedLeft.patch - parsedRight.patch;\n  }\n\n  if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {\n    return 0;\n  }\n  if (parsedLeft.prerelease.length === 0) {\n    return 1;\n  }\n  if (parsedRight.prerelease.length === 0) {\n    return -1;\n  }\n\n  const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);\n  for (let index = 0; index < length; index += 1) {\n    const leftIdentifier = parsedLeft.prerelease[index];\n    const rightIdentifier = parsedRight.prerelease[index];\n    if (leftIdentifier === undefined) {\n      return -1;\n    }\n    if (rightIdentifier === undefined) {\n      return 1;\n    }\n    const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);\n    if (comparison !== 0) {\n      return comparison;\n    }\n  }\n\n  return 0;\n}\n\n/**\n * Small semver range checker for CLI/runtime gates.\n *\n * Keep the function body valid plain JavaScript: SSH startup stringifies this\n * function and runs it on remote Node versions before TypeScript support is known.\n *\n * @param rawVersion Version string, with or without a leading `v`.\n * @param range Space-separated comparators, with `||` range groups.\n * @returns Whether `rawVersion` satisfies the supported range syntax.\n */\nexport const satisfiesSemverRange: (rawVersion: string, range: string) => boolean =\n  function satisfiesSemverRange(rawVersion, range) {\n    const normalizedVersion = String(rawVersion).trim().replace(/^v/, \"\");\n    const versionMatch = normalizedVersion.match(\n      /^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:-[0-9A-Za-z.-]+)?$/,\n    );\n    if (!versionMatch) {\n      return false;\n    }\n\n    const version = {\n      major: Number(versionMatch[1]),\n      minor: Number(versionMatch[2] || 0),\n      patch: Number(versionMatch[3] || 0),\n    };\n\n    return range.split(\"||\").some((group) => {\n      const comparators = group.trim().split(/\\s+/).filter(Boolean);\n      if (comparators.length === 0) {\n        return false;\n      }\n      return comparators.every((comparator) => {\n        const match = comparator.trim().match(/^(\\^|>=|>|<=|<|=)?\\s*v?(\\d+(?:\\.\\d+){0,2})$/);\n        if (!match) {\n          return false;\n        }\n        const targetVersion = match[2];\n        if (targetVersion === undefined) {\n          return false;\n        }\n        const targetMatch = targetVersion.match(/^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?$/);\n        if (!targetMatch) {\n          return false;\n        }\n        const target = {\n          major: Number(targetMatch[1]),\n          minor: Number(targetMatch[2] || 0),\n          patch: Number(targetMatch[3] || 0),\n        };\n        const compared =\n          version.major !== target.major\n            ? version.major > target.major\n              ? 1\n              : -1\n            : version.minor !== target.minor\n              ? version.minor > target.minor\n                ? 1\n                : -1\n              : version.patch !== target.patch\n                ? version.patch > target.patch\n                  ? 1\n                  : -1\n                : 0;\n        const operator = match[1] || \"=\";\n        switch (operator) {\n          case \"^\":\n            if (compared < 0) {\n              return false;\n            }\n            if (target.major > 0) {\n              return version.major === target.major;\n            }\n            if (target.minor > 0) {\n              return version.major === 0 && version.minor === target.minor;\n            }\n            return version.major === 0 && version.minor === 0 && version.patch === target.patch;\n          case \">=\":\n            return compared >= 0;\n          case \">\":\n            return compared > 0;\n          case \"<=\":\n            return compared <= 0;\n          case \"<\":\n            return compared < 0;\n          case \"=\":\n            return compared === 0;\n          default:\n            return false;\n        }\n      });\n    });\n  };\n","import {\n  ProviderDriverKind,\n  type ServerProvider,\n  type ServerProviderVersionAdvisory,\n} from \"@t3tools/contracts\";\nimport { compareSemverVersions } from \"@t3tools/shared/semver\";\nimport { resolveCommandPath } from \"@t3tools/shared/shell\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\nconst LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;\nconst LATEST_VERSION_TIMEOUT_MS = 4_000;\nconst PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = \"Install the update now or review provider settings.\";\n\nconst compactEnv = (input: Record<string, Option.Option<string>>): NodeJS.ProcessEnv =>\n  Object.fromEntries(\n    Object.entries(input).flatMap(([key, value]) =>\n      Option.match(value, {\n        onNone: () => [],\n        onSome: (resolved) => [[key, resolved]],\n      }),\n    ),\n  );\n\nconst CommandLookupEnvConfig = Config.all({\n  PATH: Config.string(\"PATH\").pipe(Config.option),\n  Path: Config.string(\"Path\").pipe(Config.option),\n  path: Config.string(\"path\").pipe(Config.option),\n  PATHEXT: Config.string(\"PATHEXT\").pipe(Config.option),\n}).pipe(Config.map(compactEnv));\n\nconst readCommandLookupEnv = CommandLookupEnvConfig.pipe(Effect.orElseSucceed(() => ({})));\n\nexport interface ProviderMaintenanceCapabilities {\n  readonly provider: ProviderDriverKind;\n  readonly packageName: string | null;\n  readonly update: ProviderMaintenanceCommandAction | null;\n}\n\nexport interface ProviderMaintenanceCommandAction {\n  readonly command: string;\n  readonly executable: string;\n  readonly args: ReadonlyArray<string>;\n  readonly lockKey: string;\n}\n\nexport interface ProviderMaintenanceCapabilityResolutionOptions {\n  readonly binaryPath?: string | null;\n  readonly env?: NodeJS.ProcessEnv;\n  readonly resolvedCommandPath?: string | null;\n  readonly realCommandPath?: string | null;\n}\n\nexport interface ProviderMaintenanceCapabilitiesResolver {\n  readonly resolve: (\n    options?: ProviderMaintenanceCapabilityResolutionOptions,\n  ) => ProviderMaintenanceCapabilities;\n}\n\nexport interface PackageManagedProviderMaintenanceDefinition {\n  readonly provider: ProviderDriverKind;\n  readonly npmPackageName: string;\n  readonly homebrewFormula: string | null;\n  readonly nativeUpdate: {\n    readonly executable: string;\n    readonly args: ReadonlyArray<string>;\n    readonly lockKey: string;\n    readonly isCommandPath: (commandPath: string) => boolean;\n  } | null;\n}\n\nexport interface ProviderVersionCacheEntry {\n  readonly expiresAt: number;\n  readonly version: string | null;\n}\n\nexport const ProviderVersionCache = Context.Reference<Map<string, ProviderVersionCacheEntry>>(\n  \"@t3tools/server/providerMaintenance/ProviderVersionCache\",\n  {\n    defaultValue: () => new Map(),\n  },\n);\nconst NpmLatestVersionResponse = Schema.Struct({\n  version: Schema.optional(Schema.String),\n});\n\nfunction nonEmptyString(value: unknown): string | null {\n  return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : null;\n}\n\nexport function makeProviderMaintenanceCapabilities(input: {\n  readonly provider: ProviderDriverKind;\n  readonly packageName: string | null;\n  readonly updateExecutable: string | null;\n  readonly updateArgs: ReadonlyArray<string>;\n  readonly updateLockKey: string | null;\n}): ProviderMaintenanceCapabilities {\n  const update =\n    input.updateExecutable === null || input.updateLockKey === null\n      ? null\n      : {\n          command: [input.updateExecutable, ...input.updateArgs].join(\" \"),\n          executable: input.updateExecutable,\n          args: input.updateArgs,\n          lockKey: input.updateLockKey,\n        };\n  return {\n    provider: input.provider,\n    packageName: input.packageName,\n    update,\n  };\n}\n\nexport function makeManualOnlyProviderMaintenanceCapabilities(input: {\n  readonly provider: ProviderDriverKind;\n  readonly packageName: string | null;\n}): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: input.provider,\n    packageName: input.packageName,\n    updateExecutable: null,\n    updateArgs: [],\n    updateLockKey: null,\n  });\n}\n\nfunction makeNpmGlobalProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"npm\",\n    // npm 12 blocks install scripts by default (empty allow-scripts allowlist)\n    // and still exits 0, so a package whose postinstall finishes the install\n    // (claude copies its native binary over a placeholder stub) is left broken\n    // while the update reports success. Allow this one package's scripts.\n    // Older npm warns about the unknown config and continues.\n    updateArgs: [\n      \"install\",\n      \"-g\",\n      `--allow-scripts=${definition.npmPackageName}`,\n      `${definition.npmPackageName}@latest`,\n    ],\n    updateLockKey: \"npm-global\",\n  });\n}\n\nfunction makeBunGlobalProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"bun\",\n    updateArgs: [\"i\", \"-g\", `${definition.npmPackageName}@latest`],\n    updateLockKey: \"bun-global\",\n  });\n}\n\nfunction makePnpmGlobalProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"pnpm\",\n    updateArgs: [\"add\", \"-g\", `${definition.npmPackageName}@latest`],\n    updateLockKey: \"pnpm-global\",\n  });\n}\n\nfunction makeVitePlusGlobalProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"vp\",\n    updateArgs: [\"i\", \"-g\", definition.npmPackageName],\n    updateLockKey: \"vite-plus-global\",\n  });\n}\n\nfunction makeHomebrewProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities {\n  if (!definition.homebrewFormula) {\n    return makeManualOnlyProviderMaintenanceCapabilities({\n      provider: definition.provider,\n      packageName: definition.npmPackageName,\n    });\n  }\n\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: \"brew\",\n    updateArgs: [\"upgrade\", definition.homebrewFormula],\n    updateLockKey: \"homebrew\",\n  });\n}\n\nfunction makeNativeProviderMaintenanceCapabilities(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilities | null {\n  if (!definition.nativeUpdate) {\n    return null;\n  }\n\n  return makeProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n    updateExecutable: definition.nativeUpdate.executable,\n    updateArgs: definition.nativeUpdate.args,\n    updateLockKey: definition.nativeUpdate.lockKey,\n  });\n}\n\nexport function hasPathSeparator(value: string): boolean {\n  return value.includes(\"/\") || value.includes(\"\\\\\");\n}\n\nexport function normalizeCommandPath(commandPath: string): string {\n  return commandPath.replaceAll(\"\\\\\", \"/\").toLowerCase();\n}\n\nfunction isBunGlobalCommandPath(commandPath: string): boolean {\n  return normalizeCommandPath(commandPath).includes(\"/.bun/bin/\");\n}\n\nfunction isVitePlusGlobalCommandPath(commandPath: string): boolean {\n  return normalizeCommandPath(commandPath).includes(\"/.vite-plus/bin/\");\n}\n\nfunction isPnpmGlobalCommandPath(commandPath: string): boolean {\n  const normalized = normalizeCommandPath(commandPath);\n  return (\n    normalized.includes(\"/.local/share/pnpm/\") ||\n    normalized.includes(\"/library/pnpm/\") ||\n    normalized.includes(\"/local/share/pnpm/\") ||\n    normalized.includes(\"/appdata/local/pnpm/\") ||\n    normalized.includes(\"/pnpm/global/\")\n  );\n}\n\nfunction isNpmGlobalCommandPath(commandPath: string): boolean {\n  const normalized = normalizeCommandPath(commandPath);\n  return (\n    normalized.includes(\"/node_modules/.bin/\") ||\n    normalized.includes(\"/lib/node_modules/\") ||\n    normalized.includes(\"/npm/node_modules/\")\n  );\n}\n\nfunction isHomebrewCommandPath(commandPath: string): boolean {\n  const normalized = normalizeCommandPath(commandPath);\n  return (\n    normalized.includes(\"/opt/homebrew/cellar/\") ||\n    normalized.includes(\"/usr/local/cellar/\") ||\n    normalized.includes(\"/homebrew/cellar/\") ||\n    normalized.includes(\"/opt/homebrew/caskroom/\") ||\n    normalized.includes(\"/usr/local/caskroom/\") ||\n    normalized.includes(\"/homebrew/caskroom/\") ||\n    normalized.startsWith(\"/opt/homebrew/bin/\") ||\n    normalized.startsWith(\"/usr/local/bin/\")\n  );\n}\n\nexport function resolvePackageManagedProviderMaintenance(\n  definition: PackageManagedProviderMaintenanceDefinition,\n  options?: ProviderMaintenanceCapabilityResolutionOptions,\n): ProviderMaintenanceCapabilities {\n  const binaryPath = nonEmptyString(options?.binaryPath);\n  if (!binaryPath) {\n    return makeNpmGlobalProviderMaintenanceCapabilities(definition);\n  }\n\n  const resolvedCommandPath =\n    options?.resolvedCommandPath ?? (hasPathSeparator(binaryPath) ? binaryPath : null);\n\n  if (resolvedCommandPath) {\n    const commandPaths = [\n      resolvedCommandPath,\n      ...(options?.realCommandPath ? [options.realCommandPath] : []),\n    ];\n\n    const nativeUpdate = definition.nativeUpdate;\n    if (\n      nativeUpdate &&\n      commandPaths.some((commandPath) => nativeUpdate.isCommandPath(commandPath))\n    ) {\n      return (\n        makeNativeProviderMaintenanceCapabilities(definition) ??\n        makeNpmGlobalProviderMaintenanceCapabilities(definition)\n      );\n    }\n    if (commandPaths.some(isVitePlusGlobalCommandPath)) {\n      return makeVitePlusGlobalProviderMaintenanceCapabilities(definition);\n    }\n    if (commandPaths.some(isBunGlobalCommandPath)) {\n      return makeBunGlobalProviderMaintenanceCapabilities(definition);\n    }\n    if (commandPaths.some(isPnpmGlobalCommandPath)) {\n      return makePnpmGlobalProviderMaintenanceCapabilities(definition);\n    }\n    if (commandPaths.some(isNpmGlobalCommandPath)) {\n      return makeNpmGlobalProviderMaintenanceCapabilities(definition);\n    }\n    if (commandPaths.some(isHomebrewCommandPath)) {\n      return makeHomebrewProviderMaintenanceCapabilities(definition);\n    }\n  }\n\n  if (!hasPathSeparator(binaryPath)) {\n    return makeNpmGlobalProviderMaintenanceCapabilities(definition);\n  }\n\n  return makeManualOnlyProviderMaintenanceCapabilities({\n    provider: definition.provider,\n    packageName: definition.npmPackageName,\n  });\n}\n\nexport function makePackageManagedProviderMaintenanceResolver(\n  definition: PackageManagedProviderMaintenanceDefinition,\n): ProviderMaintenanceCapabilitiesResolver {\n  return {\n    resolve: (options) => resolvePackageManagedProviderMaintenance(definition, options),\n  };\n}\n\nexport function makeStaticProviderMaintenanceResolver(\n  capabilities: ProviderMaintenanceCapabilities,\n): ProviderMaintenanceCapabilitiesResolver {\n  return {\n    resolve: () => capabilities,\n  };\n}\n\nfunction makeManualProviderMaintenanceCapabilities(\n  provider: ProviderDriverKind,\n): ProviderMaintenanceCapabilities {\n  return makeManualOnlyProviderMaintenanceCapabilities({\n    provider,\n    packageName: null,\n  });\n}\n\nexport const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(\n  \"resolveProviderMaintenanceCapabilitiesEffect\",\n)(function* (\n  resolver: ProviderMaintenanceCapabilitiesResolver,\n  options?: Omit<ProviderMaintenanceCapabilityResolutionOptions, \"realCommandPath\">,\n) {\n  const binaryPath = nonEmptyString(options?.binaryPath);\n  if (!binaryPath) {\n    return resolver.resolve(options);\n  }\n\n  const env = options?.env ?? (yield* readCommandLookupEnv);\n  const resolvedCommandPath =\n    (yield* resolveCommandPath(binaryPath, { env }).pipe(\n      Effect.catchTag(\"CommandResolutionError\", () => Effect.succeed(null)),\n    )) ?? (hasPathSeparator(binaryPath) ? binaryPath : null);\n  if (!resolvedCommandPath) {\n    return resolver.resolve(options);\n  }\n\n  const fileSystem = yield* FileSystem.FileSystem;\n  const realCommandPath = yield* fileSystem\n    .realPath(resolvedCommandPath)\n    .pipe(Effect.orElseSucceed(() => resolvedCommandPath));\n  return resolver.resolve({\n    ...options,\n    env,\n    resolvedCommandPath,\n    realCommandPath,\n  });\n});\n\nfunction deriveVersionAdvisory(input: {\n  readonly currentVersion: string | null;\n  readonly latestVersion: string | null;\n}): Pick<ServerProviderVersionAdvisory, \"status\" | \"message\"> {\n  if (!input.currentVersion) {\n    return { status: \"unknown\", message: null };\n  }\n  if (!input.latestVersion) {\n    return { status: \"unknown\", message: null };\n  }\n  if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {\n    return {\n      status: \"behind_latest\",\n      message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,\n    };\n  }\n  return { status: \"current\", message: null };\n}\n\nexport function createProviderVersionAdvisory(input: {\n  readonly driver: ProviderDriverKind;\n  readonly currentVersion: string | null;\n  readonly latestVersion?: string | null;\n  readonly checkedAt?: string | null;\n  readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;\n}): ServerProviderVersionAdvisory {\n  const capabilities =\n    input.maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(input.driver);\n  const latestVersion = input.latestVersion ?? null;\n  const advisory = deriveVersionAdvisory({\n    currentVersion: input.currentVersion,\n    latestVersion,\n  });\n\n  return {\n    status: advisory.status,\n    currentVersion: input.currentVersion,\n    latestVersion,\n    updateCommand: capabilities.update?.command ?? null,\n    canUpdate: capabilities.update !== null,\n    checkedAt: input.checkedAt ?? null,\n    message: advisory.message,\n  };\n}\n\nconst fetchNpmLatestVersion = Effect.fn(\"fetchNpmLatestVersion\")(function* (packageName: string) {\n  const client = yield* HttpClient.HttpClient;\n  const request = HttpClientRequest.get(\n    `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`,\n  ).pipe(HttpClientRequest.setHeader(\"accept\", \"application/json\"));\n  const response = yield* client.execute(request).pipe(\n    Effect.timeoutOption(LATEST_VERSION_TIMEOUT_MS),\n    Effect.orElseSucceed(() => Option.none()),\n  );\n  if (Option.isNone(response)) {\n    return null;\n  }\n  const httpResponse = response.value;\n  if (httpResponse.status < 200 || httpResponse.status >= 300) {\n    return null;\n  }\n  const payload = yield* httpResponse.json.pipe(\n    Effect.flatMap(Schema.decodeUnknownEffect(NpmLatestVersionResponse)),\n    Effect.orElseSucceed(() => null),\n  );\n  return payload ? nonEmptyString(payload.version) : null;\n});\n\nexport const resolveLatestProviderVersion = Effect.fn(\"resolveLatestProviderVersion\")(function* (\n  maintenanceCapabilities: ProviderMaintenanceCapabilities,\n) {\n  const packageName = maintenanceCapabilities.packageName;\n  if (!packageName) {\n    return null;\n  }\n\n  const latestVersionCache = yield* ProviderVersionCache;\n  const cached = latestVersionCache.get(packageName);\n  const now = DateTime.toEpochMillis(yield* DateTime.now);\n  if (cached && cached.expiresAt > now) {\n    return cached.version;\n  }\n\n  const version = yield* fetchNpmLatestVersion(packageName);\n  latestVersionCache.set(packageName, {\n    expiresAt: now + LATEST_VERSION_CACHE_TTL_MS,\n    version,\n  });\n  return version;\n});\n\nexport const enrichProviderSnapshotWithVersionAdvisory = Effect.fn(\n  \"enrichProviderSnapshotWithVersionAdvisory\",\n)(function* (\n  snapshot: ServerProvider,\n  maintenanceCapabilities?: ProviderMaintenanceCapabilities,\n  options?: {\n    readonly enableProviderUpdateChecks: boolean | undefined;\n  },\n) {\n  const capabilities =\n    maintenanceCapabilities ?? makeManualProviderMaintenanceCapabilities(snapshot.driver);\n  const shouldResolveLatestVersion =\n    options?.enableProviderUpdateChecks !== false &&\n    snapshot.enabled &&\n    snapshot.installed &&\n    Boolean(snapshot.version);\n  if (!shouldResolveLatestVersion) {\n    return {\n      ...snapshot,\n      versionAdvisory: createProviderVersionAdvisory({\n        driver: snapshot.driver,\n        currentVersion: snapshot.version,\n        checkedAt: snapshot.checkedAt,\n        maintenanceCapabilities: capabilities,\n      }),\n    };\n  }\n\n  const latestVersion = yield* resolveLatestProviderVersion(capabilities);\n  return {\n    ...snapshot,\n    versionAdvisory: createProviderVersionAdvisory({\n      driver: snapshot.driver,\n      currentVersion: snapshot.version,\n      latestVersion,\n      checkedAt: DateTime.formatIso(yield* DateTime.now),\n      maintenanceCapabilities: capabilities,\n    }),\n  };\n});\n","import {\n  defaultInstanceIdForDriver,\n  ProviderDriverKind,\n  ServerProviderUpdateError,\n  type ProviderInstanceId,\n  type ServerProvider,\n  type ServerProviderUpdatedPayload,\n  type ServerProviderUpdateState,\n} from \"@t3tools/contracts\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Data from \"effect/Data\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { ProviderRegistry } from \"./Services/ProviderRegistry.ts\";\nimport { makeProviderMaintenanceCommandCoordinator } from \"./providerMaintenanceCommandCoordinator.ts\";\nimport { enrichProviderSnapshotWithVersionAdvisory } from \"./providerMaintenance.ts\";\nimport type { ProviderMaintenanceCapabilities } from \"./providerMaintenance.ts\";\nimport { collectUint8StreamText } from \"../stream/collectUint8StreamText.ts\";\nconst isServerProviderUpdateError = Schema.is(ServerProviderUpdateError);\n\nconst UPDATE_TIMEOUT_MS = 5 * 60_000;\nconst UPDATE_OUTPUT_MAX_BYTES = 10_000;\n\nexport interface ProviderMaintenanceCommandResult {\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly exitCode: number | null;\n  readonly timedOut: boolean;\n  readonly stdoutTruncated: boolean;\n  readonly stderrTruncated: boolean;\n}\n\nexport interface ProviderMaintenanceRunnerShape {\n  readonly updateProvider: (\n    target:\n      | ProviderDriverKind\n      | {\n          readonly provider: ProviderDriverKind;\n          readonly instanceId?: ProviderInstanceId | undefined;\n        },\n  ) => Effect.Effect<ServerProviderUpdatedPayload, ServerProviderUpdateError>;\n}\n\nexport class ProviderMaintenanceRunner extends Context.Service<\n  ProviderMaintenanceRunner,\n  ProviderMaintenanceRunnerShape\n>()(\"t3/provider/providerMaintenanceRunner\") {}\n\nclass ProviderMaintenanceCommandError extends Data.TaggedError(\"ProviderMaintenanceCommandError\")<{\n  readonly message: string;\n  readonly cause?: unknown;\n}> {}\n\ninterface VerifiedProviderRefresh {\n  readonly providers: ReadonlyArray<ServerProvider>;\n  readonly verifiedProviders: ReadonlyArray<ServerProvider>;\n}\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\nconst runProviderMaintenanceCommandWithSpawner = Effect.fn(\"ProviderMaintenanceRunner.runCommand\")(\n  function* (input: {\n    readonly spawner: ChildProcessSpawner.ChildProcessSpawner[\"Service\"];\n    readonly command: string;\n    readonly args: ReadonlyArray<string>;\n  }) {\n    const collectCommandResult = Effect.fn(\"ProviderMaintenanceRunner.collectCommandResult\")(\n      function* () {\n        // Resolve the executable for the host platform before spawning. On\n        // Windows the update tools are batch shims (e.g. `npm` -> `npm.cmd`),\n        // which a bare ChildProcess.spawn cannot launch (spawn npm ENOENT);\n        // resolveSpawnCommand finds the real `.cmd` and routes it through the\n        // shell. On Linux/macOS (incl. the WSL backend) this is a no-op.\n        const resolved = yield* resolveSpawnCommand(input.command, input.args);\n        const child = yield* input.spawner\n          .spawn(ChildProcess.make(resolved.command, resolved.args, { shell: resolved.shell }))\n          .pipe(\n            Effect.mapError(\n              (cause) =>\n                new ProviderMaintenanceCommandError({\n                  message: `Failed to run update command ${input.command}: ${cause.message}`,\n                  cause,\n                }),\n            ),\n          );\n        yield* Effect.addFinalizer(() => child.kill().pipe(Effect.ignore));\n\n        const [stdout, stderr, exitCode] = yield* Effect.all(\n          [\n            collectUint8StreamText({\n              stream: child.stdout,\n              maxBytes: UPDATE_OUTPUT_MAX_BYTES,\n            }),\n            collectUint8StreamText({\n              stream: child.stderr,\n              maxBytes: UPDATE_OUTPUT_MAX_BYTES,\n            }),\n            child.exitCode,\n          ],\n          { concurrency: \"unbounded\" },\n        ).pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProviderMaintenanceCommandError({\n                message: cause instanceof Error ? cause.message : \"Update command failed to run.\",\n                cause,\n              }),\n          ),\n        );\n\n        return {\n          stdout: stdout.text,\n          stderr: stderr.text,\n          exitCode: Number(exitCode),\n          timedOut: false,\n          stdoutTruncated: stdout.truncated,\n          stderrTruncated: stderr.truncated,\n        } satisfies ProviderMaintenanceCommandResult;\n      },\n    );\n\n    return yield* collectCommandResult().pipe(\n      Effect.scoped,\n      Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)),\n      Effect.map((result) =>\n        Option.match(result, {\n          onSome: (value) => value,\n          onNone: () =>\n            ({\n              stdout: \"\",\n              stderr: \"\",\n              exitCode: null,\n              timedOut: true,\n              stdoutTruncated: false,\n              stderrTruncated: false,\n            }) satisfies ProviderMaintenanceCommandResult,\n        }),\n      ),\n    );\n  },\n);\n\nfunction trimNullable(value: string): string | null {\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction truncateText(value: string, maxLength: number): string {\n  return value.length <= maxLength ? value : value.slice(0, maxLength);\n}\n\nfunction commandOutput(result: ProviderMaintenanceCommandResult): string | null {\n  const output = trimNullable([result.stderr, result.stdout].filter(Boolean).join(\"\\n\\n\"));\n  if (!output) {\n    return null;\n  }\n  return truncateText(output, UPDATE_OUTPUT_MAX_BYTES);\n}\n\nfunction failureMessage(result: ProviderMaintenanceCommandResult): string {\n  if (result.timedOut) {\n    return \"Update timed out.\";\n  }\n  if (result.exitCode !== null && result.exitCode !== 0) {\n    return `Update command exited with code ${result.exitCode}.`;\n  }\n  return \"Update command failed.\";\n}\n\nfunction isOutdatedProvider(provider: ServerProvider | undefined): boolean {\n  return provider?.versionAdvisory?.status === \"behind_latest\";\n}\n\nfunction makeUpdateState(input: {\n  readonly status: ServerProviderUpdateState[\"status\"];\n  readonly startedAt: string | null;\n  readonly finishedAt: string | null;\n  readonly message: string | null;\n  readonly output?: string | null;\n}): ServerProviderUpdateState {\n  return {\n    status: input.status,\n    startedAt: input.startedAt,\n    finishedAt: input.finishedAt,\n    message: input.message,\n    output: input.output ?? null,\n  };\n}\n\nexport const make = Effect.fn(\"ProviderMaintenanceRunner.make\")(function* () {\n  const providerRegistry = yield* ProviderRegistry;\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const httpClient = yield* HttpClient.HttpClient;\n  const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>\n    runProviderMaintenanceCommandWithSpawner({\n      spawner,\n      command,\n      args,\n    });\n  const commandCoordinator = yield* makeProviderMaintenanceCommandCoordinator({\n    makeAlreadyRunningError: () =>\n      new ServerProviderUpdateError({\n        provider: ProviderDriverKind.make(\"unknown\"),\n        reason: \"An update is already running for this provider.\",\n      }),\n  });\n\n  const verifyRefreshedProvider = (\n    provider: ProviderDriverKind,\n    maintenanceCapabilities: ProviderMaintenanceCapabilities,\n    instanceId: ProviderInstanceId,\n  ): Effect.Effect<VerifiedProviderRefresh> =>\n    providerRegistry.getProviders.pipe(\n      Effect.map((providers) => {\n        const instanceIds: Array<ProviderInstanceId> = [];\n        for (const candidate of providers) {\n          if (candidate.driver === provider && candidate.instanceId === instanceId) {\n            instanceIds.push(candidate.instanceId);\n          }\n        }\n        return instanceIds;\n      }),\n      Effect.flatMap((instanceIds) =>\n        instanceIds.length === 0\n          ? providerRegistry.refreshInstance(instanceId)\n          : Effect.forEach(\n              instanceIds,\n              (instanceId) => providerRegistry.refreshInstance(instanceId),\n              {\n                concurrency: \"unbounded\",\n                discard: true,\n              },\n            ).pipe(Effect.andThen(providerRegistry.getProviders)),\n      ),\n      Effect.flatMap((providers) => {\n        const refreshedProviders = providers.filter(\n          (candidate) => candidate.driver === provider && candidate.instanceId === instanceId,\n        );\n        if (refreshedProviders.length === 0) {\n          return Effect.succeed<VerifiedProviderRefresh>({\n            providers,\n            verifiedProviders: [],\n          });\n        }\n        return Effect.forEach(\n          refreshedProviders,\n          (refreshedProvider) =>\n            enrichProviderSnapshotWithVersionAdvisory(\n              refreshedProvider,\n              maintenanceCapabilities,\n            ).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)),\n          {\n            concurrency: \"unbounded\",\n          },\n        ).pipe(\n          Effect.map(\n            (verifiedProviders): VerifiedProviderRefresh => ({\n              providers,\n              verifiedProviders,\n            }),\n          ),\n          Effect.catchCause((cause) =>\n            Effect.logWarning(\"Provider post-update version verification failed\", {\n              provider,\n              cause: Cause.pretty(cause),\n            }).pipe(\n              Effect.as<VerifiedProviderRefresh>({\n                providers,\n                verifiedProviders: refreshedProviders,\n              }),\n            ),\n          ),\n        );\n      }),\n    );\n\n  const updateProvider: ProviderMaintenanceRunnerShape[\"updateProvider\"] = Effect.fn(\n    \"ProviderMaintenanceRunner.updateProvider\",\n  )(function* (target) {\n    const provider = typeof target === \"string\" ? target : target.provider;\n    const instanceId =\n      typeof target === \"string\"\n        ? defaultInstanceIdForDriver(provider)\n        : (target.instanceId ?? defaultInstanceIdForDriver(provider));\n    const targetKey = `instance:${instanceId}`;\n    const capabilities = yield* providerRegistry.getProviderMaintenanceCapabilitiesForInstance(\n      instanceId,\n      provider,\n    );\n    const update = capabilities.update;\n    if (!update) {\n      return yield* new ServerProviderUpdateError({\n        provider,\n        reason: \"This provider does not support one-click updates.\",\n      });\n    }\n\n    const setUpdateState = (state: ServerProviderUpdateState | null) =>\n      providerRegistry.setProviderMaintenanceActionState({\n        instanceId,\n        action: \"update\",\n        state,\n      });\n    const setQueuedState = setUpdateState(\n      makeUpdateState({\n        status: \"queued\",\n        startedAt: null,\n        finishedAt: null,\n        message: \"Waiting for another provider update to finish.\",\n      }),\n    ).pipe(Effect.asVoid);\n\n    const runProviderUpdate = Effect.fn(\"ProviderMaintenanceRunner.runProviderUpdate\")(\n      function* () {\n        const finish = (state: ServerProviderUpdateState) =>\n          setUpdateState(state).pipe(Effect.map((providers) => ({ providers })));\n        const startedAtRef = yield* Ref.make<string | null>(null);\n\n        const runCommandAndVerify = Effect.fn(\"ProviderMaintenanceRunner.runCommandAndVerify\")(\n          function* () {\n            const startedAt = yield* nowIso;\n            yield* Ref.set(startedAtRef, startedAt);\n            yield* setUpdateState(\n              makeUpdateState({\n                status: \"running\",\n                startedAt,\n                finishedAt: null,\n                message: \"Updating provider.\",\n              }),\n            );\n\n            const result = yield* runMaintenanceCommand(update.executable, update.args);\n            const finishedAt = yield* nowIso;\n            if (result.timedOut || result.exitCode !== 0) {\n              return yield* finish(\n                makeUpdateState({\n                  status: \"failed\",\n                  startedAt,\n                  finishedAt,\n                  message: failureMessage(result),\n                  output: commandOutput(result),\n                }),\n              );\n            }\n\n            const { verifiedProviders } = yield* verifyRefreshedProvider(\n              provider,\n              capabilities,\n              instanceId,\n            );\n            const couldNotVerify = verifiedProviders.length === 0;\n            const stillOutdated =\n              couldNotVerify ||\n              verifiedProviders.some((verifiedProvider) => isOutdatedProvider(verifiedProvider));\n            return yield* finish(\n              makeUpdateState({\n                status: stillOutdated ? \"unchanged\" : \"succeeded\",\n                startedAt,\n                finishedAt,\n                message: couldNotVerify\n                  ? \"Update command completed, but Synaptic Code could not verify the provider version.\"\n                  : stillOutdated\n                    ? \"Update command completed, but Synaptic Code still detects an outdated provider version.\"\n                    : \"Provider updated.\",\n                output: commandOutput(result),\n              }),\n            );\n          },\n        );\n\n        const recordFailedUpdate = Effect.fn(\"ProviderMaintenanceRunner.recordFailedUpdate\")(\n          function* (cause: Cause.Cause<unknown>) {\n            const failure = Cause.squash(cause);\n            const startedAt = yield* Ref.get(startedAtRef);\n            return yield* finish(\n              makeUpdateState({\n                status: \"failed\",\n                startedAt,\n                finishedAt: yield* nowIso,\n                message: failure instanceof Error ? failure.message : \"Update command failed.\",\n                output: null,\n              }),\n            );\n          },\n        );\n\n        return yield* runCommandAndVerify().pipe(Effect.catchCause(recordFailedUpdate));\n      },\n    );\n\n    return yield* commandCoordinator\n      .withCommandLock({\n        targetKey,\n        lockKey: update.lockKey,\n        onQueued: setQueuedState,\n        run: runProviderUpdate(),\n      })\n      .pipe(\n        Effect.mapError((error) =>\n          isServerProviderUpdateError(error)\n            ? new ServerProviderUpdateError({\n                provider,\n                reason: error.reason,\n              })\n            : error,\n        ),\n      );\n  });\n\n  return ProviderMaintenanceRunner.of({\n    updateProvider,\n  });\n});\n\nexport const layer = Layer.effect(ProviderMaintenanceRunner, make());\n","/**\n * KeyedCoalescingWorker - A keyed worker that keeps only the latest value per key.\n *\n * Enqueues for an active or already-queued key are merged atomically instead of\n * creating duplicate queued items. `drainKey()` resolves only when that key has\n * no queued, pending, or active work left.\n *\n * @module KeyedCoalescingWorker\n */\nimport * as Scope from \"effect/Scope\";\nimport * as Effect from \"effect/Effect\";\nimport * as TxQueue from \"effect/TxQueue\";\nimport * as TxRef from \"effect/TxRef\";\n\nexport interface KeyedCoalescingWorker<K, V> {\n  readonly enqueue: (key: K, value: V) => Effect.Effect<void>;\n  readonly drainKey: (key: K) => Effect.Effect<void>;\n}\n\ninterface KeyedCoalescingWorkerState<K, V> {\n  readonly latestByKey: Map<K, V>;\n  readonly queuedKeys: Set<K>;\n  readonly activeKeys: Set<K>;\n}\n\nexport const makeKeyedCoalescingWorker = <K, V, E, R>(options: {\n  readonly merge: (current: V, next: V) => V;\n  readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;\n}): Effect.Effect<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> =>\n  Effect.gen(function* () {\n    const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);\n    const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({\n      latestByKey: new Map(),\n      queuedKeys: new Set(),\n      activeKeys: new Set(),\n    });\n\n    const processKey = (key: K, value: V): Effect.Effect<void, E, R> =>\n      options.process(key, value).pipe(\n        Effect.flatMap(() =>\n          TxRef.modify(stateRef, (state) => {\n            const nextValue = state.latestByKey.get(key);\n            if (nextValue === undefined) {\n              const activeKeys = new Set(state.activeKeys);\n              activeKeys.delete(key);\n              return [null, { ...state, activeKeys }] as const;\n            }\n\n            const latestByKey = new Map(state.latestByKey);\n            latestByKey.delete(key);\n            return [nextValue, { ...state, latestByKey }] as const;\n          }).pipe(Effect.tx),\n        ),\n        Effect.flatMap((nextValue) =>\n          nextValue === null ? Effect.void : processKey(key, nextValue),\n        ),\n      );\n\n    const cleanupFailedKey = (key: K): Effect.Effect<void> =>\n      TxRef.modify(stateRef, (state) => {\n        const activeKeys = new Set(state.activeKeys);\n        activeKeys.delete(key);\n\n        if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {\n          const queuedKeys = new Set(state.queuedKeys);\n          queuedKeys.add(key);\n          return [true, { ...state, activeKeys, queuedKeys }] as const;\n        }\n\n        return [false, { ...state, activeKeys }] as const;\n      }).pipe(\n        Effect.tx,\n        Effect.flatMap((shouldRequeue) =>\n          shouldRequeue ? TxQueue.offer(queue, key) : Effect.void,\n        ),\n      );\n\n    yield* TxQueue.take(queue).pipe(\n      Effect.flatMap((key) =>\n        TxRef.modify(stateRef, (state) => {\n          const queuedKeys = new Set(state.queuedKeys);\n          queuedKeys.delete(key);\n\n          const value = state.latestByKey.get(key);\n          if (value === undefined) {\n            return [null, { ...state, queuedKeys }] as const;\n          }\n\n          const latestByKey = new Map(state.latestByKey);\n          latestByKey.delete(key);\n          const activeKeys = new Set(state.activeKeys);\n          activeKeys.add(key);\n\n          return [\n            { key, value } as const,\n            { ...state, latestByKey, queuedKeys, activeKeys },\n          ] as const;\n        }).pipe(Effect.tx),\n      ),\n      Effect.flatMap((item) =>\n        item === null\n          ? Effect.void\n          : processKey(item.key, item.value).pipe(\n              Effect.catchCause(() => cleanupFailedKey(item.key)),\n            ),\n      ),\n      Effect.forever,\n      Effect.forkScoped,\n    );\n\n    const enqueue: KeyedCoalescingWorker<K, V>[\"enqueue\"] = (key, value) =>\n      TxRef.modify(stateRef, (state) => {\n        const latestByKey = new Map(state.latestByKey);\n        const existing = latestByKey.get(key);\n        latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));\n\n        if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {\n          return [false, { ...state, latestByKey }] as const;\n        }\n\n        const queuedKeys = new Set(state.queuedKeys);\n        queuedKeys.add(key);\n        return [true, { ...state, latestByKey, queuedKeys }] as const;\n      }).pipe(\n        Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),\n        Effect.tx,\n        Effect.asVoid,\n      );\n\n    const drainKey: KeyedCoalescingWorker<K, V>[\"drainKey\"] = (key) =>\n      TxRef.get(stateRef).pipe(\n        Effect.tap((state) =>\n          state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)\n            ? Effect.txRetry\n            : Effect.void,\n        ),\n        Effect.asVoid,\n        Effect.tx,\n      );\n\n    return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;\n  });\n","import type { TerminalSummary } from \"@t3tools/contracts\";\n\n/** Human-readable label for a terminal tab; matches mobile and web sidebars. */\nexport function getTerminalLabel(terminalId: string): string {\n  const numericSuffix = /^term(?:inal)?-(\\d+)$/i.exec(terminalId)?.[1];\n  if (numericSuffix) {\n    return `Terminal ${numericSuffix}`;\n  }\n\n  return terminalId;\n}\n\n/** Prefer server summary label when present; otherwise fall back to `getTerminalLabel`. */\nexport function resolveTerminalSessionLabel(\n  terminalId: string,\n  summary: Pick<TerminalSummary, \"label\"> | null | undefined,\n): string {\n  const trimmed = summary?.label?.trim();\n  if (trimmed && trimmed.length > 0) {\n    return trimmed;\n  }\n  return getTerminalLabel(terminalId);\n}\n\n/**\n * Client-side terminal id allocator. Ids are ALWAYS chosen by the client and sent explicitly\n * on every `terminal.open` / `terminal.attach` call — the server never allocates.\n *\n * Returns the lowest unused `term-N` id (starting at `term-1`), skipping any ids already in\n * `existingTerminalIds`.\n */\nexport function nextTerminalId(existingTerminalIds: ReadonlyArray<string>): string {\n  const usedIds = new Set(existingTerminalIds.filter((id) => id.trim().length > 0));\n  let nextIndex = 1;\n  while (usedIds.has(`term-${nextIndex}`)) {\n    nextIndex += 1;\n  }\n\n  return `term-${nextIndex}`;\n}\n","/**\n * Pure URL helpers shared between the preview server, desktop main process,\n * and web renderer. Centralising these guarantees the four call sites agree\n * on what counts as \"loopback\" and how to normalise a free-form URL string.\n */\n\nimport * as Schema from \"effect/Schema\";\n\nconst TAB_ID_PREFIX = \"tab_\";\nlet nextPreviewTabSequence = 0;\n\n/**\n * Generate a fresh preview tab id. Lives in shared (not contracts) because\n * the contracts package is schema-only — runtime helpers belong here.\n */\nexport function newPreviewTabId(): string {\n  nextPreviewTabSequence += 1;\n  return `${TAB_ID_PREFIX}${nextPreviewTabSequence.toString(36)}`;\n}\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set([\"localhost\", \"127.0.0.1\", \"0.0.0.0\", \"::1\"]);\n\n/** Internal — used by `lsof` parsing where the host string is wire-formatted. */\nexport const LSOF_LOCAL_HOST_TOKENS: ReadonlySet<string> = new Set([\n  ...LOOPBACK_HOSTS,\n  \"*\",\n  \"[::]\",\n  \"[::1]\",\n]);\n\nconst LOOPBACK_PREFIX_PATTERN = /^(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|\\[::1?\\])(?::|\\/|$)/i;\n\nexport function isLoopbackHost(host: string): boolean {\n  if (LOOPBACK_HOSTS.has(host)) return true;\n  if (host === \"[::1]\") return true;\n  return false;\n}\n\n/** True when a raw URL string looks like a loopback dev URL we can preview. */\nexport function isPreviewableUrl(rawUrl: string): boolean {\n  try {\n    const parsed = new URL(rawUrl);\n    if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") return false;\n    return isLoopbackHost(parsed.hostname);\n  } catch {\n    return false;\n  }\n}\n\nexport class PreviewUrlNormalizationError extends Schema.TaggedErrorClass<PreviewUrlNormalizationError>()(\n  \"PreviewUrlNormalizationError\",\n  {\n    inputLength: Schema.Number,\n    reason: Schema.Literals([\"empty\", \"parse\", \"unsupported-protocol\"]),\n    protocol: Schema.optional(Schema.String),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    const protocol = this.protocol === undefined ? \"\" : `: ${this.protocol}`;\n    return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}).`;\n  }\n}\n\nexport const isPreviewUrlNormalizationError = Schema.is(PreviewUrlNormalizationError);\n\nfunction previewUrlProtocol(rawUrl: string): string | undefined {\n  return /^([A-Za-z][A-Za-z\\d+.-]*):/.exec(rawUrl)?.[1]?.toLowerCase().concat(\":\");\n}\n\n/**\n * Normalise a free-form URL string into a fully-qualified `http(s)://` URL.\n *\n * - Bare loopback hosts (`localhost`, `localhost:5173`) become `http://...`.\n * - Bare public hosts (`example.com`) become `https://...`.\n * - Already-qualified URLs are validated and returned as `URL.href`.\n *\n * Throws `PreviewUrlNormalizationError` for empty, unparseable, or\n * unsupported-protocol inputs.\n */\nexport function normalizePreviewUrl(rawUrl: string): string {\n  const trimmed = rawUrl.trim();\n  if (trimmed.length === 0) {\n    throw new PreviewUrlNormalizationError({ inputLength: rawUrl.length, reason: \"empty\" });\n  }\n  const useHttp = LOOPBACK_PREFIX_PATTERN.test(trimmed);\n  const candidate = trimmed.includes(\"://\")\n    ? trimmed\n    : `${useHttp ? \"http\" : \"https\"}://${trimmed}`;\n  let parsed: URL;\n  try {\n    parsed = new URL(candidate);\n  } catch (cause) {\n    throw new PreviewUrlNormalizationError({\n      inputLength: rawUrl.length,\n      reason: \"parse\",\n      protocol: previewUrlProtocol(candidate),\n      cause,\n    });\n  }\n  if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n    throw new PreviewUrlNormalizationError({\n      inputLength: rawUrl.length,\n      reason: \"unsupported-protocol\",\n      protocol: parsed.protocol,\n    });\n  }\n  return parsed.href;\n}\n","/**\n * In-process PortScanner implementation.\n *\n * macOS/Linux: parses `lsof -iTCP -sTCP:LISTEN -P -n -F pcn` (-F output is a\n * stable line-prefixed field format; this is the only `lsof` flag set we rely\n * on).\n *\n * Windows / lsof missing: checks a curated list of common dev ports through\n * the shared Net service.\n *\n * Polling is reference-counted via scoped `retain`. A single layer-scoped fiber\n * polls forever, but each tick is a no-op when the retain count is zero.\n */\nimport { ThreadId, type DiscoveredLocalServer } from \"@t3tools/contracts\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Net from \"@t3tools/shared/Net\";\nimport { LSOF_LOCAL_HOST_TOKENS } from \"@t3tools/shared/preview\";\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Scope from \"effect/Scope\";\n\nimport * as ProcessRunner from \"../processRunner.ts\";\n\nexport class PortDiscovery extends Context.Service<\n  PortDiscovery,\n  {\n    readonly scan: () => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;\n    readonly subscribe: (\n      listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,\n    ) => Effect.Effect<void, never, Scope.Scope>;\n    readonly retain: Effect.Effect<void, never, Scope.Scope>;\n    readonly registerTerminalProcesses: (input: {\n      readonly threadId: string;\n      readonly terminalId: string;\n      readonly processIds: ReadonlyArray<number>;\n    }) => Effect.Effect<void>;\n    readonly unregisterTerminal: (input: {\n      readonly threadId: string;\n      readonly terminalId: string;\n    }) => Effect.Effect<void>;\n  }\n>()(\"t3/preview/PortScanner/PortDiscovery\") {}\n\nexport const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([\n  3000, 3001, 3333, 4173, 4200, 4321, 5000, 5173, 5174, 5175, 5500, 8000, 8080, 8081, 8888, 9000,\n]);\n\nconst POLL_INTERVAL = Duration.seconds(3);\nconst LSOF_TIMEOUT_MS = 5_000;\nconst WINDOWS_LISTENER_TIMEOUT_MS = 5_000;\n\ntype Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;\n\ninterface ScannerState {\n  readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;\n  readonly listeners: ReadonlySet<Listener>;\n  readonly terminalProcesses: ReadonlyMap<\n    string,\n    {\n      readonly owner: TerminalProcessOwner;\n      readonly processIds: ReadonlySet<number>;\n    }\n  >;\n  readonly retainCount: number;\n}\n\ninterface TerminalProcessOwner {\n  readonly threadId: ThreadId;\n  readonly terminalId: string;\n}\n\nconst terminalOwnerKey = (owner: {\n  readonly threadId: string;\n  readonly terminalId: string;\n}): string => `${owner.threadId}\\u0000${owner.terminalId}`;\n\nconst parseLsofOutput = (\n  raw: string,\n  terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),\n): ReadonlyArray<DiscoveredLocalServer> => {\n  const seen = new Map<string, DiscoveredLocalServer>();\n  let pid: number | null = null;\n  let processName: string | null = null;\n\n  for (const line of raw.split(\"\\n\")) {\n    if (line.length === 0) continue;\n    const tag = line.charAt(0);\n    const value = line.slice(1);\n    if (tag === \"p\") {\n      const parsed = Number.parseInt(value, 10);\n      pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n      processName = null;\n      continue;\n    }\n    if (tag === \"c\") {\n      processName = value.trim() || null;\n      continue;\n    }\n    if (tag === \"n\") {\n      const portMatch = parsePortFromLsofName(value);\n      if (portMatch == null) continue;\n      const url = `http://localhost:${portMatch}`;\n      const key = `localhost:${portMatch}`;\n      if (seen.has(key)) continue;\n      seen.set(key, {\n        host: \"localhost\",\n        port: portMatch,\n        url,\n        processName,\n        pid,\n        terminal: pid === null ? null : (terminalByProcessId.get(pid) ?? null),\n      });\n    }\n  }\n\n  return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);\n};\n\nconst parsePortFromLsofName = (name: string): number | null => {\n  // Examples: \"*:5173\", \"127.0.0.1:5173\", \"[::1]:5173\", \"localhost:5173\",\n  //           \"192.168.1.10:5173 (LISTEN)\" — we only care if the host part is local.\n  const trimmed = name.split(\" \", 1)[0]?.trim() ?? \"\";\n  if (trimmed.length === 0) return null;\n  const lastColon = trimmed.lastIndexOf(\":\");\n  if (lastColon < 0) return null;\n  const hostPart = trimmed.slice(0, lastColon);\n  const portPart = trimmed.slice(lastColon + 1);\n  if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;\n  const port = Number.parseInt(portPart, 10);\n  if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;\n  return port;\n};\n\nconst parseWindowsListenerOutput = (\n  raw: string,\n  terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),\n): ReadonlyArray<DiscoveredLocalServer> => {\n  const seen = new Map<number, DiscoveredLocalServer>();\n  for (const line of raw.split(/\\r?\\n/g)) {\n    const [hostRaw, portRaw, pidRaw, processNameRaw] = line.trim().split(\"|\", 4);\n    const host = hostRaw?.trim() ?? \"\";\n    if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== \"::\") continue;\n    const port = Number(portRaw);\n    const pid = Number(pidRaw);\n    if (!Number.isInteger(port) || port <= 0 || port >= 65536) continue;\n    const normalizedPid = Number.isInteger(pid) && pid > 0 ? pid : null;\n    if (seen.has(port)) continue;\n    seen.set(port, {\n      host: \"localhost\",\n      port,\n      url: `http://localhost:${port}`,\n      processName: processNameRaw?.trim() || null,\n      pid: normalizedPid,\n      terminal: normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null),\n    });\n  }\n  return [...seen.values()].toSorted((left, right) => left.port - right.port);\n};\n\nconst serversEqual = (\n  left: ReadonlyArray<DiscoveredLocalServer>,\n  right: ReadonlyArray<DiscoveredLocalServer>,\n): boolean => {\n  if (left.length !== right.length) return false;\n  for (let i = 0; i < left.length; i += 1) {\n    const a = left[i];\n    const b = right[i];\n    if (!a || !b) return false;\n    if (\n      a.host !== b.host ||\n      a.port !== b.port ||\n      a.url !== b.url ||\n      a.processName !== b.processName ||\n      a.pid !== b.pid ||\n      a.terminal?.threadId !== b.terminal?.threadId ||\n      a.terminal?.terminalId !== b.terminal?.terminalId\n    ) {\n      return false;\n    }\n  }\n  return true;\n};\n\nexport const make = Effect.gen(function* PortDiscoveryMake() {\n  const net = yield* Net.NetService;\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n  const hostPlatform = yield* HostProcessPlatform;\n  const stateRef = yield* Ref.make<ScannerState>({\n    lastSnapshot: [],\n    listeners: new Set(),\n    terminalProcesses: new Map(),\n    retainCount: 0,\n  });\n\n  const probeCommonPorts = Effect.fn(\"PortDiscovery.probeCommonPorts\")(function* () {\n    const results = yield* Effect.forEach(\n      COMMON_DEV_PORTS,\n      (port) =>\n        net.isPortAvailableOnLoopback(port).pipe(\n          Effect.map((available) => ({\n            port,\n            listening: !available,\n          })),\n        ),\n      { concurrency: \"unbounded\" },\n    );\n    return results\n      .filter((result) => result.listening)\n      .map<DiscoveredLocalServer>((result) => ({\n        host: \"localhost\",\n        port: result.port,\n        url: `http://localhost:${result.port}`,\n        processName: null,\n        pid: null,\n        terminal: null,\n      }));\n  });\n\n  const recoverProcessProbeFailure =\n    (probe: \"lsof\" | \"windows-listeners\") => (error: ProcessRunner.ProcessRunError) =>\n      Effect.logDebug(\"preview port process probe failed; falling back to common-port probes\", {\n        cause: error,\n        probe,\n        platform: hostPlatform,\n      }).pipe(Effect.as(null));\n\n  const scanOnce = Effect.fn(\"PortDiscovery.scan\")(function* () {\n    const state = yield* Ref.get(stateRef);\n    const terminalByProcessId = new Map<number, TerminalProcessOwner>();\n    for (const registration of state.terminalProcesses.values()) {\n      for (const processId of registration.processIds) {\n        terminalByProcessId.set(processId, registration.owner);\n      }\n    }\n    if (hostPlatform === \"win32\") {\n      const recoverWindowsProbeFailure = recoverProcessProbeFailure(\"windows-listeners\");\n      const command =\n        'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output \"$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName\" }';\n      const listeners = yield* processRunner\n        .run({\n          command: \"powershell.exe\",\n          args: [\"-NoProfile\", \"-NonInteractive\", \"-Command\", command],\n          timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS),\n          maxOutputBytes: 1024 * 1024,\n          outputMode: \"truncate\",\n        })\n        .pipe(\n          Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)),\n          Effect.catchTags({\n            ProcessSpawnError: recoverWindowsProbeFailure,\n            ProcessStdinError: recoverWindowsProbeFailure,\n            ProcessOutputLimitError: recoverWindowsProbeFailure,\n            ProcessReadError: recoverWindowsProbeFailure,\n            ProcessTimeoutError: recoverWindowsProbeFailure,\n          }),\n        );\n      if (listeners !== null) return listeners;\n      return yield* probeCommonPorts();\n    }\n    const recoverLsofProbeFailure = recoverProcessProbeFailure(\"lsof\");\n    const lsofResult = yield* processRunner\n      .run({\n        command: \"lsof\",\n        args: [\"-iTCP\", \"-sTCP:LISTEN\", \"-P\", \"-n\", \"-F\", \"pcn\"],\n        timeout: Duration.millis(LSOF_TIMEOUT_MS),\n        maxOutputBytes: 1024 * 1024,\n        outputMode: \"truncate\",\n      })\n      .pipe(\n        Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),\n        Effect.catchTags({\n          ProcessSpawnError: recoverLsofProbeFailure,\n          ProcessStdinError: recoverLsofProbeFailure,\n          ProcessOutputLimitError: recoverLsofProbeFailure,\n          ProcessReadError: recoverLsofProbeFailure,\n          ProcessTimeoutError: recoverLsofProbeFailure,\n        }),\n      );\n    if (lsofResult !== null) return lsofResult;\n    return yield* probeCommonPorts();\n  });\n\n  const broadcast = Effect.fn(\"PortDiscovery.broadcast\")(function* (\n    servers: ReadonlyArray<DiscoveredLocalServer>,\n  ) {\n    const listeners = (yield* Ref.get(stateRef)).listeners;\n    yield* Effect.forEach(listeners, (listener) => listener(servers), { discard: true });\n  });\n\n  const pollTick = Effect.fn(\"PortDiscovery.pollTick\")(\n    function* () {\n      if ((yield* Ref.get(stateRef)).retainCount <= 0) return;\n      const next = yield* scanOnce();\n      const changed = yield* Ref.modify(stateRef, (state) =>\n        serversEqual(state.lastSnapshot, next)\n          ? [false, state]\n          : [true, { ...state, lastSnapshot: next }],\n      );\n      if (changed) yield* broadcast(next);\n    },\n    Effect.catchCause((cause: Cause.Cause<never>) =>\n      Effect.logWarning(\"preview port scan failed\", Cause.pretty(cause)),\n    ),\n  );\n\n  // Single layer-scoped polling fiber. Ticks are no-ops when no client is\n  // currently retained, so the cost is one Ref.get every POLL_INTERVAL.\n  yield* Effect.forkScoped(pollTick().pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));\n\n  const acquireRetention = Effect.fn(\"PortDiscovery.retain\")(function* () {\n    const wasIdle = yield* Ref.modify(stateRef, (state) => [\n      state.retainCount === 0,\n      { ...state, retainCount: state.retainCount + 1 },\n    ]);\n    if (wasIdle) {\n      // Run an immediate scan + broadcast so the new retainer doesn't have\n      // to wait up to POLL_INTERVAL for the first emission.\n      yield* pollTick();\n    }\n  });\n\n  const retain: PortDiscovery[\"Service\"][\"retain\"] = Effect.acquireRelease(acquireRetention(), () =>\n    Ref.update(stateRef, (state) => ({\n      ...state,\n      retainCount: Math.max(0, state.retainCount - 1),\n    })),\n  );\n\n  const subscribe: PortDiscovery[\"Service\"][\"subscribe\"] = Effect.fn(\"PortDiscovery.subscribe\")(\n    (listener) =>\n      Effect.acquireRelease(\n        Ref.update(stateRef, (state) => ({\n          ...state,\n          listeners: new Set([...state.listeners, listener]),\n        })),\n        () =>\n          Ref.update(stateRef, (state) => {\n            const listeners = new Set(state.listeners);\n            listeners.delete(listener);\n            return { ...state, listeners };\n          }),\n      ),\n  );\n\n  const registerTerminalProcesses: PortDiscovery[\"Service\"][\"registerTerminalProcesses\"] =\n    Effect.fn(\"PortDiscovery.registerTerminalProcesses\")(function* (input) {\n      const owner = {\n        threadId: ThreadId.make(input.threadId),\n        terminalId: input.terminalId,\n      };\n      const processIds = new Set(\n        input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),\n      );\n      yield* Ref.update(stateRef, (state) => {\n        const terminalProcesses = new Map(state.terminalProcesses);\n        const key = terminalOwnerKey(owner);\n        if (processIds.size === 0) {\n          terminalProcesses.delete(key);\n        } else {\n          terminalProcesses.set(key, { owner, processIds });\n        }\n        return { ...state, terminalProcesses };\n      });\n    });\n\n  const unregisterTerminal: PortDiscovery[\"Service\"][\"unregisterTerminal\"] = Effect.fn(\n    \"PortDiscovery.unregisterTerminal\",\n  )(function* (input) {\n    yield* Ref.update(stateRef, (state) => {\n      const terminalProcesses = new Map(state.terminalProcesses);\n      terminalProcesses.delete(terminalOwnerKey(input));\n      return { ...state, terminalProcesses };\n    });\n  });\n\n  return PortDiscovery.of({\n    scan: scanOnce,\n    subscribe,\n    retain,\n    registerTerminalProcesses,\n    unregisterTerminal,\n  });\n}).pipe(Effect.withSpan(\"PortDiscovery.make\"));\n\nexport const layer = Layer.effect(PortDiscovery, make);\n","/**\n * TerminalManager - Terminal session orchestration service interface.\n *\n * Owns terminal lifecycle operations, output fanout, and session state\n * transitions for thread-scoped terminals.\n *\n * @module TerminalManager\n */\nimport {\n  DEFAULT_TERMINAL_ID,\n  TerminalCwdError,\n  TerminalCwdNotDirectoryError,\n  TerminalCwdNotFoundError,\n  TerminalCwdStatError,\n  TerminalError,\n  TerminalHistoryError,\n  TerminalNotRunningError,\n  TerminalResizeError,\n  TerminalSessionLookupError,\n  TerminalWriteError,\n  type TerminalAttachInput,\n  type TerminalAttachStreamEvent,\n  type TerminalClearInput,\n  type TerminalCloseInput,\n  type TerminalEvent,\n  type TerminalMetadataStreamEvent,\n  type TerminalOpenInput,\n  type TerminalResizeInput,\n  type TerminalRestartInput,\n  type TerminalSessionSnapshot,\n  type TerminalSessionStatus,\n  type TerminalSummary,\n  type TerminalWriteInput,\n} from \"@t3tools/contracts\";\nimport { makeKeyedCoalescingWorker } from \"@t3tools/shared/KeyedCoalescingWorker\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { getTerminalLabel } from \"@t3tools/shared/terminalLabels\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as Equal from \"effect/Equal\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport {\n  increment,\n  terminalRestartsTotal,\n  terminalSessionsTotal,\n} from \"../observability/Metrics.ts\";\nimport * as ProcessRunner from \"../processRunner.ts\";\nimport * as PortScanner from \"../preview/PortScanner.ts\";\nimport * as PtyAdapter from \"./PtyAdapter.ts\";\n\nexport {\n  TerminalCwdError,\n  TerminalCwdNotDirectoryError,\n  TerminalCwdNotFoundError,\n  TerminalCwdStatError,\n  TerminalError,\n  TerminalHistoryError,\n  TerminalNotRunningError,\n  TerminalResizeError,\n  TerminalSessionLookupError,\n  TerminalWriteError,\n};\n\nconst DEFAULT_HISTORY_LINE_LIMIT = 5_000;\nconst DEFAULT_PERSIST_DEBOUNCE_MS = 40;\nconst DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;\nconst DEFAULT_PROCESS_KILL_GRACE_MS = 1_000;\nconst DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;\nconst DEFAULT_OPEN_COLS = 120;\nconst DEFAULT_OPEN_ROWS = 30;\nconst TERMINAL_ENV_BLOCKLIST = new Set([\"PORT\", \"ELECTRON_RENDERER_PORT\", \"ELECTRON_RUN_AS_NODE\"]);\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\nconst MAX_TERMINAL_LABEL_LENGTH = 128;\n\nclass TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubprocessCheckError>()(\n  \"TerminalSubprocessCheckError\",\n  {\n    cause: Schema.optional(Schema.Defect()),\n    terminalPid: Schema.Number,\n    command: Schema.Literals([\"powershell\", \"pgrep\", \"ps\"]),\n  },\n) {\n  override get message(): string {\n    return `Failed to inspect terminal subprocesses for PID ${this.terminalPid} with ${this.command}`;\n  }\n}\n\nclass TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcessSignalError>()(\n  \"TerminalProcessSignalError\",\n  {\n    cause: Schema.optional(Schema.Defect()),\n    signal: Schema.Literals([\"SIGTERM\", \"SIGKILL\"]),\n    terminalPid: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Failed to send ${this.signal} to terminal process ${this.terminalPid}`;\n  }\n}\n\n/**\n * TerminalManager - Service tag for terminal session orchestration.\n */\nexport class TerminalManager extends Context.Service<\n  TerminalManager,\n  {\n    /**\n     * Open or attach to a terminal session.\n     *\n     * Reuses an existing session for the same thread/terminal id and restores\n     * persisted history on first open.\n     */\n    readonly open: (\n      input: TerminalOpenInput,\n    ) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;\n\n    /**\n     * Attach to a terminal and stream its initial snapshot followed by live events.\n     *\n     * Returns an unsubscribe function.\n     */\n    readonly attachStream: (\n      input: TerminalAttachInput,\n      listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,\n    ) => Effect.Effect<() => void, TerminalError>;\n\n    /**\n     * Write input bytes to a terminal session.\n     */\n    readonly write: (input: TerminalWriteInput) => Effect.Effect<void, TerminalError>;\n\n    /**\n     * Resize the PTY backing a terminal session.\n     */\n    readonly resize: (input: TerminalResizeInput) => Effect.Effect<void, TerminalError>;\n\n    /**\n     * Clear terminal output history.\n     */\n    readonly clear: (input: TerminalClearInput) => Effect.Effect<void, TerminalError>;\n\n    /**\n     * Restart a terminal session in place.\n     *\n     * Always resets history before spawning the new process.\n     */\n    readonly restart: (\n      input: TerminalRestartInput,\n    ) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;\n\n    /**\n     * Close an active terminal session.\n     *\n     * When `terminalId` is omitted, closes all sessions for the thread.\n     */\n    readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;\n\n    /**\n     * Subscribe to terminal runtime events with a direct callback.\n     *\n     * Returns an unsubscribe function.\n     */\n    readonly subscribe: (\n      listener: (event: TerminalEvent) => Effect.Effect<void>,\n    ) => Effect.Effect<() => void>;\n\n    /**\n     * Subscribe to lightweight terminal metadata with an initial full snapshot.\n     *\n     * Returns an unsubscribe function.\n     */\n    readonly subscribeMetadata: (\n      listener: (event: TerminalMetadataStreamEvent) => Effect.Effect<void>,\n    ) => Effect.Effect<() => void>;\n  }\n>()(\"t3/terminal/Manager/TerminalManager\") {}\n\ninterface TerminalSubprocessInspectResult {\n  readonly hasRunningSubprocess: boolean;\n  readonly childCommand: string | null;\n  readonly processIds: ReadonlyArray<number>;\n}\n\ninterface TerminalSubprocessInspector {\n  (\n    terminalPid: number,\n  ): Effect.Effect<TerminalSubprocessInspectResult, TerminalSubprocessCheckError>;\n}\n\nconst resizePtyProcess = (\n  session: TerminalSessionState,\n  process: PtyAdapter.PtyProcess,\n  cols: number,\n  rows: number,\n) =>\n  Effect.try({\n    try: () => process.resize(cols, rows),\n    catch: (cause) =>\n      new TerminalResizeError({\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n        terminalPid: process.pid,\n        cols,\n        rows,\n        cause,\n      }),\n  });\n\nexport interface ShellCandidate {\n  shell: string;\n  args?: string[];\n}\n\nexport interface TerminalStartInput extends TerminalOpenInput {\n  cols: number;\n  rows: number;\n}\n\nexport interface TerminalSessionState {\n  threadId: string;\n  terminalId: string;\n  cwd: string;\n  worktreePath: string | null;\n  status: TerminalSessionStatus;\n  pid: number | null;\n  history: string;\n  pendingHistoryControlSequence: string;\n  pendingProcessEvents: Array<PendingProcessEvent>;\n  pendingProcessEventIndex: number;\n  processEventDrainRunning: boolean;\n  exitCode: number | null;\n  exitSignal: number | null;\n  updatedAt: string;\n  eventSequence: number;\n  cols: number;\n  rows: number;\n  process: PtyAdapter.PtyProcess | null;\n  unsubscribeData: (() => void) | null;\n  unsubscribeExit: (() => void) | null;\n  hasRunningSubprocess: boolean;\n  /** Normalized child command name when `hasRunningSubprocess`; cleared when idle. */\n  childCommandLabel: string | null;\n  runtimeEnv: Record<string, string> | null;\n}\n\ninterface PersistHistoryRequest {\n  history: string;\n  immediate: boolean;\n}\n\ntype PendingProcessEvent =\n  | { type: \"output\"; data: string }\n  | { type: \"exit\"; event: PtyAdapter.PtyExitEvent };\n\ntype DrainProcessEventAction =\n  | { type: \"idle\" }\n  | {\n      type: \"output\";\n      threadId: string;\n      terminalId: string;\n      sequence: number;\n      history: string | null;\n      data: string;\n    }\n  | {\n      type: \"exit\";\n      process: PtyAdapter.PtyProcess | null;\n      threadId: string;\n      terminalId: string;\n      sequence: number;\n      exitCode: number | null;\n      exitSignal: number | null;\n    };\n\ninterface TerminalManagerState {\n  sessions: Map<string, TerminalSessionState>;\n  killFibers: Map<PtyAdapter.PtyProcess, Fiber.Fiber<void, never>>;\n}\n\nfunction truncateTerminalWireLabel(value: string): string {\n  if (value.length <= MAX_TERMINAL_LABEL_LENGTH) return value;\n  return value.slice(0, MAX_TERMINAL_LABEL_LENGTH);\n}\n\nfunction normalizeChildCommandName(raw: string, platform: NodeJS.Platform): string | null {\n  let trimmed = raw.trim();\n  if (trimmed.length === 0) return null;\n  if (\n    (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) ||\n    (trimmed.startsWith(\"(\") && trimmed.endsWith(\")\"))\n  ) {\n    trimmed = trimmed.slice(1, -1).trim();\n  }\n  const firstToken = (trimmed.split(/\\s+/)[0] ?? trimmed).trim();\n  if (firstToken.length === 0) return null;\n  const separators = platform === \"win32\" ? /[\\\\/]/ : /\\//;\n  const base = firstToken.split(separators).at(-1) ?? firstToken;\n  const withoutExe =\n    platform === \"win32\" && base.toLowerCase().endsWith(\".exe\") ? base.slice(0, -4) : base;\n  return withoutExe.length > 0 ? withoutExe : null;\n}\n\nfunction terminalWireLabel(session: TerminalSessionState): string {\n  if (session.hasRunningSubprocess && session.childCommandLabel) {\n    const trimmed = session.childCommandLabel.trim();\n    if (trimmed.length > 0) {\n      return truncateTerminalWireLabel(trimmed);\n    }\n  }\n  return truncateTerminalWireLabel(getTerminalLabel(session.terminalId));\n}\n\nfunction snapshot(session: TerminalSessionState): TerminalSessionSnapshot {\n  return {\n    threadId: session.threadId,\n    terminalId: session.terminalId,\n    cwd: session.cwd,\n    worktreePath: session.worktreePath,\n    status: session.status,\n    pid: session.pid,\n    history: session.history,\n    exitCode: session.exitCode,\n    exitSignal: session.exitSignal,\n    label: terminalWireLabel(session),\n    updatedAt: session.updatedAt,\n    sequence: session.eventSequence,\n  };\n}\n\nfunction summary(session: TerminalSessionState): TerminalSummary {\n  return {\n    threadId: session.threadId,\n    terminalId: session.terminalId,\n    cwd: session.cwd,\n    worktreePath: session.worktreePath,\n    status: session.status,\n    pid: session.pid,\n    exitCode: session.exitCode,\n    exitSignal: session.exitSignal,\n    hasRunningSubprocess: session.hasRunningSubprocess,\n    label: terminalWireLabel(session),\n    updatedAt: session.updatedAt,\n  };\n}\n\nfunction shouldPublishTerminalMetadataEvent(event: TerminalEvent): boolean {\n  switch (event.type) {\n    case \"started\":\n    case \"restarted\":\n    case \"exited\":\n    case \"closed\":\n    case \"error\":\n    case \"activity\":\n      return true;\n    case \"output\":\n    case \"cleared\":\n      return false;\n  }\n}\n\nfunction terminalEventToAttachEvent(event: TerminalEvent): TerminalAttachStreamEvent | null {\n  switch (event.type) {\n    case \"started\":\n      return {\n        type: \"snapshot\",\n        snapshot: event.snapshot,\n      };\n    case \"output\":\n    case \"exited\":\n    case \"closed\":\n    case \"error\":\n    case \"cleared\":\n    case \"restarted\":\n    case \"activity\":\n      return event;\n  }\n}\n\nfunction isDuplicateAttachSnapshotEvent(\n  event: TerminalEvent,\n  initialSnapshot: TerminalSessionSnapshot,\n) {\n  return typeof event.sequence === \"number\" && typeof initialSnapshot.sequence === \"number\"\n    ? event.sequence <= initialSnapshot.sequence\n    : event.type === \"started\" &&\n        event.snapshot.threadId === initialSnapshot.threadId &&\n        event.snapshot.terminalId === initialSnapshot.terminalId &&\n        event.snapshot.updatedAt <= initialSnapshot.updatedAt;\n}\n\nfunction advanceEventSequence(session: TerminalSessionState): {\n  readonly updatedAt: string;\n  readonly sequence: number;\n} {\n  const updatedAt = DateTime.formatIso(DateTime.nowUnsafe());\n  session.eventSequence += 1;\n  session.updatedAt = updatedAt;\n  return { updatedAt, sequence: session.eventSequence };\n}\n\nfunction cleanupProcessHandles(session: TerminalSessionState): void {\n  session.unsubscribeData?.();\n  session.unsubscribeData = null;\n  session.unsubscribeExit?.();\n  session.unsubscribeExit = null;\n}\n\nfunction enqueueProcessEvent(\n  session: TerminalSessionState,\n  expectedPid: number,\n  event: PendingProcessEvent,\n): boolean {\n  if (!session.process || session.status !== \"running\" || session.pid !== expectedPid) {\n    return false;\n  }\n\n  session.pendingProcessEvents.push(event);\n  if (session.processEventDrainRunning) {\n    return false;\n  }\n\n  session.processEventDrainRunning = true;\n  return true;\n}\n\nfunction defaultShellResolver(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): string {\n  if (platform === \"win32\") {\n    return \"pwsh.exe\";\n  }\n  return env.SHELL ?? \"bash\";\n}\n\nfunction normalizeShellCommand(\n  value: string | undefined,\n  platform: NodeJS.Platform,\n): string | null {\n  if (!value) return null;\n  const trimmed = value.trim();\n  if (trimmed.length === 0) return null;\n\n  if (platform === \"win32\") {\n    return trimmed;\n  }\n\n  const firstToken = trimmed.split(/\\s+/g)[0]?.trim();\n  if (!firstToken) return null;\n  return firstToken.replace(/^['\"]|['\"]$/g, \"\");\n}\n\nfunction basenameForPlatform(command: string, platform: NodeJS.Platform): string {\n  const normalized =\n    platform === \"win32\" ? command.replaceAll(\"/\", \"\\\\\") : command.replaceAll(\"\\\\\", \"/\");\n  const parts = normalized\n    .split(platform === \"win32\" ? /\\\\+/ : /\\/+/)\n    .filter((part) => part.length > 0);\n  return parts.at(-1) ?? normalized;\n}\n\nfunction joinWindowsPath(...parts: ReadonlyArray<string>): string {\n  return parts\n    .map((part, index) => {\n      if (index === 0) return part.replace(/[\\\\/]+$/g, \"\");\n      return part.replace(/^[\\\\/]+|[\\\\/]+$/g, \"\");\n    })\n    .filter((part) => part.length > 0)\n    .join(\"\\\\\");\n}\n\nfunction shellCandidateFromCommand(\n  command: string | null,\n  platform: NodeJS.Platform,\n): ShellCandidate | null {\n  if (!command || command.length === 0) return null;\n  const shellName = basenameForPlatform(command, platform).toLowerCase();\n  if (platform === \"win32\" && (shellName === \"pwsh.exe\" || shellName === \"powershell.exe\")) {\n    return { shell: command, args: [\"-NoLogo\"] };\n  }\n  if (platform !== \"win32\" && shellName === \"zsh\") {\n    return { shell: command, args: [\"-o\", \"nopromptsp\"] };\n  }\n  return { shell: command };\n}\n\nfunction windowsSystemRoot(env: NodeJS.ProcessEnv): string {\n  return env.SystemRoot?.trim() || env.windir?.trim() || \"C:\\\\Windows\";\n}\n\nfunction windowsPowerShellPath(env: NodeJS.ProcessEnv): string {\n  return joinWindowsPath(\n    windowsSystemRoot(env),\n    \"System32\",\n    \"WindowsPowerShell\",\n    \"v1.0\",\n    \"powershell.exe\",\n  );\n}\n\nfunction windowsCmdPath(env: NodeJS.ProcessEnv): string {\n  return joinWindowsPath(windowsSystemRoot(env), \"System32\", \"cmd.exe\");\n}\n\nfunction formatShellCandidate(candidate: ShellCandidate): string {\n  if (!candidate.args || candidate.args.length === 0) return candidate.shell;\n  return `${candidate.shell} ${candidate.args.join(\" \")}`;\n}\n\nfunction uniqueShellCandidates(candidates: Array<ShellCandidate | null>): ShellCandidate[] {\n  const seen = new Set<string>();\n  const ordered: ShellCandidate[] = [];\n  for (const candidate of candidates) {\n    if (!candidate) continue;\n    const key = formatShellCandidate(candidate);\n    if (seen.has(key)) continue;\n    seen.add(key);\n    ordered.push(candidate);\n  }\n  return ordered;\n}\n\nfunction resolveShellCandidates(\n  shellResolver: () => string,\n  platform: NodeJS.Platform,\n  env: NodeJS.ProcessEnv,\n): ShellCandidate[] {\n  const requested = shellCandidateFromCommand(\n    normalizeShellCommand(shellResolver(), platform),\n    platform,\n  );\n\n  if (platform === \"win32\") {\n    return uniqueShellCandidates([\n      requested,\n      shellCandidateFromCommand(\"pwsh.exe\", platform),\n      shellCandidateFromCommand(windowsPowerShellPath(env), platform),\n      shellCandidateFromCommand(\"powershell.exe\", platform),\n      shellCandidateFromCommand(env.ComSpec ?? null, platform),\n      shellCandidateFromCommand(windowsCmdPath(env), platform),\n      shellCandidateFromCommand(\"cmd.exe\", platform),\n    ]);\n  }\n\n  return uniqueShellCandidates([\n    requested,\n    shellCandidateFromCommand(normalizeShellCommand(env.SHELL, platform), platform),\n    shellCandidateFromCommand(\"/bin/zsh\", platform),\n    shellCandidateFromCommand(\"/bin/bash\", platform),\n    shellCandidateFromCommand(\"/bin/sh\", platform),\n    shellCandidateFromCommand(\"zsh\", platform),\n    shellCandidateFromCommand(\"bash\", platform),\n    shellCandidateFromCommand(\"sh\", platform),\n  ]);\n}\n\nfunction isRetryableShellSpawnError(error: PtyAdapter.PtySpawnError): boolean {\n  const queue: unknown[] = [error];\n  const seen = new Set<unknown>();\n  const messages: string[] = [];\n\n  while (queue.length > 0) {\n    const current = queue.shift();\n    if (!current || seen.has(current)) {\n      continue;\n    }\n    seen.add(current);\n\n    if (typeof current === \"string\") {\n      messages.push(current);\n      continue;\n    }\n\n    if (current instanceof Error) {\n      messages.push(current.message);\n      if (current.cause) {\n        queue.push(current.cause);\n      }\n      continue;\n    }\n\n    if (typeof current === \"object\") {\n      const value = current as { message?: unknown; cause?: unknown };\n      if (typeof value.message === \"string\") {\n        messages.push(value.message);\n      }\n      if (value.cause) {\n        queue.push(value.cause);\n      }\n    }\n  }\n\n  const message = messages.join(\" \").toLowerCase();\n  return (\n    message.includes(\"posix_spawnp failed\") ||\n    message.includes(\"enoent\") ||\n    message.includes(\"not found\") ||\n    message.includes(\"file not found\") ||\n    message.includes(\"no such file\")\n  );\n}\n\nfunction parseFirstChildPidFromPgrep(stdout: string): number | null {\n  for (const line of stdout.split(/\\r?\\n/g)) {\n    const n = Number.parseInt(line.trim(), 10);\n    if (Number.isInteger(n) && n > 0) {\n      return n;\n    }\n  }\n  return null;\n}\n\nfunction windowsInspectSubprocess(\n  terminalPid: number,\n  platform: NodeJS.Platform,\n): Effect.Effect<\n  TerminalSubprocessInspectResult,\n  TerminalSubprocessCheckError,\n  ProcessRunner.ProcessRunner\n> {\n  const command =\n    'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { Write-Output \"$($_.ProcessId)|$($_.ParentProcessId)|$($_.Name)\" }';\n  return Effect.gen(function* () {\n    const processRunner = yield* ProcessRunner.ProcessRunner;\n    return yield* processRunner.run({\n      // powershell.exe is a real executable — never spawn it through cmd.exe\n      // shell mode, which would re-tokenize the `-Command` payload (pipes,\n      // semicolons) before PowerShell ever sees it.\n      command: \"powershell.exe\",\n      args: [\"-NoProfile\", \"-NonInteractive\", \"-Command\", command],\n      timeout: \"1500 millis\",\n      maxOutputBytes: 32_768,\n      outputMode: \"truncate\",\n      timeoutBehavior: \"timedOutResult\",\n    });\n  }).pipe(\n    Effect.map((result) => {\n      if (result.code !== 0) {\n        return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;\n      }\n      const processNameById = new Map<number, string>();\n      const childrenByParent = new Map<number, number[]>();\n      for (const line of result.stdout.split(/\\r?\\n/g)) {\n        const [pidRaw, parentPidRaw, nameRaw] = line.trim().split(\"|\", 3);\n        const pid = Number(pidRaw);\n        const parentPid = Number(parentPidRaw);\n        if (!Number.isInteger(pid) || !Number.isInteger(parentPid)) continue;\n        processNameById.set(pid, nameRaw?.trim() ?? \"\");\n        const children = childrenByParent.get(parentPid) ?? [];\n        children.push(pid);\n        childrenByParent.set(parentPid, children);\n      }\n      const directChildren = childrenByParent.get(terminalPid) ?? [];\n      const childPid = directChildren[0];\n      if (childPid === undefined) {\n        return { hasRunningSubprocess: false, childCommand: null, processIds: [] } as const;\n      }\n      const processIds = new Set<number>([terminalPid]);\n      const pending = [terminalPid];\n      while (pending.length > 0) {\n        const parentPid = pending.pop();\n        if (parentPid === undefined) continue;\n        for (const pid of childrenByParent.get(parentPid) ?? []) {\n          if (processIds.has(pid)) continue;\n          processIds.add(pid);\n          pending.push(pid);\n        }\n      }\n      const normalized = normalizeChildCommandName(processNameById.get(childPid) ?? \"\", platform);\n      return {\n        hasRunningSubprocess: true,\n        childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,\n        processIds: [...processIds],\n      } as const;\n    }),\n    Effect.mapError(\n      (cause) =>\n        new TerminalSubprocessCheckError({\n          cause,\n          terminalPid,\n          command: \"powershell\",\n        }),\n    ),\n  );\n}\n\nconst posixInspectSubprocess = Effect.fn(\"terminal.posixInspectSubprocess\")(function* (\n  terminalPid: number,\n  platform: NodeJS.Platform,\n): Effect.fn.Return<\n  TerminalSubprocessInspectResult,\n  TerminalSubprocessCheckError,\n  ProcessRunner.ProcessRunner\n> {\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n  const runPgrep = processRunner\n    .run({\n      command: \"pgrep\",\n      args: [\"-P\", String(terminalPid)],\n      timeout: \"1 second\",\n      maxOutputBytes: 32_768,\n      outputMode: \"truncate\",\n      timeoutBehavior: \"timedOutResult\",\n    })\n    .pipe(\n      Effect.mapError(\n        (cause) =>\n          new TerminalSubprocessCheckError({\n            cause,\n            terminalPid,\n            command: \"pgrep\",\n          }),\n      ),\n    );\n\n  const runPs = processRunner\n    .run({\n      command: \"ps\",\n      args: [\"-eo\", \"pid=,ppid=\"],\n      timeout: \"1 second\",\n      maxOutputBytes: 262_144,\n      outputMode: \"truncate\",\n      timeoutBehavior: \"timedOutResult\",\n    })\n    .pipe(\n      Effect.mapError(\n        (cause) =>\n          new TerminalSubprocessCheckError({\n            cause,\n            terminalPid,\n            command: \"ps\",\n          }),\n      ),\n    );\n\n  let childPid: number | null = null;\n\n  const pgrepResult = yield* Effect.exit(runPgrep);\n  if (pgrepResult._tag === \"Success\") {\n    if (pgrepResult.value.code === 0) {\n      childPid = parseFirstChildPidFromPgrep(pgrepResult.value.stdout);\n    } else if (pgrepResult.value.code === 1) {\n      return { hasRunningSubprocess: false, childCommand: null, processIds: [] };\n    }\n  }\n\n  if (childPid === null) {\n    const psResult = yield* Effect.exit(runPs);\n    if (psResult._tag === \"Failure\" || psResult.value.code !== 0) {\n      return { hasRunningSubprocess: false, childCommand: null, processIds: [] };\n    }\n    for (const line of psResult.value.stdout.split(/\\r?\\n/g)) {\n      const [pidRaw, ppidRaw] = line.trim().split(/\\s+/g);\n      const pid = Number(pidRaw);\n      const ppid = Number(ppidRaw);\n      if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;\n      if (ppid === terminalPid) {\n        childPid = pid;\n        break;\n      }\n    }\n  }\n\n  if (childPid === null) {\n    return { hasRunningSubprocess: false, childCommand: null, processIds: [] };\n  }\n\n  const runComm = processRunner.run({\n    command: \"ps\",\n    args: [\"-p\", String(childPid), \"-o\", \"comm=\"],\n    timeout: \"1 second\",\n    maxOutputBytes: 8_192,\n    outputMode: \"truncate\",\n    timeoutBehavior: \"timedOutResult\",\n  });\n\n  const commResult = yield* Effect.exit(runComm);\n  let rawComm: string | null = null;\n  if (commResult._tag === \"Success\" && commResult.value && commResult.value.code === 0) {\n    rawComm = commResult.value.stdout.trim();\n  }\n\n  if (!rawComm || rawComm.length === 0) {\n    const runArgs = processRunner.run({\n      command: \"ps\",\n      args: [\"-p\", String(childPid), \"-o\", \"args=\"],\n      timeout: \"1 second\",\n      maxOutputBytes: 16_384,\n      outputMode: \"truncate\",\n      timeoutBehavior: \"timedOutResult\",\n    });\n    const argsResult = yield* Effect.exit(runArgs);\n    if (argsResult._tag === \"Success\" && argsResult.value && argsResult.value.code === 0) {\n      const first = argsResult.value.stdout.trim().split(/\\s+/)[0] ?? \"\";\n      rawComm = first.length > 0 ? first : null;\n    }\n  }\n\n  const normalized = rawComm ? normalizeChildCommandName(rawComm, platform) : null;\n  const processIds = new Set<number>([terminalPid]);\n  const psResult = yield* Effect.exit(runPs);\n  if (psResult._tag === \"Success\" && psResult.value.code === 0) {\n    const childrenByParent = new Map<number, number[]>();\n    for (const line of psResult.value.stdout.split(/\\r?\\n/g)) {\n      const [pidRaw, ppidRaw] = line.trim().split(/\\s+/g);\n      const pid = Number(pidRaw);\n      const ppid = Number(ppidRaw);\n      if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;\n      const children = childrenByParent.get(ppid) ?? [];\n      children.push(pid);\n      childrenByParent.set(ppid, children);\n    }\n    const pending = [terminalPid];\n    while (pending.length > 0) {\n      const parentPid = pending.pop();\n      if (parentPid === undefined) continue;\n      for (const child of childrenByParent.get(parentPid) ?? []) {\n        if (processIds.has(child)) continue;\n        processIds.add(child);\n        pending.push(child);\n      }\n    }\n  } else {\n    processIds.add(childPid);\n  }\n  return {\n    hasRunningSubprocess: true,\n    childCommand: normalized ? truncateTerminalWireLabel(normalized) : null,\n    processIds: [...processIds],\n  };\n});\n\nfunction defaultSubprocessInspectorForPlatform(platform: NodeJS.Platform) {\n  return Effect.fn(\"terminal.defaultSubprocessInspector\")(function* (terminalPid: number) {\n    if (!Number.isInteger(terminalPid) || terminalPid <= 0) {\n      return { hasRunningSubprocess: false, childCommand: null, processIds: [] };\n    }\n    if (platform === \"win32\") {\n      return yield* windowsInspectSubprocess(terminalPid, platform);\n    }\n    return yield* posixInspectSubprocess(terminalPid, platform);\n  });\n}\n\nfunction capHistory(history: string, maxLines: number): string {\n  if (history.length === 0) return history;\n  const hasTrailingNewline = history.endsWith(\"\\n\");\n  const lines = history.split(\"\\n\");\n  if (hasTrailingNewline) {\n    lines.pop();\n  }\n  if (lines.length <= maxLines) return history;\n  const capped = lines.slice(lines.length - maxLines).join(\"\\n\");\n  return hasTrailingNewline ? `${capped}\\n` : capped;\n}\n\nfunction isCsiFinalByte(codePoint: number): boolean {\n  return codePoint >= 0x40 && codePoint <= 0x7e;\n}\n\nfunction shouldStripCsiSequence(body: string, finalByte: string): boolean {\n  if (finalByte === \"n\") {\n    return true;\n  }\n  if (finalByte === \"R\" && /^[0-9;?]*$/.test(body)) {\n    return true;\n  }\n  if (finalByte === \"c\" && /^[>0-9;?]*$/.test(body)) {\n    return true;\n  }\n  // DECRQM mode queries (…$p) and DECRPM replies (…$y): replaying a stored\n  // query makes the terminal answer again, and the shell echoes the answer as\n  // junk at the prompt. The `$` guard keeps setters like DECSTR (!p) and\n  // DECSCL (\"p) intact.\n  if ((finalByte === \"p\" || finalByte === \"y\") && /^[0-9;?]*\\$$/.test(body)) {\n    return true;\n  }\n  // XTVERSION query (>q). DECSCUSR (space-intermediate q) stays.\n  if (finalByte === \"q\" && /^>[0-9;]*$/.test(body)) {\n    return true;\n  }\n  // Kitty keyboard protocol query/reply (?u). Restore-cursor (bare u) stays.\n  if (finalByte === \"u\" && body.startsWith(\"?\")) {\n    return true;\n  }\n  return false;\n}\n\n// DECRQSS ($q) and XTGETTCAP (+q) queries plus their replies ([01]$r / [01]+r):\n// pure request/response traffic with no visual value, and replaying a stored\n// query triggers a fresh reply.\nfunction shouldStripDcsSequence(content: string): boolean {\n  return /^[01]?[$+][qr]/.test(content);\n}\n\nfunction shouldStripOscSequence(content: string): boolean {\n  return /^(10|11|12);(?:\\?|rgb:)/.test(content);\n}\n\nfunction stripStringTerminator(value: string): string {\n  if (value.endsWith(\"\\u001b\\\\\")) {\n    return value.slice(0, -2);\n  }\n  const lastCharacter = value.at(-1);\n  if (lastCharacter === \"\\u0007\" || lastCharacter === \"\\u009c\") {\n    return value.slice(0, -1);\n  }\n  return value;\n}\n\nfunction findStringTerminatorIndex(input: string, start: number): number | null {\n  for (let index = start; index < input.length; index += 1) {\n    const codePoint = input.charCodeAt(index);\n    if (codePoint === 0x07 || codePoint === 0x9c) {\n      return index + 1;\n    }\n    if (codePoint === 0x1b && input.charCodeAt(index + 1) === 0x5c) {\n      return index + 2;\n    }\n  }\n  return null;\n}\n\nfunction isEscapeIntermediateByte(codePoint: number): boolean {\n  return codePoint >= 0x20 && codePoint <= 0x2f;\n}\n\nfunction isEscapeFinalByte(codePoint: number): boolean {\n  return codePoint >= 0x30 && codePoint <= 0x7e;\n}\n\nfunction findEscapeSequenceEndIndex(input: string, start: number): number | null {\n  let cursor = start;\n  while (cursor < input.length && isEscapeIntermediateByte(input.charCodeAt(cursor))) {\n    cursor += 1;\n  }\n  if (cursor >= input.length) {\n    return null;\n  }\n  return isEscapeFinalByte(input.charCodeAt(cursor)) ? cursor + 1 : start + 1;\n}\n\nfunction sanitizeTerminalHistoryChunk(\n  pendingControlSequence: string,\n  data: string,\n): { visibleText: string; pendingControlSequence: string } {\n  const input = `${pendingControlSequence}${data}`;\n  let visibleText = \"\";\n  let index = 0;\n\n  const append = (value: string) => {\n    visibleText += value;\n  };\n\n  while (index < input.length) {\n    const codePoint = input.charCodeAt(index);\n\n    if (codePoint === 0x1b) {\n      const nextCodePoint = input.charCodeAt(index + 1);\n      if (Number.isNaN(nextCodePoint)) {\n        return { visibleText, pendingControlSequence: input.slice(index) };\n      }\n\n      if (nextCodePoint === 0x5b) {\n        let cursor = index + 2;\n        while (cursor < input.length) {\n          if (isCsiFinalByte(input.charCodeAt(cursor))) {\n            const sequence = input.slice(index, cursor + 1);\n            const body = input.slice(index + 2, cursor);\n            if (!shouldStripCsiSequence(body, input[cursor] ?? \"\")) {\n              append(sequence);\n            }\n            index = cursor + 1;\n            break;\n          }\n          cursor += 1;\n        }\n        if (cursor >= input.length) {\n          return { visibleText, pendingControlSequence: input.slice(index) };\n        }\n        continue;\n      }\n\n      if (\n        nextCodePoint === 0x5d ||\n        nextCodePoint === 0x50 ||\n        nextCodePoint === 0x5e ||\n        nextCodePoint === 0x5f\n      ) {\n        const terminatorIndex = findStringTerminatorIndex(input, index + 2);\n        if (terminatorIndex === null) {\n          return { visibleText, pendingControlSequence: input.slice(index) };\n        }\n        const sequence = input.slice(index, terminatorIndex);\n        const content = stripStringTerminator(input.slice(index + 2, terminatorIndex));\n        const strip =\n          (nextCodePoint === 0x5d && shouldStripOscSequence(content)) ||\n          (nextCodePoint === 0x50 && shouldStripDcsSequence(content));\n        if (!strip) {\n          append(sequence);\n        }\n        index = terminatorIndex;\n        continue;\n      }\n\n      const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1);\n      if (escapeSequenceEndIndex === null) {\n        return { visibleText, pendingControlSequence: input.slice(index) };\n      }\n      append(input.slice(index, escapeSequenceEndIndex));\n      index = escapeSequenceEndIndex;\n      continue;\n    }\n\n    if (codePoint === 0x9b) {\n      let cursor = index + 1;\n      while (cursor < input.length) {\n        if (isCsiFinalByte(input.charCodeAt(cursor))) {\n          const sequence = input.slice(index, cursor + 1);\n          const body = input.slice(index + 1, cursor);\n          if (!shouldStripCsiSequence(body, input[cursor] ?? \"\")) {\n            append(sequence);\n          }\n          index = cursor + 1;\n          break;\n        }\n        cursor += 1;\n      }\n      if (cursor >= input.length) {\n        return { visibleText, pendingControlSequence: input.slice(index) };\n      }\n      continue;\n    }\n\n    if (codePoint === 0x9d || codePoint === 0x90 || codePoint === 0x9e || codePoint === 0x9f) {\n      const terminatorIndex = findStringTerminatorIndex(input, index + 1);\n      if (terminatorIndex === null) {\n        return { visibleText, pendingControlSequence: input.slice(index) };\n      }\n      const sequence = input.slice(index, terminatorIndex);\n      const content = stripStringTerminator(input.slice(index + 1, terminatorIndex));\n      const strip =\n        (codePoint === 0x9d && shouldStripOscSequence(content)) ||\n        (codePoint === 0x90 && shouldStripDcsSequence(content));\n      if (!strip) {\n        append(sequence);\n      }\n      index = terminatorIndex;\n      continue;\n    }\n\n    append(input[index] ?? \"\");\n    index += 1;\n  }\n\n  return { visibleText, pendingControlSequence: \"\" };\n}\n\nfunction legacySafeThreadId(threadId: string): string {\n  return threadId.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n}\n\nfunction toSafeThreadId(threadId: string): string {\n  return `terminal_${Encoding.encodeBase64Url(threadId)}`;\n}\n\nfunction toSafeTerminalId(terminalId: string): string {\n  return Encoding.encodeBase64Url(terminalId);\n}\n\nfunction toSessionKey(threadId: string, terminalId: string): string {\n  return `${threadId}\\u0000${terminalId}`;\n}\n\nfunction shouldExcludeTerminalEnvKey(key: string): boolean {\n  const normalizedKey = key.toUpperCase();\n  if (normalizedKey.startsWith(\"SYNAPTIC_\")) {\n    return true;\n  }\n  if (normalizedKey.startsWith(\"VITE_\")) {\n    return true;\n  }\n  return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);\n}\n\n// Marker variables the AppImage runtime injects into the process it launches.\n// They describe the AppImage itself, not the user's session, so terminals must\n// not inherit them.\nconst APPIMAGE_RUNTIME_ENV_KEYS = [\"APPIMAGE\", \"APPDIR\", \"ARGV0\", \"OWD\"] as const;\n// Colon-separated search-path variables the AppImage runtime points at its\n// temporary mount (e.g. /tmp/.mount_T3-XXXX/usr/bin, the bundled glib schemas,\n// and an $APPDIR/usr/share XDG data entry). Only the mount segments are\n// dropped; the user's real entries are preserved. When nothing but mount\n// segments remain the variable is removed entirely so consumers fall back to\n// their platform default (e.g. gsettings finds the host schemas instead of\n// reporting \"No schemas installed\"). See issues #1699 and #5059.\nconst APPIMAGE_PATH_LIKE_ENV_KEYS = [\n  \"PATH\",\n  \"LD_LIBRARY_PATH\",\n  \"XDG_DATA_DIRS\",\n  \"GSETTINGS_SCHEMA_DIR\",\n] as const;\n\nfunction isPathSegmentUnderAppDir(segment: string, appDir: string): boolean {\n  return segment === appDir || segment.startsWith(`${appDir}/`);\n}\n\n// On Linux AppImage builds the runtime mounts the app under a temporary dir and\n// injects APPIMAGE/APPDIR/ARGV0/OWD plus mount entries on PATH/LD_LIBRARY_PATH.\n// The integrated terminal inherits the server process environment, so without\n// this scrub those leak into the PTY and tools resolve against the AppImage\n// mount instead of the user's real environment (e.g. `php` reporting\n// PHP_BINARY as the AppImage path). See issue #1699. The scrub is gated on an\n// actual AppImage launch so non-AppImage environments are left untouched.\nfunction stripAppImageRuntimeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n  if (env.APPIMAGE === undefined && env.APPDIR === undefined) return env;\n\n  const scrubbed: NodeJS.ProcessEnv = { ...env };\n  for (const key of APPIMAGE_RUNTIME_ENV_KEYS) {\n    delete scrubbed[key];\n  }\n\n  const appDir = env.APPDIR?.replace(/\\/+$/, \"\");\n  if (appDir) {\n    for (const key of APPIMAGE_PATH_LIKE_ENV_KEYS) {\n      const value = scrubbed[key];\n      if (value === undefined) continue;\n      const kept = value\n        .split(\":\")\n        .filter((segment) => segment.length > 0 && !isPathSegmentUnderAppDir(segment, appDir));\n      if (kept.length > 0) {\n        scrubbed[key] = kept.join(\":\");\n      } else {\n        delete scrubbed[key];\n      }\n    }\n  }\n\n  return scrubbed;\n}\n\nfunction createTerminalSpawnEnv(\n  baseEnv: NodeJS.ProcessEnv,\n  runtimeEnv?: Record<string, string> | null,\n): NodeJS.ProcessEnv {\n  const spawnEnv: NodeJS.ProcessEnv = {};\n  for (const [key, value] of Object.entries(baseEnv)) {\n    if (value === undefined) continue;\n    if (shouldExcludeTerminalEnvKey(key)) continue;\n    spawnEnv[key] = value;\n  }\n  if (runtimeEnv) {\n    for (const [key, value] of Object.entries(runtimeEnv)) {\n      spawnEnv[key] = value;\n    }\n  }\n  return stripAppImageRuntimeEnv(spawnEnv);\n}\n\nfunction normalizedRuntimeEnv(\n  env: Record<string, string> | undefined,\n): Record<string, string> | null {\n  if (!env) return null;\n  const entries = Object.entries(env);\n  if (entries.length === 0) return null;\n  return Object.fromEntries(entries.toSorted(([left], [right]) => left.localeCompare(right)));\n}\n\ninterface TerminalManagerOptions {\n  logsDir: string;\n  historyLineLimit?: number;\n  ptyAdapter: PtyAdapter.PtyAdapter[\"Service\"];\n  shellResolver?: () => string;\n  env?: NodeJS.ProcessEnv;\n  subprocessInspector?: TerminalSubprocessInspector;\n  subprocessPollIntervalMs?: number;\n  processKillGraceMs?: number;\n  maxRetainedInactiveSessions?: number;\n  registerTerminalProcesses?: (input: {\n    readonly threadId: string;\n    readonly terminalId: string;\n    readonly processIds: ReadonlyArray<number>;\n  }) => Effect.Effect<void>;\n  unregisterTerminal?: (input: {\n    readonly threadId: string;\n    readonly terminalId: string;\n  }) => Effect.Effect<void>;\n}\n\nexport const make = Effect.fn(\"TerminalManager.make\")(function* () {\n  const { terminalLogsDir } = yield* ServerConfig.ServerConfig;\n  const ptyAdapter = yield* PtyAdapter.PtyAdapter;\n  const portDiscovery = yield* PortScanner.PortDiscovery;\n  return yield* makeWithOptions({\n    logsDir: terminalLogsDir,\n    ptyAdapter,\n    registerTerminalProcesses: portDiscovery.registerTerminalProcesses,\n    unregisterTerminal: portDiscovery.unregisterTerminal,\n  });\n});\n\nexport const makeWithOptions = Effect.fn(\"TerminalManager.makeWithOptions\")(function* (\n  options: TerminalManagerOptions,\n) {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const context = yield* Effect.context<never>();\n  const runFork = Effect.runForkWith(context);\n\n  const logsDir = options.logsDir;\n  const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;\n  const platform = yield* HostProcessPlatform;\n  // Terminals must inherit the user's full environment (minus the blocklist\n  // applied in createTerminalSpawnEnv) — an allowlist here silently strips\n  // things like PSModulePath, DISPLAY, proxies, and toolchain variables.\n  // `options.env` is the test seam.\n  const baseEnv = options.env ?? process.env;\n  const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));\n  const processRunner = yield* ProcessRunner.ProcessRunner;\n  const subprocessInspector =\n    options.subprocessInspector ??\n    ((terminalPid) =>\n      defaultSubprocessInspectorForPlatform(platform)(terminalPid).pipe(\n        Effect.provideService(ProcessRunner.ProcessRunner, processRunner),\n      ));\n  const subprocessPollIntervalMs =\n    options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;\n  const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;\n  const maxRetainedInactiveSessions =\n    options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS;\n  const registerTerminalProcesses = options.registerTerminalProcesses ?? (() => Effect.void);\n  const unregisterTerminal = options.unregisterTerminal ?? (() => Effect.void);\n\n  yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);\n\n  const managerStateRef = yield* SynchronizedRef.make<TerminalManagerState>({\n    sessions: new Map(),\n    killFibers: new Map(),\n  });\n  const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());\n  const terminalEventListeners = new Set<(event: TerminalEvent) => Effect.Effect<void>>();\n  const workerScope = yield* Scope.make(\"sequential\");\n  yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void));\n\n  const publishEvent = (event: TerminalEvent) =>\n    Effect.gen(function* () {\n      for (const listener of terminalEventListeners) {\n        yield* listener(event).pipe(Effect.ignoreCause({ log: true }));\n      }\n    });\n\n  const historyPath = (threadId: string, terminalId: string) => {\n    const threadPart = toSafeThreadId(threadId);\n    if (terminalId === DEFAULT_TERMINAL_ID) {\n      return path.join(logsDir, `${threadPart}.log`);\n    }\n    return path.join(logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`);\n  };\n\n  const legacyHistoryPath = (threadId: string) =>\n    path.join(logsDir, `${legacySafeThreadId(threadId)}.log`);\n\n  const readManagerState = SynchronizedRef.get(managerStateRef);\n\n  const modifyManagerState = <A>(\n    f: (state: TerminalManagerState) => readonly [A, TerminalManagerState],\n  ) => SynchronizedRef.modify(managerStateRef, f);\n\n  const getThreadSemaphore = (threadId: string) =>\n    SynchronizedRef.modifyEffect(threadLocksRef, (current) => {\n      const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(\n        current.get(threadId),\n      );\n      return Option.match(existing, {\n        onNone: () =>\n          Semaphore.make(1).pipe(\n            Effect.map((semaphore) => {\n              const next = new Map(current);\n              next.set(threadId, semaphore);\n              return [semaphore, next] as const;\n            }),\n          ),\n        onSome: (semaphore) => Effect.succeed([semaphore, current] as const),\n      });\n    });\n\n  const withThreadLock = <A, E, R>(\n    threadId: string,\n    effect: Effect.Effect<A, E, R>,\n  ): Effect.Effect<A, E, R> =>\n    Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));\n\n  const clearKillFiber = Effect.fn(\"terminal.clearKillFiber\")(function* (\n    process: PtyAdapter.PtyProcess | null,\n  ) {\n    if (!process) return;\n    const fiber: Option.Option<Fiber.Fiber<void, never>> = yield* modifyManagerState<\n      Option.Option<Fiber.Fiber<void, never>>\n    >((state) => {\n      const existing: Option.Option<Fiber.Fiber<void, never>> = Option.fromNullishOr(\n        state.killFibers.get(process),\n      );\n      if (Option.isNone(existing)) {\n        return [Option.none<Fiber.Fiber<void, never>>(), state] as const;\n      }\n      const killFibers = new Map(state.killFibers);\n      killFibers.delete(process);\n      return [existing, { ...state, killFibers }] as const;\n    });\n    if (Option.isSome(fiber)) {\n      yield* Fiber.interrupt(fiber.value).pipe(Effect.ignore);\n    }\n  });\n\n  const registerKillFiber = Effect.fn(\"terminal.registerKillFiber\")(function* (\n    process: PtyAdapter.PtyProcess,\n    fiber: Fiber.Fiber<void, never>,\n  ) {\n    yield* modifyManagerState((state) => {\n      const killFibers = new Map(state.killFibers);\n      killFibers.set(process, fiber);\n      return [undefined, { ...state, killFibers }] as const;\n    });\n  });\n\n  const runKillEscalation = Effect.fn(\"terminal.runKillEscalation\")(function* (\n    process: PtyAdapter.PtyProcess,\n    threadId: string,\n    terminalId: string,\n  ) {\n    const terminated = yield* Effect.try({\n      try: () => process.kill(\"SIGTERM\"),\n      catch: (cause) =>\n        new TerminalProcessSignalError({\n          cause,\n          signal: \"SIGTERM\",\n          terminalPid: process.pid,\n        }),\n    }).pipe(\n      Effect.as(true),\n      Effect.catch((error) =>\n        Effect.logWarning(\"failed to kill terminal process\", {\n          threadId,\n          terminalId,\n          signal: \"SIGTERM\",\n          cause: error,\n        }).pipe(Effect.as(false)),\n      ),\n    );\n    if (!terminated) {\n      return;\n    }\n\n    yield* Effect.sleep(processKillGraceMs);\n\n    yield* Effect.try({\n      try: () => process.kill(\"SIGKILL\"),\n      catch: (cause) =>\n        new TerminalProcessSignalError({\n          cause,\n          signal: \"SIGKILL\",\n          terminalPid: process.pid,\n        }),\n    }).pipe(\n      Effect.catch((error) =>\n        Effect.logWarning(\"failed to force-kill terminal process\", {\n          threadId,\n          terminalId,\n          signal: \"SIGKILL\",\n          cause: error,\n        }),\n      ),\n    );\n  });\n\n  const startKillEscalation = Effect.fn(\"terminal.startKillEscalation\")(function* (\n    process: PtyAdapter.PtyProcess,\n    threadId: string,\n    terminalId: string,\n  ) {\n    const fiber = yield* runKillEscalation(process, threadId, terminalId).pipe(\n      Effect.ensuring(\n        modifyManagerState((state) => {\n          if (!state.killFibers.has(process)) {\n            return [undefined, state] as const;\n          }\n          const killFibers = new Map(state.killFibers);\n          killFibers.delete(process);\n          return [undefined, { ...state, killFibers }] as const;\n        }),\n      ),\n      Effect.forkIn(workerScope),\n    );\n\n    yield* registerKillFiber(process, fiber);\n  });\n\n  const persistWorker = yield* makeKeyedCoalescingWorker<\n    string,\n    PersistHistoryRequest,\n    never,\n    never\n  >({\n    merge: (current, next) => ({\n      history: next.history,\n      immediate: current.immediate || next.immediate,\n    }),\n    process: Effect.fn(\"terminal.persistHistoryWorker\")(function* (sessionKey, request) {\n      if (!request.immediate) {\n        yield* Effect.sleep(DEFAULT_PERSIST_DEBOUNCE_MS);\n      }\n\n      const [threadId, terminalId] = sessionKey.split(\"\\u0000\");\n      if (!threadId || !terminalId) {\n        return;\n      }\n\n      yield* fileSystem.writeFileString(historyPath(threadId, terminalId), request.history).pipe(\n        Effect.catch((error) =>\n          Effect.logWarning(\"failed to persist terminal history\", {\n            threadId,\n            terminalId,\n            error,\n          }),\n        ),\n      );\n    }),\n  });\n\n  const queuePersist = Effect.fn(\"terminal.queuePersist\")(function* (\n    threadId: string,\n    terminalId: string,\n    history: string,\n  ) {\n    yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), {\n      history,\n      immediate: false,\n    });\n  });\n\n  const flushPersist = Effect.fn(\"terminal.flushPersist\")(function* (\n    threadId: string,\n    terminalId: string,\n  ) {\n    yield* persistWorker.drainKey(toSessionKey(threadId, terminalId));\n  });\n\n  const persistHistory = Effect.fn(\"terminal.persistHistory\")(function* (\n    threadId: string,\n    terminalId: string,\n    history: string,\n  ) {\n    yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), {\n      history,\n      immediate: true,\n    });\n    yield* flushPersist(threadId, terminalId);\n  });\n\n  const readHistory = Effect.fn(\"terminal.readHistory\")(function* (\n    threadId: string,\n    terminalId: string,\n  ) {\n    const nextPath = historyPath(threadId, terminalId);\n    if (\n      yield* fileSystem\n        .exists(nextPath)\n        .pipe(\n          Effect.mapError(\n            (cause) => new TerminalHistoryError({ operation: \"read\", threadId, terminalId, cause }),\n          ),\n        )\n    ) {\n      const raw = yield* fileSystem\n        .readFileString(nextPath)\n        .pipe(\n          Effect.mapError(\n            (cause) => new TerminalHistoryError({ operation: \"read\", threadId, terminalId, cause }),\n          ),\n        );\n      const capped = capHistory(raw, historyLineLimit);\n      if (capped !== raw) {\n        yield* fileSystem\n          .writeFileString(nextPath, capped)\n          .pipe(\n            Effect.mapError(\n              (cause) =>\n                new TerminalHistoryError({ operation: \"truncate\", threadId, terminalId, cause }),\n            ),\n          );\n      }\n      return capped;\n    }\n\n    if (terminalId !== DEFAULT_TERMINAL_ID) {\n      return \"\";\n    }\n\n    const legacyPath = legacyHistoryPath(threadId);\n    if (\n      !(yield* fileSystem\n        .exists(legacyPath)\n        .pipe(\n          Effect.mapError(\n            (cause) =>\n              new TerminalHistoryError({ operation: \"migrate\", threadId, terminalId, cause }),\n          ),\n        ))\n    ) {\n      return \"\";\n    }\n\n    const raw = yield* fileSystem\n      .readFileString(legacyPath)\n      .pipe(\n        Effect.mapError(\n          (cause) =>\n            new TerminalHistoryError({ operation: \"migrate\", threadId, terminalId, cause }),\n        ),\n      );\n    const capped = capHistory(raw, historyLineLimit);\n    yield* fileSystem\n      .writeFileString(nextPath, capped)\n      .pipe(\n        Effect.mapError(\n          (cause) =>\n            new TerminalHistoryError({ operation: \"migrate\", threadId, terminalId, cause }),\n        ),\n      );\n    yield* fileSystem.remove(legacyPath, { force: true }).pipe(\n      Effect.catch((cleanupError) =>\n        Effect.logWarning(\"failed to remove legacy terminal history\", {\n          threadId,\n          error: cleanupError,\n        }),\n      ),\n    );\n    return capped;\n  });\n\n  const deleteHistory = Effect.fn(\"terminal.deleteHistory\")(function* (\n    threadId: string,\n    terminalId: string,\n  ) {\n    yield* fileSystem.remove(historyPath(threadId, terminalId), { force: true }).pipe(\n      Effect.catch((error) =>\n        Effect.logWarning(\"failed to delete terminal history\", {\n          threadId,\n          terminalId,\n          error,\n        }),\n      ),\n    );\n    if (terminalId === DEFAULT_TERMINAL_ID) {\n      yield* fileSystem.remove(legacyHistoryPath(threadId), { force: true }).pipe(\n        Effect.catch((error) =>\n          Effect.logWarning(\"failed to delete terminal history\", {\n            threadId,\n            terminalId,\n            error,\n          }),\n        ),\n      );\n    }\n  });\n\n  const deleteAllHistoryForThread = Effect.fn(\"terminal.deleteAllHistoryForThread\")(function* (\n    threadId: string,\n  ) {\n    const threadPrefix = `${toSafeThreadId(threadId)}_`;\n    const entries = yield* fileSystem\n      .readDirectory(logsDir, { recursive: false })\n      .pipe(Effect.orElseSucceed(() => [] as Array<string>));\n    yield* Effect.forEach(\n      entries.filter(\n        (name) =>\n          name === `${toSafeThreadId(threadId)}.log` ||\n          name === `${legacySafeThreadId(threadId)}.log` ||\n          name.startsWith(threadPrefix),\n      ),\n      (name) =>\n        fileSystem.remove(path.join(logsDir, name), { force: true }).pipe(\n          Effect.catch((error) =>\n            Effect.logWarning(\"failed to delete terminal histories for thread\", {\n              threadId,\n              error,\n            }),\n          ),\n        ),\n      { discard: true },\n    );\n  });\n\n  const assertValidCwd = Effect.fn(\"terminal.assertValidCwd\")(function* (cwd: string) {\n    const stats = yield* fileSystem.stat(cwd).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          cause.reason._tag === \"NotFound\"\n            ? new TerminalCwdNotFoundError({ cwd })\n            : new TerminalCwdStatError({ cwd, cause }),\n      }),\n    );\n    if (stats.type !== \"Directory\") {\n      return yield* new TerminalCwdNotDirectoryError({ cwd });\n    }\n  });\n\n  const getSession = Effect.fn(\"terminal.getSession\")(function* (\n    threadId: string,\n    terminalId: string,\n  ): Effect.fn.Return<Option.Option<TerminalSessionState>> {\n    return yield* Effect.map(readManagerState, (state) =>\n      Option.fromNullishOr(state.sessions.get(toSessionKey(threadId, terminalId))),\n    );\n  });\n\n  const requireSession = Effect.fn(\"terminal.requireSession\")(function* (\n    threadId: string,\n    terminalId: string,\n  ): Effect.fn.Return<TerminalSessionState, TerminalSessionLookupError> {\n    return yield* Effect.flatMap(getSession(threadId, terminalId), (session) =>\n      Option.match(session, {\n        onNone: () =>\n          Effect.fail(\n            new TerminalSessionLookupError({\n              threadId,\n              terminalId,\n            }),\n          ),\n        onSome: Effect.succeed,\n      }),\n    );\n  });\n\n  const sessionsForThread = Effect.fn(\"terminal.sessionsForThread\")(function* (threadId: string) {\n    return yield* readManagerState.pipe(\n      Effect.map((state) =>\n        [...state.sessions.values()].filter((session) => session.threadId === threadId),\n      ),\n    );\n  });\n\n  const evictInactiveSessionsIfNeeded = Effect.fn(\"terminal.evictInactiveSessionsIfNeeded\")(\n    function* () {\n      yield* modifyManagerState((state) => {\n        const inactiveSessions = [...state.sessions.values()].filter(\n          (session) => session.status !== \"running\",\n        );\n        if (inactiveSessions.length <= maxRetainedInactiveSessions) {\n          return [undefined, state] as const;\n        }\n\n        inactiveSessions.sort(\n          (left, right) =>\n            left.updatedAt.localeCompare(right.updatedAt) ||\n            left.threadId.localeCompare(right.threadId) ||\n            left.terminalId.localeCompare(right.terminalId),\n        );\n\n        const sessions = new Map(state.sessions);\n\n        const toEvict = inactiveSessions.length - maxRetainedInactiveSessions;\n        for (const session of inactiveSessions.slice(0, toEvict)) {\n          const key = toSessionKey(session.threadId, session.terminalId);\n          sessions.delete(key);\n        }\n\n        return [undefined, { ...state, sessions }] as const;\n      });\n    },\n  );\n\n  const drainProcessEvents = Effect.fn(\"terminal.drainProcessEvents\")(function* (\n    session: TerminalSessionState,\n    expectedPid: number,\n  ) {\n    while (true) {\n      const action: DrainProcessEventAction = yield* Effect.sync(() => {\n        if (session.pid !== expectedPid || !session.process || session.status !== \"running\") {\n          session.pendingProcessEvents = [];\n          session.pendingProcessEventIndex = 0;\n          session.processEventDrainRunning = false;\n          return { type: \"idle\" } as const;\n        }\n\n        const nextEvent = session.pendingProcessEvents[session.pendingProcessEventIndex];\n        if (!nextEvent) {\n          session.pendingProcessEvents = [];\n          session.pendingProcessEventIndex = 0;\n          session.processEventDrainRunning = false;\n          return { type: \"idle\" } as const;\n        }\n\n        session.pendingProcessEventIndex += 1;\n        if (session.pendingProcessEventIndex >= session.pendingProcessEvents.length) {\n          session.pendingProcessEvents = [];\n          session.pendingProcessEventIndex = 0;\n        }\n\n        if (nextEvent.type === \"output\") {\n          const sanitized = sanitizeTerminalHistoryChunk(\n            session.pendingHistoryControlSequence,\n            nextEvent.data,\n          );\n          session.pendingHistoryControlSequence = sanitized.pendingControlSequence;\n          if (sanitized.visibleText.length > 0) {\n            session.history = capHistory(\n              `${session.history}${sanitized.visibleText}`,\n              historyLineLimit,\n            );\n          }\n          const eventStamp = advanceEventSequence(session);\n\n          return {\n            type: \"output\",\n            threadId: session.threadId,\n            terminalId: session.terminalId,\n            sequence: eventStamp.sequence,\n            history: sanitized.visibleText.length > 0 ? session.history : null,\n            data: nextEvent.data,\n          } as const;\n        }\n\n        const process = session.process;\n        cleanupProcessHandles(session);\n        session.process = null;\n        session.pid = null;\n        session.hasRunningSubprocess = false;\n        session.childCommandLabel = null;\n        session.status = \"exited\";\n        session.pendingHistoryControlSequence = \"\";\n        session.pendingProcessEvents = [];\n        session.pendingProcessEventIndex = 0;\n        session.processEventDrainRunning = false;\n        session.exitCode = Number.isInteger(nextEvent.event.exitCode)\n          ? nextEvent.event.exitCode\n          : null;\n        session.exitSignal = Number.isInteger(nextEvent.event.signal)\n          ? nextEvent.event.signal\n          : null;\n        const eventStamp = advanceEventSequence(session);\n\n        return {\n          type: \"exit\",\n          process,\n          threadId: session.threadId,\n          terminalId: session.terminalId,\n          sequence: eventStamp.sequence,\n          exitCode: session.exitCode,\n          exitSignal: session.exitSignal,\n        } as const;\n      });\n\n      if (action.type === \"idle\") {\n        return;\n      }\n\n      if (action.type === \"output\") {\n        if (action.history !== null) {\n          yield* queuePersist(action.threadId, action.terminalId, action.history);\n        }\n\n        yield* publishEvent({\n          type: \"output\",\n          threadId: action.threadId,\n          terminalId: action.terminalId,\n          sequence: action.sequence,\n          data: action.data,\n        });\n        continue;\n      }\n\n      yield* clearKillFiber(action.process);\n      yield* unregisterTerminal({\n        threadId: action.threadId,\n        terminalId: action.terminalId,\n      });\n      yield* publishEvent({\n        type: \"exited\",\n        threadId: action.threadId,\n        terminalId: action.terminalId,\n        sequence: action.sequence,\n        exitCode: action.exitCode,\n        exitSignal: action.exitSignal,\n      });\n      yield* evictInactiveSessionsIfNeeded();\n      return;\n    }\n  });\n\n  const stopProcess = Effect.fn(\"terminal.stopProcess\")(function* (session: TerminalSessionState) {\n    const process = session.process;\n    if (!process) return;\n\n    const updatedAt = yield* nowIso;\n    yield* modifyManagerState((state) => {\n      cleanupProcessHandles(session);\n      session.process = null;\n      session.pid = null;\n      session.hasRunningSubprocess = false;\n      session.childCommandLabel = null;\n      session.status = \"exited\";\n      session.pendingHistoryControlSequence = \"\";\n      session.pendingProcessEvents = [];\n      session.pendingProcessEventIndex = 0;\n      session.processEventDrainRunning = false;\n      session.updatedAt = updatedAt;\n      return [undefined, state] as const;\n    });\n\n    yield* clearKillFiber(process);\n    yield* unregisterTerminal({\n      threadId: session.threadId,\n      terminalId: session.terminalId,\n    });\n    yield* startKillEscalation(process, session.threadId, session.terminalId);\n    yield* evictInactiveSessionsIfNeeded();\n  });\n\n  const trySpawn = Effect.fn(\"terminal.trySpawn\")(function* (\n    shellCandidates: ReadonlyArray<ShellCandidate>,\n    spawnEnv: NodeJS.ProcessEnv,\n    session: TerminalSessionState,\n    index = 0,\n    lastError: PtyAdapter.PtySpawnError | null = null,\n  ): Effect.fn.Return<\n    { process: PtyAdapter.PtyProcess; shellLabel: string },\n    PtyAdapter.PtySpawnError\n  > {\n    if (index >= shellCandidates.length) {\n      return yield* new PtyAdapter.PtySpawnError({\n        adapter: \"terminal-manager\",\n        attemptedShells: shellCandidates.map((candidate) => formatShellCandidate(candidate)),\n        ...(lastError ? { cause: lastError } : {}),\n      });\n    }\n\n    const candidate = shellCandidates[index];\n    if (!candidate) {\n      return yield* (\n        lastError ??\n          new PtyAdapter.PtySpawnError({\n            adapter: \"terminal-manager\",\n            attemptedShells: [],\n          })\n      );\n    }\n\n    const attempt = yield* Effect.result(\n      options.ptyAdapter.spawn({\n        shell: candidate.shell,\n        ...(candidate.args ? { args: candidate.args } : {}),\n        cwd: session.cwd,\n        cols: session.cols,\n        rows: session.rows,\n        env: spawnEnv,\n      }),\n    );\n\n    if (attempt._tag === \"Success\") {\n      return {\n        process: attempt.success,\n        shellLabel: formatShellCandidate(candidate),\n      };\n    }\n\n    const spawnError = attempt.failure;\n    if (!isRetryableShellSpawnError(spawnError)) {\n      return yield* spawnError;\n    }\n\n    return yield* trySpawn(shellCandidates, spawnEnv, session, index + 1, spawnError);\n  });\n\n  const startSession = Effect.fn(\"terminal.startSession\")(function* (\n    session: TerminalSessionState,\n    input: TerminalStartInput,\n    eventType: \"started\" | \"restarted\",\n  ) {\n    yield* stopProcess(session);\n    yield* Effect.annotateCurrentSpan({\n      \"terminal.thread_id\": session.threadId,\n      \"terminal.id\": session.terminalId,\n      \"terminal.event_type\": eventType,\n      \"terminal.cwd\": input.cwd,\n    });\n\n    const startingAt = yield* nowIso;\n    yield* modifyManagerState((state) => {\n      session.status = \"starting\";\n      session.cwd = input.cwd;\n      session.worktreePath = input.worktreePath ?? null;\n      session.cols = input.cols;\n      session.rows = input.rows;\n      session.exitCode = null;\n      session.exitSignal = null;\n      session.hasRunningSubprocess = false;\n      session.childCommandLabel = null;\n      session.pendingProcessEvents = [];\n      session.pendingProcessEventIndex = 0;\n      session.processEventDrainRunning = false;\n      session.updatedAt = startingAt;\n      return [undefined, state] as const;\n    });\n\n    let ptyProcess: PtyAdapter.PtyProcess | null = null;\n    let startedShell: string | null = null;\n\n    const startResult = yield* Effect.result(\n      increment(terminalSessionsTotal, { lifecycle: eventType }).pipe(\n        Effect.andThen(\n          Effect.gen(function* () {\n            const shellCandidates = resolveShellCandidates(shellResolver, platform, baseEnv);\n            const terminalEnv = createTerminalSpawnEnv(baseEnv, session.runtimeEnv);\n            const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session);\n            ptyProcess = spawnResult.process;\n            startedShell = spawnResult.shellLabel;\n\n            const processPid = ptyProcess.pid;\n            const unsubscribeData = ptyProcess.onData((data) => {\n              if (!enqueueProcessEvent(session, processPid, { type: \"output\", data })) {\n                return;\n              }\n              runFork(drainProcessEvents(session, processPid));\n            });\n            const unsubscribeExit = ptyProcess.onExit((event) => {\n              if (!enqueueProcessEvent(session, processPid, { type: \"exit\", event })) {\n                return;\n              }\n              runFork(drainProcessEvents(session, processPid));\n            });\n\n            let eventStamp: ReturnType<typeof advanceEventSequence> = {\n              updatedAt: session.updatedAt,\n              sequence: session.eventSequence,\n            };\n            yield* modifyManagerState((state) => {\n              session.process = ptyProcess;\n              session.pid = processPid;\n              session.status = \"running\";\n              session.unsubscribeData = unsubscribeData;\n              session.unsubscribeExit = unsubscribeExit;\n              eventStamp = advanceEventSequence(session);\n              return [undefined, state] as const;\n            });\n\n            yield* publishEvent({\n              type: eventType,\n              threadId: session.threadId,\n              terminalId: session.terminalId,\n              sequence: eventStamp.sequence,\n              snapshot: snapshot(session),\n            });\n          }),\n        ),\n      ),\n    );\n\n    if (startResult._tag === \"Success\") {\n      return;\n    }\n\n    {\n      const error = startResult.failure;\n      if (ptyProcess) {\n        yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId);\n      }\n\n      yield* modifyManagerState((state) => {\n        cleanupProcessHandles(session);\n        session.status = \"error\";\n        session.pid = null;\n        session.process = null;\n        session.hasRunningSubprocess = false;\n        session.childCommandLabel = null;\n        session.pendingProcessEvents = [];\n        session.pendingProcessEventIndex = 0;\n        session.processEventDrainRunning = false;\n        advanceEventSequence(session);\n        return [undefined, state] as const;\n      });\n      yield* unregisterTerminal({\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n      });\n\n      yield* evictInactiveSessionsIfNeeded();\n\n      const message = error.message;\n      yield* publishEvent({\n        type: \"error\",\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n        sequence: session.eventSequence,\n        message,\n      });\n      yield* Effect.logError(\"failed to start terminal\", {\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n        cause: error,\n        ...(startedShell ? { shell: startedShell } : {}),\n      });\n    }\n  });\n\n  const closeSession = Effect.fn(\"terminal.closeSession\")(function* (\n    threadId: string,\n    terminalId: string,\n    deleteHistoryOnClose: boolean,\n  ) {\n    const key = toSessionKey(threadId, terminalId);\n    const session = yield* getSession(threadId, terminalId);\n    const closedEventSequence = Option.isSome(session) ? session.value.eventSequence + 1 : 0;\n\n    if (Option.isSome(session)) {\n      yield* stopProcess(session.value);\n      yield* unregisterTerminal({ threadId, terminalId });\n      yield* persistHistory(threadId, terminalId, session.value.history);\n    }\n\n    yield* flushPersist(threadId, terminalId);\n\n    const removed = yield* modifyManagerState((state) => {\n      if (!state.sessions.has(key)) {\n        return [false, state] as const;\n      }\n      const sessions = new Map(state.sessions);\n      sessions.delete(key);\n      return [true, { ...state, sessions }] as const;\n    });\n\n    if (removed) {\n      yield* publishEvent({\n        type: \"closed\",\n        threadId,\n        terminalId,\n        sequence: closedEventSequence,\n      });\n    }\n\n    if (deleteHistoryOnClose) {\n      yield* deleteHistory(threadId, terminalId);\n    }\n  });\n\n  const pollSubprocessActivity = Effect.fn(\"terminal.pollSubprocessActivity\")(function* () {\n    const state = yield* readManagerState;\n    const runningSessions = [...state.sessions.values()].filter(\n      (session): session is TerminalSessionState & { pid: number } =>\n        session.status === \"running\" && Number.isInteger(session.pid),\n    );\n\n    if (runningSessions.length === 0) {\n      return;\n    }\n\n    const checkSubprocessActivity = Effect.fn(\"terminal.checkSubprocessActivity\")(function* (\n      session: TerminalSessionState & { pid: number },\n    ) {\n      const terminalPid = session.pid;\n      const inspectResult = yield* subprocessInspector(terminalPid).pipe(\n        Effect.map(Option.some),\n        Effect.catch((reason) =>\n          Effect.logWarning(\"failed to check terminal subprocess activity\", {\n            threadId: session.threadId,\n            terminalId: session.terminalId,\n            terminalPid,\n            reason,\n          }).pipe(Effect.as(Option.none<TerminalSubprocessInspectResult>())),\n        ),\n      );\n\n      if (Option.isNone(inspectResult)) {\n        return;\n      }\n\n      const next = inspectResult.value;\n      yield* registerTerminalProcesses({\n        threadId: session.threadId,\n        terminalId: session.terminalId,\n        processIds: next.processIds,\n      });\n      const nextChildLabel = next.hasRunningSubprocess ? next.childCommand : null;\n      const event = yield* modifyManagerState((state) => {\n        const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(\n          state.sessions.get(toSessionKey(session.threadId, session.terminalId)),\n        );\n        if (\n          Option.isNone(liveSession) ||\n          liveSession.value.status !== \"running\" ||\n          liveSession.value.pid !== terminalPid ||\n          (liveSession.value.hasRunningSubprocess === next.hasRunningSubprocess &&\n            liveSession.value.childCommandLabel === nextChildLabel)\n        ) {\n          return [Option.none(), state] as const;\n        }\n\n        liveSession.value.hasRunningSubprocess = next.hasRunningSubprocess;\n        liveSession.value.childCommandLabel = nextChildLabel;\n        const eventStamp = advanceEventSequence(liveSession.value);\n\n        return [\n          Option.some({\n            type: \"activity\" as const,\n            threadId: liveSession.value.threadId,\n            terminalId: liveSession.value.terminalId,\n            sequence: eventStamp.sequence,\n            hasRunningSubprocess: next.hasRunningSubprocess,\n            label: terminalWireLabel(liveSession.value),\n          }),\n          state,\n        ] as const;\n      });\n\n      if (Option.isSome(event)) {\n        yield* publishEvent(event.value);\n      }\n    });\n\n    yield* Effect.forEach(runningSessions, checkSubprocessActivity, {\n      concurrency: \"unbounded\",\n      discard: true,\n    });\n  });\n\n  const hasRunningSessions = readManagerState.pipe(\n    Effect.map((state) =>\n      [...state.sessions.values()].some((session) => session.status === \"running\"),\n    ),\n  );\n\n  yield* Effect.forever(\n    hasRunningSessions.pipe(\n      Effect.flatMap((active) =>\n        active\n          ? pollSubprocessActivity().pipe(\n              Effect.flatMap(() => Effect.sleep(subprocessPollIntervalMs)),\n            )\n          : Effect.sleep(subprocessPollIntervalMs),\n      ),\n    ),\n  ).pipe(Effect.forkIn(workerScope));\n\n  yield* Effect.addFinalizer(() =>\n    Effect.gen(function* () {\n      const sessions = yield* modifyManagerState(\n        (state) =>\n          [\n            [...state.sessions.values()],\n            {\n              ...state,\n              sessions: new Map(),\n            },\n          ] as const,\n      );\n\n      const cleanupSession = Effect.fn(\"terminal.cleanupSession\")(function* (\n        session: TerminalSessionState,\n      ) {\n        cleanupProcessHandles(session);\n        if (!session.process) return;\n        yield* clearKillFiber(session.process);\n        yield* runKillEscalation(session.process, session.threadId, session.terminalId);\n      });\n\n      yield* Effect.forEach(sessions, cleanupSession, {\n        concurrency: \"unbounded\",\n        discard: true,\n      });\n    }).pipe(Effect.ignoreCause({ log: true })),\n  );\n\n  const openLocked = Effect.fn(\"terminal.openLocked\")(function* (input: TerminalOpenInput) {\n    const terminalId = input.terminalId;\n    yield* assertValidCwd(input.cwd);\n\n    const sessionKey = toSessionKey(input.threadId, terminalId);\n    const existing = yield* getSession(input.threadId, terminalId);\n    if (Option.isNone(existing)) {\n      yield* flushPersist(input.threadId, terminalId);\n      const history = yield* readHistory(input.threadId, terminalId);\n      const cols = input.cols ?? DEFAULT_OPEN_COLS;\n      const rows = input.rows ?? DEFAULT_OPEN_ROWS;\n      const session: TerminalSessionState = {\n        threadId: input.threadId,\n        terminalId,\n        cwd: input.cwd,\n        worktreePath: input.worktreePath ?? null,\n        status: \"starting\",\n        pid: null,\n        history,\n        pendingHistoryControlSequence: \"\",\n        pendingProcessEvents: [],\n        pendingProcessEventIndex: 0,\n        processEventDrainRunning: false,\n        exitCode: null,\n        exitSignal: null,\n        updatedAt: yield* nowIso,\n        eventSequence: 0,\n        cols,\n        rows,\n        process: null,\n        unsubscribeData: null,\n        unsubscribeExit: null,\n        hasRunningSubprocess: false,\n        childCommandLabel: null,\n        runtimeEnv: normalizedRuntimeEnv(input.env),\n      };\n\n      const createdSession = session;\n      yield* modifyManagerState((state) => {\n        const sessions = new Map(state.sessions);\n        sessions.set(sessionKey, createdSession);\n        return [undefined, { ...state, sessions }] as const;\n      });\n\n      yield* evictInactiveSessionsIfNeeded();\n      yield* startSession(\n        session,\n        {\n          threadId: input.threadId,\n          terminalId,\n          cwd: input.cwd,\n          ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),\n          cols,\n          rows,\n          ...(input.env ? { env: input.env } : {}),\n        },\n        \"started\",\n      );\n      return snapshot(session);\n    }\n\n    const liveSession = existing.value;\n    const nextRuntimeEnv = normalizedRuntimeEnv(input.env);\n    const currentRuntimeEnv = liveSession.runtimeEnv;\n    const targetCols = input.cols ?? liveSession.cols;\n    const targetRows = input.rows ?? liveSession.rows;\n    const runtimeEnvChanged = !Equal.equals(currentRuntimeEnv, nextRuntimeEnv);\n    const nextWorktreePath =\n      input.worktreePath !== undefined ? (input.worktreePath ?? null) : liveSession.worktreePath;\n    const launchContextChanged =\n      liveSession.cwd !== input.cwd ||\n      runtimeEnvChanged ||\n      liveSession.worktreePath !== nextWorktreePath;\n\n    if (launchContextChanged) {\n      yield* stopProcess(liveSession);\n      liveSession.cwd = input.cwd;\n      liveSession.worktreePath = nextWorktreePath;\n      liveSession.runtimeEnv = nextRuntimeEnv;\n      liveSession.history = \"\";\n      liveSession.pendingHistoryControlSequence = \"\";\n      liveSession.pendingProcessEvents = [];\n      liveSession.pendingProcessEventIndex = 0;\n      liveSession.processEventDrainRunning = false;\n      yield* persistHistory(liveSession.threadId, liveSession.terminalId, liveSession.history);\n    } else if (liveSession.status === \"exited\" || liveSession.status === \"error\") {\n      liveSession.runtimeEnv = nextRuntimeEnv;\n      liveSession.worktreePath = nextWorktreePath;\n      liveSession.history = \"\";\n      liveSession.pendingHistoryControlSequence = \"\";\n      liveSession.pendingProcessEvents = [];\n      liveSession.pendingProcessEventIndex = 0;\n      liveSession.processEventDrainRunning = false;\n      yield* persistHistory(liveSession.threadId, liveSession.terminalId, liveSession.history);\n    }\n\n    if (!liveSession.process) {\n      yield* startSession(\n        liveSession,\n        {\n          threadId: input.threadId,\n          terminalId,\n          cwd: input.cwd,\n          worktreePath: liveSession.worktreePath,\n          cols: targetCols,\n          rows: targetRows,\n          ...(input.env ? { env: input.env } : {}),\n        },\n        \"started\",\n      );\n      return snapshot(liveSession);\n    }\n\n    if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) {\n      yield* resizePtyProcess(liveSession, liveSession.process, targetCols, targetRows);\n      liveSession.cols = targetCols;\n      liveSession.rows = targetRows;\n      liveSession.updatedAt = yield* nowIso;\n    }\n\n    return snapshot(liveSession);\n  });\n\n  const open: TerminalManager[\"Service\"][\"open\"] = (input) =>\n    withThreadLock(input.threadId, openLocked(input));\n\n  const openOrAttachForStream = (input: TerminalAttachInput) =>\n    withThreadLock(\n      input.threadId,\n      Effect.gen(function* () {\n        const terminalId = input.terminalId;\n        const existing = yield* getSession(input.threadId, terminalId);\n\n        if (Option.isNone(existing)) {\n          if (!input.cwd) {\n            return yield* new TerminalSessionLookupError({\n              threadId: input.threadId,\n              terminalId,\n            });\n          }\n\n          return yield* openLocked({\n            ...input,\n            terminalId,\n            cwd: input.cwd,\n          });\n        }\n\n        const session = existing.value;\n        const targetCols = input.cols ?? session.cols;\n        const targetRows = input.rows ?? session.rows;\n\n        if (!session.process && input.cwd && input.restartIfNotRunning === true) {\n          return yield* openLocked({\n            ...input,\n            terminalId,\n            cwd: input.cwd,\n          });\n        }\n\n        if (\n          session.process &&\n          session.status === \"running\" &&\n          (session.cols !== targetCols || session.rows !== targetRows)\n        ) {\n          const process = session.process;\n          yield* resizePtyProcess(session, process, targetCols, targetRows);\n          session.cols = targetCols;\n          session.rows = targetRows;\n          session.updatedAt = yield* nowIso;\n        }\n\n        return snapshot(session);\n      }),\n    );\n\n  const readAllTerminalMetadata = () =>\n    readManagerState.pipe(\n      Effect.map((state) =>\n        [...state.sessions.values()]\n          .map(summary)\n          .sort(\n            (left, right) =>\n              right.updatedAt.localeCompare(left.updatedAt) ||\n              left.threadId.localeCompare(right.threadId) ||\n              left.terminalId.localeCompare(right.terminalId),\n          ),\n      ),\n    );\n\n  const readTerminalMetadata = (input: {\n    readonly threadId: string;\n    readonly terminalId: string;\n  }) =>\n    getSession(input.threadId, input.terminalId).pipe(\n      Effect.map((session) => (Option.isSome(session) ? summary(session.value) : null)),\n    );\n\n  const subscribe: TerminalManager[\"Service\"][\"subscribe\"] = (listener) =>\n    Effect.sync(() => {\n      terminalEventListeners.add(listener);\n      return () => {\n        terminalEventListeners.delete(listener);\n      };\n    });\n\n  const attachStream: TerminalManager[\"Service\"][\"attachStream\"] = (input, listener) => {\n    let unsubscribe: (() => void) | null = null;\n\n    return Effect.gen(function* () {\n      const bufferedEvents: TerminalEvent[] = [];\n      let deliverLive = false;\n\n      unsubscribe = yield* subscribe((event) => {\n        if (event.threadId !== input.threadId || event.terminalId !== input.terminalId) {\n          return Effect.void;\n        }\n\n        if (!deliverLive) {\n          bufferedEvents.push(event);\n          return Effect.void;\n        }\n\n        const attachEvent = terminalEventToAttachEvent(event);\n        return attachEvent ? listener(attachEvent) : Effect.void;\n      });\n\n      const initialSnapshot = yield* openOrAttachForStream(input);\n\n      yield* listener({\n        type: \"snapshot\",\n        snapshot: initialSnapshot,\n      });\n\n      for (const event of bufferedEvents) {\n        if (isDuplicateAttachSnapshotEvent(event, initialSnapshot)) {\n          continue;\n        }\n\n        const attachEvent = terminalEventToAttachEvent(event);\n        if (attachEvent) {\n          yield* listener(attachEvent);\n        }\n      }\n\n      deliverLive = true;\n      return () => {\n        unsubscribe?.();\n        unsubscribe = null;\n      };\n    }).pipe(\n      Effect.catchCause((cause) =>\n        Effect.flatMap(\n          Effect.sync(() => {\n            unsubscribe?.();\n            unsubscribe = null;\n          }),\n          () => Effect.failCause(cause),\n        ),\n      ),\n    );\n  };\n\n  const metadataEventFromTerminalEvent = (\n    event: TerminalEvent,\n  ): Effect.Effect<TerminalMetadataStreamEvent | null> => {\n    if (!shouldPublishTerminalMetadataEvent(event)) {\n      return Effect.succeed(null);\n    }\n\n    if (event.type === \"closed\") {\n      return Effect.succeed({\n        type: \"remove\" as const,\n        threadId: event.threadId,\n        terminalId: event.terminalId,\n      });\n    }\n\n    return readTerminalMetadata({\n      threadId: event.threadId,\n      terminalId: event.terminalId,\n    }).pipe(\n      Effect.map((terminal) =>\n        terminal\n          ? {\n              type: \"upsert\" as const,\n              terminal,\n            }\n          : null,\n      ),\n    );\n  };\n\n  const offerMetadataEvent = (\n    listener: (event: TerminalMetadataStreamEvent) => Effect.Effect<void>,\n    event: TerminalEvent,\n  ) =>\n    metadataEventFromTerminalEvent(event).pipe(\n      Effect.flatMap((metadataEvent) => (metadataEvent ? listener(metadataEvent) : Effect.void)),\n    );\n\n  const subscribeMetadata: TerminalManager[\"Service\"][\"subscribeMetadata\"] = (listener) => {\n    let unsubscribe: (() => void) | null = null;\n\n    return Effect.gen(function* () {\n      const bufferedEvents: TerminalEvent[] = [];\n      let deliverLive = false;\n\n      unsubscribe = yield* subscribe((event) => {\n        if (!deliverLive) {\n          bufferedEvents.push(event);\n          return Effect.void;\n        }\n\n        return offerMetadataEvent(listener, event);\n      });\n\n      const terminals = yield* readAllTerminalMetadata();\n      yield* listener({\n        type: \"snapshot\",\n        terminals,\n      });\n\n      for (const event of bufferedEvents) {\n        yield* offerMetadataEvent(listener, event);\n      }\n\n      deliverLive = true;\n      return () => {\n        unsubscribe?.();\n        unsubscribe = null;\n      };\n    }).pipe(\n      Effect.catchCause((cause) =>\n        Effect.flatMap(\n          Effect.sync(() => {\n            unsubscribe?.();\n            unsubscribe = null;\n          }),\n          () => Effect.failCause(cause),\n        ),\n      ),\n    );\n  };\n\n  const write: TerminalManager[\"Service\"][\"write\"] = Effect.fn(\"terminal.write\")(function* (input) {\n    const terminalId = input.terminalId;\n    const session = yield* requireSession(input.threadId, terminalId);\n    const process = session.process;\n    if (!process || session.status !== \"running\") {\n      if (session.status === \"exited\") return;\n      return yield* new TerminalNotRunningError({\n        threadId: input.threadId,\n        terminalId,\n      });\n    }\n    yield* Effect.try({\n      try: () => process.write(input.data),\n      catch: (cause) =>\n        new TerminalWriteError({\n          threadId: input.threadId,\n          terminalId,\n          terminalPid: process.pid,\n          cause,\n        }),\n    });\n  });\n\n  const resizeLocked = Effect.fn(\"terminal.resize\")(function* (input: TerminalResizeInput) {\n    const session = yield* getSession(input.threadId, input.terminalId);\n    // ResizeObserver traffic can already be in flight when the UI closes the session.\n    if (Option.isNone(session)) {\n      return;\n    }\n    const process = session.value.process;\n    if (!process || session.value.status !== \"running\") {\n      return;\n    }\n    yield* resizePtyProcess(session.value, process, input.cols, input.rows);\n    session.value.cols = input.cols;\n    session.value.rows = input.rows;\n    session.value.updatedAt = yield* nowIso;\n  });\n\n  const resize: TerminalManager[\"Service\"][\"resize\"] = (input) =>\n    withThreadLock(input.threadId, resizeLocked(input));\n\n  const clear: TerminalManager[\"Service\"][\"clear\"] = (input) =>\n    withThreadLock(\n      input.threadId,\n      Effect.gen(function* () {\n        const terminalId = input.terminalId;\n        const session = yield* requireSession(input.threadId, terminalId);\n        session.history = \"\";\n        session.pendingHistoryControlSequence = \"\";\n        session.pendingProcessEvents = [];\n        session.pendingProcessEventIndex = 0;\n        session.processEventDrainRunning = false;\n        const eventStamp = advanceEventSequence(session);\n        yield* persistHistory(input.threadId, terminalId, session.history);\n        yield* publishEvent({\n          type: \"cleared\",\n          threadId: input.threadId,\n          terminalId,\n          sequence: eventStamp.sequence,\n        });\n      }),\n    );\n\n  const restart: TerminalManager[\"Service\"][\"restart\"] = (input) =>\n    withThreadLock(\n      input.threadId,\n      Effect.gen(function* () {\n        yield* increment(terminalRestartsTotal, { scope: \"thread\" });\n        const terminalId = input.terminalId;\n        yield* assertValidCwd(input.cwd);\n\n        const sessionKey = toSessionKey(input.threadId, terminalId);\n        const existingSession = yield* getSession(input.threadId, terminalId);\n        let session: TerminalSessionState;\n        if (Option.isNone(existingSession)) {\n          const cols = input.cols ?? DEFAULT_OPEN_COLS;\n          const rows = input.rows ?? DEFAULT_OPEN_ROWS;\n          session = {\n            threadId: input.threadId,\n            terminalId,\n            cwd: input.cwd,\n            worktreePath: input.worktreePath ?? null,\n            status: \"starting\",\n            pid: null,\n            history: \"\",\n            pendingHistoryControlSequence: \"\",\n            pendingProcessEvents: [],\n            pendingProcessEventIndex: 0,\n            processEventDrainRunning: false,\n            exitCode: null,\n            exitSignal: null,\n            updatedAt: yield* nowIso,\n            eventSequence: 0,\n            cols,\n            rows,\n            process: null,\n            unsubscribeData: null,\n            unsubscribeExit: null,\n            hasRunningSubprocess: false,\n            childCommandLabel: null,\n            runtimeEnv: normalizedRuntimeEnv(input.env),\n          };\n          const createdSession = session;\n          yield* modifyManagerState((state) => {\n            const sessions = new Map(state.sessions);\n            sessions.set(sessionKey, createdSession);\n            return [undefined, { ...state, sessions }] as const;\n          });\n          yield* evictInactiveSessionsIfNeeded();\n        } else {\n          session = existingSession.value;\n          yield* stopProcess(session);\n          session.cwd = input.cwd;\n          session.worktreePath = input.worktreePath ?? null;\n          session.runtimeEnv = normalizedRuntimeEnv(input.env);\n        }\n\n        const cols = input.cols ?? session.cols;\n        const rows = input.rows ?? session.rows;\n\n        session.history = \"\";\n        session.pendingHistoryControlSequence = \"\";\n        session.pendingProcessEvents = [];\n        session.pendingProcessEventIndex = 0;\n        session.processEventDrainRunning = false;\n        yield* persistHistory(input.threadId, terminalId, session.history);\n        yield* startSession(\n          session,\n          {\n            threadId: input.threadId,\n            terminalId,\n            cwd: input.cwd,\n            ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),\n            cols,\n            rows,\n            ...(input.env ? { env: input.env } : {}),\n          },\n          \"restarted\",\n        );\n        return snapshot(session);\n      }),\n    );\n\n  const close: TerminalManager[\"Service\"][\"close\"] = (input) =>\n    withThreadLock(\n      input.threadId,\n      Effect.gen(function* () {\n        if (input.terminalId) {\n          yield* closeSession(input.threadId, input.terminalId, input.deleteHistory === true);\n          return;\n        }\n\n        const threadSessions = yield* sessionsForThread(input.threadId);\n        yield* Effect.forEach(\n          threadSessions,\n          (session) => closeSession(input.threadId, session.terminalId, false),\n          { discard: true },\n        );\n\n        if (input.deleteHistory) {\n          yield* deleteAllHistoryForThread(input.threadId);\n        }\n      }),\n    );\n\n  return TerminalManager.of({\n    open,\n    attachStream,\n    write,\n    resize,\n    clear,\n    restart,\n    close,\n    subscribe,\n    subscribeMetadata,\n  });\n});\n\nexport const layer = Layer.effect(TerminalManager, make()).pipe(Layer.provide(ProcessRunner.layer));\n","import {\n  type EnvironmentId,\n  PreviewAutomationUnavailableError,\n  type ProviderInstanceId,\n  type ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\n\nexport type McpCapability = \"preview\";\n\nexport interface McpInvocationScope {\n  readonly environmentId: EnvironmentId;\n  readonly threadId: ThreadId;\n  readonly providerSessionId: string;\n  readonly providerInstanceId: ProviderInstanceId;\n  readonly capabilities: ReadonlySet<McpCapability>;\n  readonly issuedAt: number;\n}\n\nexport class McpInvocationContext extends Context.Service<\n  McpInvocationContext,\n  McpInvocationScope\n>()(\"t3/mcp/McpInvocationContext\") {}\n\nexport const requireMcpCapability = Effect.fn(\"mcp.requireCapability\")(function* (\n  capability: McpCapability,\n) {\n  const invocation = yield* McpInvocationContext;\n  if (!invocation.capabilities.has(capability)) {\n    return yield* new PreviewAutomationUnavailableError({\n      capability,\n      environmentId: invocation.environmentId,\n      threadId: invocation.threadId,\n      providerSessionId: invocation.providerSessionId,\n      providerInstanceId: invocation.providerInstanceId,\n    });\n  }\n  return invocation;\n});\n","import {\n  PREVIEW_AUTOMATION_V1_OPERATIONS,\n  PreviewAutomationClientDisconnectedError,\n  PreviewAutomationControlInterruptedError,\n  PreviewAutomationExecutionError,\n  PreviewAutomationInvalidSelectorError,\n  PreviewAutomationMalformedResponseError,\n  PreviewAutomationNoAvailableHostError,\n  PreviewAutomationRemoteUnavailableError,\n  PreviewAutomationRequestQueueClosedError,\n  PreviewAutomationResultTooLargeError,\n  PreviewAutomationTabNotFoundError,\n  PreviewAutomationTargetNotEditableError,\n  PreviewAutomationTimeoutError,\n  PreviewAutomationUnsupportedClientError,\n  PreviewTabId,\n  type PreviewAutomationError,\n  type PreviewAutomationOperation,\n  type PreviewAutomationHost,\n  type PreviewAutomationHostFocus,\n  type PreviewAutomationResponse,\n  type PreviewAutomationStreamEvent,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport * as McpInvocationContext from \"./McpInvocationContext.ts\";\n\nexport interface PreviewAutomationInvokeInput {\n  readonly scope: McpInvocationContext.McpInvocationScope;\n  readonly operation: PreviewAutomationOperation;\n  readonly input: unknown;\n  readonly tabId?: PreviewTabId;\n  readonly timeoutMs?: number;\n}\n\nexport class PreviewAutomationBroker extends Context.Service<\n  PreviewAutomationBroker,\n  {\n    readonly connect: (\n      host: PreviewAutomationHost,\n    ) => Effect.Effect<Stream.Stream<PreviewAutomationStreamEvent>>;\n    readonly focusHost: (host: PreviewAutomationHostFocus) => Effect.Effect<void>;\n    readonly respond: (\n      response: PreviewAutomationResponse,\n    ) => Effect.Effect<void, PreviewAutomationError>;\n    readonly invoke: <A = unknown>(\n      request: PreviewAutomationInvokeInput,\n    ) => Effect.Effect<A, PreviewAutomationError>;\n  }\n>()(\"t3/mcp/PreviewAutomationBroker\") {}\n\ninterface ClientConnection {\n  readonly clientId: string;\n  readonly connectionId: string;\n  readonly environmentId: PreviewAutomationHost[\"environmentId\"];\n  readonly supportedOperations: ReadonlySet<PreviewAutomationOperation>;\n  readonly focused: boolean;\n  readonly focusOrder: number;\n  readonly queue: Queue.Queue<PreviewAutomationStreamEvent>;\n}\n\ninterface PendingRequest {\n  readonly queue: ClientConnection[\"queue\"];\n  readonly deferred: Deferred.Deferred<unknown, PreviewAutomationError>;\n  readonly context: PreviewAutomationRequestErrorContext;\n}\n\n/**\n * A lease pinning one provider session to one desktop runtime. It lives exactly\n * as long as the connection it names: `connectionId`/`queue` identity is what\n * makes a lease valid, so a disconnected or replaced host is dropped on the next\n * lookup. The lease deliberately has no clock of its own — it used to inherit\n * the MCP credential's expiry, which coupled host stickiness to an unrelated\n * auth deadline and could migrate a live session to another runtime mid-flow.\n */\ninterface HostAssignment {\n  readonly clientId: ClientConnection[\"clientId\"];\n  readonly connectionId: ClientConnection[\"connectionId\"];\n  readonly queue: ClientConnection[\"queue\"];\n  readonly tabId?: PreviewTabId;\n  readonly tabSequence?: number;\n}\n\ninterface PreviewAutomationRequestErrorContext {\n  readonly operation: PreviewAutomationOperation;\n  readonly environmentId: McpInvocationContext.McpInvocationScope[\"environmentId\"];\n  readonly threadId: McpInvocationContext.McpInvocationScope[\"threadId\"];\n  readonly providerSessionId: string;\n  readonly providerInstanceId: McpInvocationContext.McpInvocationScope[\"providerInstanceId\"];\n  readonly clientId: string;\n  readonly connectionId: ClientConnection[\"connectionId\"];\n  readonly requestId: string;\n  readonly tabId?: PreviewTabId;\n  readonly timeoutMs: number;\n  readonly selectorKind?: \"locator\" | \"selector\";\n  readonly selectorLength?: number;\n}\n\ninterface BrokerState {\n  readonly clients: ReadonlyMap<string, ClientConnection>;\n  readonly assignments: ReadonlyMap<string, HostAssignment>;\n  readonly pending: ReadonlyMap<string, PendingRequest>;\n  readonly requestSequence: number;\n  readonly focusSequence: number;\n}\n\nconst removeConnectionFromState = (\n  current: BrokerState,\n  clientId: string,\n  queue: ClientConnection[\"queue\"],\n): { readonly state: BrokerState; readonly disconnected: ReadonlyArray<PendingRequest> } => {\n  const clients = new Map(current.clients);\n  const assignments = new Map(current.assignments);\n  const pending = new Map(current.pending);\n  const disconnected: PendingRequest[] = [];\n  if (current.clients.get(clientId)?.queue === queue) clients.delete(clientId);\n  for (const [assignmentKey, assignment] of assignments) {\n    if (assignment.queue === queue) assignments.delete(assignmentKey);\n  }\n  for (const [requestId, entry] of pending) {\n    if (entry.queue !== queue) continue;\n    pending.delete(requestId);\n    disconnected.push(entry);\n  }\n  return {\n    state: { ...current, clients, assignments, pending },\n    disconnected,\n  };\n};\n\nconst selectorDiagnosticsFromInput = (\n  input: unknown,\n): Pick<PreviewAutomationRequestErrorContext, \"selectorKind\" | \"selectorLength\"> => {\n  if (typeof input !== \"object\" || input === null) return {};\n  if (\"locator\" in input && typeof input.locator === \"string\") {\n    return { selectorKind: \"locator\", selectorLength: input.locator.length };\n  }\n  if (\"selector\" in input && typeof input.selector === \"string\") {\n    return { selectorKind: \"selector\", selectorLength: input.selector.length };\n  }\n  return {};\n};\n\nconst hostAssignmentKey = (scope: McpInvocationContext.McpInvocationScope): string =>\n  `${scope.environmentId}\\u0000${scope.providerSessionId}`;\n\nconst isPreviewTabId = Schema.is(PreviewTabId);\n\nconst readResultTabId = (result: unknown): PreviewTabId | null | undefined => {\n  if (typeof result !== \"object\" || result === null || !(\"tabId\" in result)) return undefined;\n  const tabId = result.tabId;\n  return tabId === null || isPreviewTabId(tabId) ? tabId : undefined;\n};\n\nconst supportsOperation = (\n  connection: ClientConnection,\n  operation: PreviewAutomationOperation,\n): boolean => connection.supportedOperations.has(operation);\n\ntype RemoteDetailKind = \"null\" | \"array\" | \"object\" | \"string\" | \"number\" | \"boolean\";\n\nfunction remoteDetailKind(detail: unknown): RemoteDetailKind {\n  if (detail === null) return \"null\";\n  if (Array.isArray(detail)) return \"array\";\n  switch (typeof detail) {\n    case \"string\":\n      return \"string\";\n    case \"number\":\n      return \"number\";\n    case \"boolean\":\n      return \"boolean\";\n    default:\n      return \"object\";\n  }\n}\n\nconst classifyResponseError = (\n  context: PreviewAutomationRequestErrorContext,\n  error: NonNullable<PreviewAutomationResponse[\"error\"]>,\n): PreviewAutomationError => {\n  const remoteDiagnostics = {\n    remoteTag: error._tag,\n    remoteMessageLength: error.message.length,\n    ...(error.detail === undefined ? {} : { remoteDetailKind: remoteDetailKind(error.detail) }),\n    cause: error,\n  };\n  switch (error._tag) {\n    case \"PreviewAutomationNoAvailableHostError\":\n      return new PreviewAutomationNoAvailableHostError({\n        ...context,\n        ...remoteDiagnostics,\n      });\n    case \"PreviewAutomationUnsupportedClientError\":\n      return new PreviewAutomationUnsupportedClientError({\n        ...context,\n        ...remoteDiagnostics,\n      });\n    case \"PreviewAutomationTabNotFoundError\":\n      return new PreviewAutomationTabNotFoundError({\n        ...context,\n        ...remoteDiagnostics,\n      });\n    case \"PreviewAutomationTimeoutError\":\n      return new PreviewAutomationTimeoutError({\n        ...context,\n        ...remoteDiagnostics,\n      });\n    case \"PreviewAutomationControlInterruptedError\":\n      return new PreviewAutomationControlInterruptedError({\n        ...context,\n        ...remoteDiagnostics,\n      });\n    case \"PreviewAutomationInvalidSelectorError\": {\n      return new PreviewAutomationInvalidSelectorError({\n        ...context,\n        ...remoteDiagnostics,\n      });\n    }\n    case \"PreviewAutomationTargetNotEditableError\": {\n      const detail =\n        typeof error.detail === \"object\" && error.detail !== null ? error.detail : undefined;\n      const remoteSelectorKind =\n        detail &&\n        \"selectorKind\" in detail &&\n        (detail.selectorKind === \"focused-element\" ||\n          detail.selectorKind === \"locator\" ||\n          detail.selectorKind === \"selector\")\n          ? detail.selectorKind\n          : undefined;\n      const remoteSelectorLength =\n        detail &&\n        \"selectorLength\" in detail &&\n        typeof detail.selectorLength === \"number\" &&\n        Number.isInteger(detail.selectorLength) &&\n        detail.selectorLength >= 0\n          ? detail.selectorLength\n          : undefined;\n      return new PreviewAutomationTargetNotEditableError({\n        ...context,\n        ...remoteDiagnostics,\n        ...(remoteSelectorKind === undefined && context.selectorKind === undefined\n          ? {}\n          : { selectorKind: remoteSelectorKind ?? context.selectorKind }),\n        ...(remoteSelectorLength === undefined && context.selectorLength === undefined\n          ? {}\n          : { selectorLength: remoteSelectorLength ?? context.selectorLength }),\n      });\n    }\n    case \"PreviewAutomationResultTooLargeError\": {\n      const detail =\n        typeof error.detail === \"object\" && error.detail !== null ? error.detail : undefined;\n      const maximumBytes =\n        detail &&\n        \"maximumBytes\" in detail &&\n        typeof detail.maximumBytes === \"number\" &&\n        Number.isInteger(detail.maximumBytes) &&\n        detail.maximumBytes > 0\n          ? detail.maximumBytes\n          : undefined;\n      return new PreviewAutomationResultTooLargeError({\n        ...context,\n        ...remoteDiagnostics,\n        ...(maximumBytes === undefined ? {} : { maximumBytes }),\n      });\n    }\n    case \"PreviewAutomationUnavailableError\":\n      return new PreviewAutomationRemoteUnavailableError({\n        ...context,\n        ...remoteDiagnostics,\n      });\n    default:\n      return new PreviewAutomationExecutionError({\n        ...context,\n        ...remoteDiagnostics,\n      });\n  }\n};\n\nexport const make = Effect.gen(function* PreviewAutomationBrokerMake() {\n  const crypto = yield* Crypto.Crypto;\n  const state = yield* SynchronizedRef.make<BrokerState>({\n    clients: new Map(),\n    assignments: new Map(),\n    pending: new Map(),\n    requestSequence: 0,\n    focusSequence: 0,\n  });\n\n  const closeConnection = Effect.fn(\"PreviewAutomationBroker.closeConnection\")(function* (\n    queue: ClientConnection[\"queue\"],\n    disconnected: ReadonlyArray<PendingRequest>,\n  ) {\n    yield* Effect.forEach(\n      disconnected,\n      ({ deferred, context }) =>\n        Deferred.fail(deferred, new PreviewAutomationClientDisconnectedError(context)),\n      { discard: true },\n    );\n    yield* Queue.shutdown(queue);\n  });\n\n  const disconnect = Effect.fn(\"PreviewAutomationBroker.disconnect\")(function* (\n    clientId: string,\n    queue: ClientConnection[\"queue\"],\n  ) {\n    const disconnected = yield* SynchronizedRef.modify(state, (current) => {\n      const removed = removeConnectionFromState(current, clientId, queue);\n      return [removed.disconnected, removed.state] as const;\n    });\n    yield* closeConnection(queue, disconnected);\n  });\n\n  const acquireConnection = Effect.fn(\"PreviewAutomationBroker.acquireConnection\")(function* (\n    host: PreviewAutomationHost,\n  ) {\n    const clientId = host.clientId;\n    const queue = yield* Queue.unbounded<PreviewAutomationStreamEvent>();\n    const connectionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);\n    yield* Queue.offer(queue, { type: \"connected\", connectionId });\n    const connection: ClientConnection = {\n      clientId,\n      connectionId,\n      environmentId: host.environmentId,\n      supportedOperations: new Set(host.supportedOperations ?? PREVIEW_AUTOMATION_V1_OPERATIONS),\n      focused: false,\n      focusOrder: 0,\n      queue,\n    };\n    const registration = yield* SynchronizedRef.modify(state, (current) => {\n      const previousConnection = current.clients.get(clientId);\n      const removed = previousConnection\n        ? removeConnectionFromState(current, clientId, previousConnection.queue)\n        : { state: current, disconnected: [] };\n      const clients = new Map(removed.state.clients);\n      const focusSequence = removed.state.focusSequence + 1;\n      const registeredConnection = { ...connection, focusOrder: focusSequence };\n      clients.set(clientId, registeredConnection);\n      return [\n        {\n          previousConnection,\n          disconnected: removed.disconnected,\n          registeredConnection,\n        },\n        { ...removed.state, clients, focusSequence },\n      ] as const;\n    });\n    if (registration.previousConnection) {\n      yield* closeConnection(registration.previousConnection.queue, registration.disconnected);\n    }\n    return registration.registeredConnection;\n  });\n\n  const connect: PreviewAutomationBroker[\"Service\"][\"connect\"] = Effect.fn(\n    \"PreviewAutomationBroker.connect\",\n  )((host) =>\n    Effect.succeed(\n      Stream.unwrap(\n        Effect.acquireRelease(acquireConnection(host), (connection) =>\n          disconnect(connection.clientId, connection.queue),\n        ).pipe(Effect.map((connection) => Stream.fromQueue(connection.queue))),\n      ),\n    ),\n  );\n\n  const focusHost: PreviewAutomationBroker[\"Service\"][\"focusHost\"] = Effect.fn(\n    \"PreviewAutomationBroker.focusHost\",\n  )(function* (host) {\n    yield* SynchronizedRef.update(state, (current) => {\n      const currentHost = current.clients.get(host.clientId);\n      if (\n        !currentHost ||\n        currentHost.environmentId !== host.environmentId ||\n        currentHost.connectionId !== host.connectionId\n      ) {\n        return current;\n      }\n      const clients = new Map(current.clients);\n      const focusSequence = host.focused ? current.focusSequence + 1 : current.focusSequence;\n      clients.set(host.clientId, {\n        ...currentHost,\n        focused: host.focused,\n        focusOrder: host.focused ? focusSequence : currentHost.focusOrder,\n      });\n      return { ...current, clients, focusSequence };\n    });\n  });\n\n  const respond: PreviewAutomationBroker[\"Service\"][\"respond\"] = Effect.fn(\n    \"PreviewAutomationBroker.respond\",\n  )(function* (response) {\n    const pending = yield* SynchronizedRef.modify(state, (current) => {\n      const entry = current.pending.get(response.requestId);\n      if (\n        !entry ||\n        entry.context.clientId !== response.clientId ||\n        entry.context.connectionId !== response.connectionId\n      ) {\n        return [undefined, current] as const;\n      }\n      const next = new Map(current.pending);\n      next.delete(response.requestId);\n      return [entry, { ...current, pending: next }] as const;\n    });\n    if (!pending) return;\n    if (response.ok) {\n      yield* Deferred.succeed(pending.deferred, response.result);\n    } else {\n      yield* Deferred.fail(\n        pending.deferred,\n        response.error\n          ? classifyResponseError(pending.context, response.error)\n          : new PreviewAutomationMalformedResponseError(pending.context),\n      );\n    }\n  });\n\n  const invoke = Effect.fn(\"PreviewAutomationBroker.invoke\")(function* <A = unknown>(\n    input: Parameters<PreviewAutomationBroker[\"Service\"][\"invoke\"]>[0],\n  ): Effect.fn.Return<A, PreviewAutomationError> {\n    const timeoutMs = input.timeoutMs ?? 15_000;\n    const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();\n    const route = yield* SynchronizedRef.modify(state, (current) => {\n      const assignments = new Map(\n        Array.from(current.assignments).filter(([, assignment]) => {\n          const connection = current.clients.get(assignment.clientId);\n          return (\n            connection?.connectionId === assignment.connectionId &&\n            connection.queue === assignment.queue\n          );\n        }),\n      );\n      const assignmentKey = hostAssignmentKey(input.scope);\n      const assigned = assignments.get(assignmentKey);\n      const assignedConnection = assigned ? current.clients.get(assigned.clientId) : undefined;\n      const hasLiveAssignment = assignedConnection?.environmentId === input.scope.environmentId;\n      // Keep one provider session on one physical desktop runtime so a\n      // multi-step browser interaction cannot jump between independent\n      // Electron cookie/DOM state. A live assignment that predates an\n      // operation is not silently moved to a newer client: the caller gets a\n      // capability failure and can deliberately start a fresh provider\n      // session. A dead lease is pruned above and may fail over.\n      const connection =\n        hasLiveAssignment && supportsOperation(assignedConnection, input.operation)\n          ? assignedConnection\n          : hasLiveAssignment\n            ? undefined\n            : Array.from(current.clients.values())\n                .filter(\n                  (host) =>\n                    host.environmentId === input.scope.environmentId &&\n                    supportsOperation(host, input.operation),\n                )\n                .sort(\n                  (left, right) =>\n                    right.supportedOperations.size - left.supportedOperations.size ||\n                    Number(right.focused) - Number(left.focused) ||\n                    right.focusOrder - left.focusOrder,\n                )[0];\n      if (!connection) {\n        if (!hasLiveAssignment) assignments.delete(assignmentKey);\n        return [undefined, { ...current, assignments }] as const;\n      }\n      const canReuseAssignedTab =\n        assigned !== undefined &&\n        assigned.connectionId === connection.connectionId &&\n        assigned.queue === connection.queue;\n      assignments.set(assignmentKey, {\n        clientId: connection.clientId,\n        connectionId: connection.connectionId,\n        queue: connection.queue,\n        ...(canReuseAssignedTab && assigned.tabId !== undefined ? { tabId: assigned.tabId } : {}),\n        ...(canReuseAssignedTab && assigned.tabSequence !== undefined\n          ? { tabSequence: assigned.tabSequence }\n          : {}),\n      });\n\n      const requestSequence = current.requestSequence;\n      const requestId = `preview-${requestSequence}`;\n      const tabId = input.tabId ?? (canReuseAssignedTab ? assigned.tabId : undefined);\n      const selectorDiagnostics = selectorDiagnosticsFromInput(input.input);\n      const context: PreviewAutomationRequestErrorContext = {\n        operation: input.operation,\n        environmentId: input.scope.environmentId,\n        threadId: input.scope.threadId,\n        providerSessionId: input.scope.providerSessionId,\n        providerInstanceId: input.scope.providerInstanceId,\n        clientId: connection.clientId,\n        connectionId: connection.connectionId,\n        requestId,\n        ...(tabId === undefined ? {} : { tabId }),\n        timeoutMs,\n        ...selectorDiagnostics,\n      };\n      const pending = new Map(current.pending);\n      pending.set(requestId, { queue: connection.queue, deferred, context });\n      return [\n        { connection, requestId, requestContext: context, requestSequence },\n        { ...current, assignments, pending, requestSequence: current.requestSequence + 1 },\n      ] as const;\n    });\n    if (!route) {\n      return yield* new PreviewAutomationNoAvailableHostError({\n        operation: input.operation,\n        environmentId: input.scope.environmentId,\n        threadId: input.scope.threadId,\n        providerSessionId: input.scope.providerSessionId,\n        providerInstanceId: input.scope.providerInstanceId,\n      });\n    }\n    const { connection, requestId, requestContext, requestSequence } = route;\n    const removePending = SynchronizedRef.update(state, (next) => {\n      if (!next.pending.has(requestId)) return next;\n      const pending = new Map(next.pending);\n      pending.delete(requestId);\n      return { ...next, pending };\n    });\n    const awaitResponse = Effect.fn(\"PreviewAutomationBroker.awaitResponse\")(function* () {\n      const offered = yield* Queue.offer(connection.queue, {\n        type: \"request\",\n        connectionId: connection.connectionId,\n        request: {\n          requestId,\n          threadId: input.scope.threadId,\n          tabId: requestContext.tabId,\n          tabIdExplicit: input.tabId !== undefined,\n          operation: input.operation,\n          input: input.input,\n          timeoutMs,\n        },\n      });\n      if (!offered) {\n        const completion = yield* Deferred.poll(deferred);\n        if (Option.isSome(completion)) {\n          return (yield* completion.value) as A;\n        }\n        return yield* new PreviewAutomationRequestQueueClosedError(requestContext);\n      }\n      const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(timeoutMs));\n      return yield* Option.match(result, {\n        onNone: () => Effect.fail(new PreviewAutomationTimeoutError(requestContext)),\n        onSome: (value) => Effect.succeed(value as A),\n      });\n    });\n    const result = yield* awaitResponse().pipe(Effect.ensuring(removePending));\n    const responseTabId = readResultTabId(result);\n    const resultTabId = responseTabId === undefined ? input.tabId : responseTabId;\n    if (resultTabId === undefined) return result;\n    const assignmentKey = hostAssignmentKey(input.scope);\n    yield* SynchronizedRef.update(state, (current) => {\n      const assignment = current.assignments.get(assignmentKey);\n      if (\n        !assignment ||\n        assignment.connectionId !== connection.connectionId ||\n        assignment.queue !== connection.queue ||\n        (assignment.tabSequence ?? -1) > requestSequence\n      ) {\n        return current;\n      }\n      const assignments = new Map(current.assignments);\n      if (resultTabId === null) {\n        const { tabId: _tabId, ...withoutTabId } = assignment;\n        assignments.set(assignmentKey, { ...withoutTabId, tabSequence: requestSequence });\n      } else {\n        assignments.set(assignmentKey, {\n          ...assignment,\n          ...(resultTabId === undefined ? {} : { tabId: resultTabId }),\n          tabSequence: requestSequence,\n        });\n      }\n      return { ...current, assignments };\n    });\n    return result;\n  });\n\n  return PreviewAutomationBroker.of({ connect, focusHost, respond, invoke });\n}).pipe(Effect.withSpan(\"PreviewAutomationBroker.make\"));\n\nexport const layer = Layer.effect(PreviewAutomationBroker, make);\n","/**\n * In-memory PreviewManager implementation.\n *\n * Sessions are keyed by `(threadId, tabId)`; a single thread can host\n * multiple tabs (browser-style). `open` always creates a new tab — tab\n * lifecycle is owned by the renderer.\n *\n * Events are published via Effect's `PubSub`, so subscriber failures are\n * isolated from the publishing call (a closed WS subscriber queue cannot\n * fail an in-progress `navigate()`).\n */\nimport {\n  type PreviewCloseInput,\n  type PreviewEvent,\n  type PreviewError,\n  PreviewInvalidUrlError,\n  type PreviewListInput,\n  type PreviewListResult,\n  type PreviewNavigateInput,\n  type PreviewOpenInput,\n  type PreviewRefreshInput,\n  type PreviewReportStatusInput,\n  type PreviewResizeInput,\n  FILL_PREVIEW_VIEWPORT,\n  PreviewSessionLookupError,\n  type PreviewSessionSnapshot,\n} from \"@t3tools/contracts\";\nimport {\n  isPreviewUrlNormalizationError,\n  newPreviewTabId,\n  normalizePreviewUrl,\n} from \"@t3tools/shared/preview\";\nimport * as NodeCrypto from \"node:crypto\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nexport class PreviewManager extends Context.Service<\n  PreviewManager,\n  {\n    readonly open: (input: PreviewOpenInput) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;\n    readonly navigate: (\n      input: PreviewNavigateInput,\n    ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;\n    readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;\n    readonly resize: (\n      input: PreviewResizeInput,\n    ) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;\n    readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;\n    readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;\n    readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;\n    readonly events: Stream.Stream<PreviewEvent>;\n    readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;\n  }\n>()(\"t3/preview/Manager/PreviewManager\") {}\n\ninterface PreviewSessionState {\n  readonly threadId: string;\n  readonly tabId: string;\n  readonly snapshot: PreviewSessionSnapshot;\n}\n\ninterface ManagerState {\n  /** All sessions across every thread, keyed by `${threadId}\\u0000${tabId}`. */\n  readonly sessions: ReadonlyMap<string, PreviewSessionState>;\n  /** Global monotonic revision establishing list/event ordering. */\n  readonly revision: number;\n}\n\nconst initialState: ManagerState = { sessions: new Map(), revision: 0 };\n\ntype PreviewEventDraft = PreviewEvent extends infer Event\n  ? Event extends { readonly revision: number }\n    ? Omit<Event, \"revision\" | \"serverEpoch\">\n    : never\n  : never;\n\nconst compositeKey = (threadId: string, tabId: string): string => `${threadId}\\u0000${tabId}`;\n\nconst sessionsForThread = (\n  state: ManagerState,\n  threadId: string,\n): ReadonlyArray<PreviewSessionState> => {\n  const out: PreviewSessionState[] = [];\n  for (const session of state.sessions.values()) {\n    if (session.threadId === threadId) out.push(session);\n  }\n  return out;\n};\n\nconst normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>\n  Effect.try({\n    try: () => normalizePreviewUrl(rawUrl),\n    catch: (cause) => {\n      if (isPreviewUrlNormalizationError(cause)) {\n        return new PreviewInvalidUrlError({\n          inputLength: cause.inputLength,\n          reason: cause.reason,\n          protocol: cause.protocol,\n          cause,\n        });\n      }\n\n      return new PreviewInvalidUrlError({\n        inputLength: rawUrl.length,\n        reason: \"unexpected\",\n        cause,\n      });\n    },\n  });\n\nconst currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));\n\nconst buildLoadingSnapshot = (input: {\n  readonly threadId: string;\n  readonly tabId: string;\n  readonly url: string;\n  readonly title: string;\n  readonly updatedAt: string;\n}): PreviewSessionSnapshot => ({\n  threadId: input.threadId,\n  tabId: input.tabId,\n  navStatus: { _tag: \"Loading\", url: input.url, title: input.title },\n  canGoBack: false,\n  canGoForward: false,\n  viewport: FILL_PREVIEW_VIEWPORT,\n  updatedAt: input.updatedAt,\n});\n\nconst buildIdleSnapshot = (input: {\n  readonly threadId: string;\n  readonly tabId: string;\n  readonly updatedAt: string;\n}): PreviewSessionSnapshot => ({\n  threadId: input.threadId,\n  tabId: input.tabId,\n  navStatus: { _tag: \"Idle\" },\n  canGoBack: false,\n  canGoForward: false,\n  viewport: FILL_PREVIEW_VIEWPORT,\n  updatedAt: input.updatedAt,\n});\n\nexport const make = Effect.gen(function* PreviewManagerMake() {\n  const serverEpoch = NodeCrypto.randomUUID();\n  const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);\n  // Unbounded PubSub is fine here — events are tiny and we don't want to\n  // block publishers if a subscriber is slow. WS clients backpressure on\n  // their own queues downstream.\n  const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();\n  const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);\n\n  /**\n   * Atomic read-modify-write over the session for `(threadId, tabId)`. The\n   * mutator runs under the SynchronizedRef so concurrent writers cannot\n   * interleave. Lookup failures travel through the modify result so both\n   * branches yield the same `[A, S]` shape `modifyEffect` requires.\n   *\n   * The event is published INSIDE the lock so observers see events in the\n   * same order as the underlying state transitions. Publishing an unbounded\n   * PubSub is non-blocking, so this is cheap.\n   */\n  const mutateExistingSession = <R, E>(\n    threadId: string,\n    tabId: string,\n    mutator: (\n      session: PreviewSessionState,\n    ) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEventDraft | null; result: R }, E>,\n  ): Effect.Effect<R, E | PreviewSessionLookupError> => {\n    type ModifyResult =\n      | { kind: \"fail\"; error: PreviewSessionLookupError }\n      | { kind: \"ok\"; result: R };\n\n    return SynchronizedRef.modifyEffect(stateRef, (state) => {\n      const session = state.sessions.get(compositeKey(threadId, tabId));\n      if (!session) {\n        return Effect.succeed([\n          { kind: \"fail\", error: new PreviewSessionLookupError({ threadId, tabId }) },\n          state,\n        ] as readonly [ModifyResult, ManagerState]);\n      }\n      return mutator(session).pipe(\n        Effect.flatMap(\n          Effect.fn(\"PreviewManager.commitMutation\")(function* ({ next, emit, result }) {\n            const revision = emit ? state.revision + 1 : state.revision;\n            if (emit) {\n              yield* PubSub.publish(eventsPubSub, {\n                ...emit,\n                revision,\n                serverEpoch,\n              } as PreviewEvent);\n            }\n            const sessions = new Map(state.sessions);\n            sessions.set(compositeKey(threadId, tabId), next);\n            return [{ kind: \"ok\", result } as ModifyResult, { sessions, revision }] as readonly [\n              ModifyResult,\n              ManagerState,\n            ];\n          }),\n        ),\n      );\n    }).pipe(\n      Effect.flatMap((modify) =>\n        modify.kind === \"fail\" ? Effect.fail(modify.error) : Effect.succeed(modify.result),\n      ),\n    );\n  };\n\n  const open: PreviewManager[\"Service\"][\"open\"] = Effect.fn(\"PreviewManager.open\")(\n    function* (input) {\n      const tabId = newPreviewTabId();\n      const updatedAt = yield* currentIsoTimestamp;\n      const snapshot = input.url\n        ? buildLoadingSnapshot({\n            threadId: input.threadId,\n            tabId,\n            url: yield* normalizeUrl(input.url),\n            title: \"\",\n            updatedAt,\n          })\n        : buildIdleSnapshot({ threadId: input.threadId, tabId, updatedAt });\n      yield* SynchronizedRef.modifyEffect(stateRef, (state) =>\n        Effect.gen(function* () {\n          const revision = state.revision + 1;\n          const sessions = new Map(state.sessions);\n          sessions.set(compositeKey(input.threadId, tabId), {\n            threadId: input.threadId,\n            tabId,\n            snapshot,\n          });\n          yield* PubSub.publish(eventsPubSub, {\n            type: \"opened\",\n            threadId: input.threadId,\n            tabId,\n            createdAt: snapshot.updatedAt,\n            serverEpoch,\n            revision,\n            snapshot,\n          });\n          return [snapshot, { sessions, revision }] as const;\n        }),\n      );\n      return snapshot;\n    },\n  );\n\n  const navigate: PreviewManager[\"Service\"][\"navigate\"] = Effect.fn(\"PreviewManager.navigate\")(\n    function* (input) {\n      const url = yield* normalizeUrl(input.url);\n      return yield* mutateExistingSession(\n        input.threadId,\n        input.tabId,\n        Effect.fn(\"PreviewManager.navigateSession\")(function* (session) {\n          const updatedAt = yield* currentIsoTimestamp;\n          const previousTitle =\n            session.snapshot.navStatus._tag === \"Idle\" ? \"\" : session.snapshot.navStatus.title;\n          const resolvedTitle = input.resolvedTitle ?? previousTitle;\n          const snapshot: PreviewSessionSnapshot = {\n            threadId: session.threadId,\n            tabId: session.tabId,\n            navStatus: { _tag: \"Success\", url, title: resolvedTitle },\n            canGoBack: session.snapshot.canGoBack,\n            canGoForward: session.snapshot.canGoForward,\n            viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,\n            updatedAt,\n          };\n          return {\n            next: { ...session, snapshot },\n            emit: {\n              type: \"navigated\",\n              threadId: session.threadId,\n              tabId: session.tabId,\n              createdAt: snapshot.updatedAt,\n              snapshot,\n            },\n            result: snapshot,\n          };\n        }),\n      );\n    },\n  );\n\n  const reportStatus: PreviewManager[\"Service\"][\"reportStatus\"] = Effect.fn(\n    \"PreviewManager.reportStatus\",\n  )(function* (input) {\n    yield* mutateExistingSession(\n      input.threadId,\n      input.tabId,\n      Effect.fn(\"PreviewManager.reportSessionStatus\")(function* (session) {\n        const updatedAt = yield* currentIsoTimestamp;\n        const snapshot: PreviewSessionSnapshot = {\n          threadId: session.threadId,\n          tabId: session.tabId,\n          navStatus: input.navStatus,\n          canGoBack: input.canGoBack,\n          canGoForward: input.canGoForward,\n          viewport: session.snapshot.viewport ?? FILL_PREVIEW_VIEWPORT,\n          updatedAt,\n        };\n        const emit: PreviewEventDraft =\n          input.navStatus._tag === \"LoadFailed\"\n            ? {\n                type: \"failed\",\n                threadId: session.threadId,\n                tabId: session.tabId,\n                createdAt: snapshot.updatedAt,\n                url: input.navStatus.url,\n                title: input.navStatus.title,\n                code: input.navStatus.code,\n                description: input.navStatus.description,\n              }\n            : {\n                type: \"navigated\",\n                threadId: session.threadId,\n                tabId: session.tabId,\n                createdAt: snapshot.updatedAt,\n                snapshot,\n              };\n        return {\n          next: { ...session, snapshot },\n          emit,\n          result: undefined as void,\n        };\n      }),\n    );\n  });\n\n  const resize: PreviewManager[\"Service\"][\"resize\"] = Effect.fn(\"PreviewManager.resize\")(\n    function* (input) {\n      return yield* mutateExistingSession(\n        input.threadId,\n        input.tabId,\n        Effect.fn(\"PreviewManager.resizeSession\")(function* (session) {\n          const updatedAt = yield* currentIsoTimestamp;\n          const snapshot: PreviewSessionSnapshot = {\n            ...session.snapshot,\n            viewport: input.viewport,\n            updatedAt,\n          };\n          return {\n            next: { ...session, snapshot },\n            emit: {\n              type: \"resized\",\n              threadId: session.threadId,\n              tabId: session.tabId,\n              createdAt: snapshot.updatedAt,\n              snapshot,\n            },\n            result: snapshot,\n          };\n        }),\n      );\n    },\n  );\n\n  const refresh: PreviewManager[\"Service\"][\"refresh\"] = Effect.fn(\"PreviewManager.refresh\")(\n    function* (input) {\n      // Verify the session exists; the desktop bridge handles the actual reload\n      // and will report progress back via `reportStatus`. No event emitted.\n      yield* mutateExistingSession(input.threadId, input.tabId, (session) =>\n        Effect.succeed({ next: session, emit: null, result: undefined as void }),\n      );\n    },\n  );\n\n  const close: PreviewManager[\"Service\"][\"close\"] = Effect.fn(\"PreviewManager.close\")(\n    function* (input) {\n      const createdAt = yield* currentIsoTimestamp;\n      yield* SynchronizedRef.modifyEffect(stateRef, (state) => {\n        const eventsToEmit: PreviewEvent[] = [];\n        const sessions = new Map(state.sessions);\n        const targets = input.tabId\n          ? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(\n              (entry): entry is PreviewSessionState => entry !== undefined,\n            )\n          : sessionsForThread(state, input.threadId);\n        let revision = state.revision;\n        for (const target of targets) {\n          revision += 1;\n          sessions.delete(compositeKey(target.threadId, target.tabId));\n          eventsToEmit.push({\n            type: \"closed\",\n            threadId: target.threadId,\n            tabId: target.tabId,\n            createdAt,\n            serverEpoch,\n            revision,\n          });\n        }\n        if (eventsToEmit.length === 0) {\n          return Effect.succeed([undefined, state] as const);\n        }\n        return Effect.as(\n          Effect.forEach(eventsToEmit, (event) => PubSub.publish(eventsPubSub, event), {\n            discard: true,\n          }),\n          [undefined, { sessions, revision }] as const,\n        );\n      });\n    },\n  );\n\n  const list: PreviewManager[\"Service\"][\"list\"] = Effect.fn(\"PreviewManager.list\")(\n    function* (input) {\n      return yield* SynchronizedRef.get(stateRef).pipe(\n        Effect.map(\n          (state): PreviewListResult => ({\n            sessions: sessionsForThread(state, input.threadId)\n              .map((s) => s.snapshot)\n              .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),\n            serverEpoch,\n            revision: state.revision,\n          }),\n        ),\n      );\n    },\n  );\n\n  return PreviewManager.of({\n    open,\n    navigate,\n    reportStatus,\n    resize,\n    refresh,\n    close,\n    list,\n    events,\n    subscribeEvents: PubSub.subscribe(eventsPubSub),\n  });\n}).pipe(Effect.withSpan(\"PreviewManager.make\"));\n\nexport const layer = Layer.effect(PreviewManager, make);\n","export type RankedSearchResult<T> = {\n  item: T;\n  score: number;\n  tieBreaker: string;\n};\n\nexport function normalizeSearchQuery(\n  input: string,\n  options?: {\n    trimLeadingPattern?: RegExp;\n  },\n): string {\n  const trimmed = input.trim();\n  if (!trimmed) {\n    return \"\";\n  }\n  return options?.trimLeadingPattern\n    ? trimmed.replace(options.trimLeadingPattern, \"\").toLowerCase()\n    : trimmed.toLowerCase();\n}\n\nexport function scoreSubsequenceMatch(value: string, query: string): number | null {\n  if (!query) return 0;\n\n  let queryIndex = 0;\n  let firstMatchIndex = -1;\n  let previousMatchIndex = -1;\n  let gapPenalty = 0;\n\n  for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {\n    if (value[valueIndex] !== query[queryIndex]) {\n      continue;\n    }\n\n    if (firstMatchIndex === -1) {\n      firstMatchIndex = valueIndex;\n    }\n    if (previousMatchIndex !== -1) {\n      gapPenalty += valueIndex - previousMatchIndex - 1;\n    }\n\n    previousMatchIndex = valueIndex;\n    queryIndex += 1;\n    if (queryIndex === query.length) {\n      const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;\n      const lengthPenalty = Math.min(64, value.length - query.length);\n      return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;\n    }\n  }\n\n  return null;\n}\n\nfunction lengthPenalty(value: string, query: string): number {\n  return Math.min(64, Math.max(0, value.length - query.length));\n}\n\nfunction findBoundaryMatchIndex(\n  value: string,\n  query: string,\n  boundaryMarkers: readonly string[],\n): number | null {\n  let bestIndex: number | null = null;\n\n  for (const marker of boundaryMarkers) {\n    const index = value.indexOf(`${marker}${query}`);\n    if (index === -1) {\n      continue;\n    }\n\n    const matchIndex = index + marker.length;\n    if (bestIndex === null || matchIndex < bestIndex) {\n      bestIndex = matchIndex;\n    }\n  }\n\n  return bestIndex;\n}\n\n/**\n * Scores how well `value` matches `query` using tiered match strategies.\n *\n * **Expects pre-normalized inputs**: both `value` and `query` must already be\n * trimmed and lowercased (e.g. via {@link normalizeSearchQuery}).\n */\nexport function scoreQueryMatch(input: {\n  value: string;\n  query: string;\n  exactBase: number;\n  prefixBase?: number;\n  boundaryBase?: number;\n  includesBase?: number;\n  fuzzyBase?: number;\n  boundaryMarkers?: readonly string[];\n}): number | null {\n  const { value, query } = input;\n\n  if (!value || !query) {\n    return null;\n  }\n\n  if (value === query) {\n    return input.exactBase;\n  }\n\n  if (input.prefixBase !== undefined && value.startsWith(query)) {\n    return input.prefixBase + lengthPenalty(value, query);\n  }\n\n  if (input.boundaryBase !== undefined) {\n    const boundaryIndex = findBoundaryMatchIndex(\n      value,\n      query,\n      input.boundaryMarkers ?? [\" \", \"-\", \"_\", \"/\"],\n    );\n    if (boundaryIndex !== null) {\n      return input.boundaryBase + boundaryIndex * 2 + lengthPenalty(value, query);\n    }\n  }\n\n  if (input.includesBase !== undefined) {\n    const includesIndex = value.indexOf(query);\n    if (includesIndex !== -1) {\n      return input.includesBase + includesIndex * 2 + lengthPenalty(value, query);\n    }\n  }\n\n  if (input.fuzzyBase !== undefined) {\n    const fuzzyScore = scoreSubsequenceMatch(value, query);\n    if (fuzzyScore !== null) {\n      return input.fuzzyBase + fuzzyScore;\n    }\n  }\n\n  return null;\n}\n\nexport function compareRankedSearchResults<T>(\n  left: RankedSearchResult<T>,\n  right: RankedSearchResult<T>,\n): number {\n  const scoreDelta = left.score - right.score;\n  if (scoreDelta !== 0) return scoreDelta;\n  return left.tieBreaker.localeCompare(right.tieBreaker);\n}\n\nfunction findInsertionIndex<T>(\n  rankedEntries: RankedSearchResult<T>[],\n  candidate: RankedSearchResult<T>,\n): number {\n  let low = 0;\n  let high = rankedEntries.length;\n\n  while (low < high) {\n    const middle = low + Math.floor((high - low) / 2);\n    const current = rankedEntries[middle];\n    if (!current) {\n      break;\n    }\n\n    if (compareRankedSearchResults(candidate, current) < 0) {\n      high = middle;\n    } else {\n      low = middle + 1;\n    }\n  }\n\n  return low;\n}\n\nexport function insertRankedSearchResult<T>(\n  rankedEntries: RankedSearchResult<T>[],\n  candidate: RankedSearchResult<T>,\n  limit: number,\n): void {\n  if (limit <= 0) {\n    return;\n  }\n\n  const insertionIndex = findInsertionIndex(rankedEntries, candidate);\n  if (rankedEntries.length < limit) {\n    rankedEntries.splice(insertionIndex, 0, candidate);\n    return;\n  }\n\n  if (insertionIndex >= limit) {\n    return;\n  }\n\n  rankedEntries.splice(insertionIndex, 0, candidate);\n  rankedEntries.pop();\n}\n","import {\n  type DirItem,\n  type DirSearchResult,\n  type FileItem,\n  FileFinder,\n  type GrepCursor,\n  type MixedItem,\n  type MixedSearchResult,\n  type Result,\n  type SearchResult,\n} from \"@ff-labs/fff-node\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as LayerMap from \"effect/LayerMap\";\nimport * as Schema from \"effect/Schema\";\n\nimport type {\n  ProjectEntry,\n  ProjectEntryKind,\n  ProjectListEntriesResult,\n  ProjectSearchContentsInput,\n  ProjectSearchContentsResult,\n  ProjectSearchEntriesResult,\n} from \"@t3tools/contracts\";\n\nconst WORKSPACE_INDEX_MAX_ENTRIES = 25_000;\nconst WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2;\nconst WORKSPACE_INDEX_SCAN_TIMEOUT = \"15 seconds\";\nconst WORKSPACE_INDEX_SCAN_TIMEOUT_MS = 15_000;\nconst WORKSPACE_INDEX_IDLE_TTL = \"15 minutes\";\nconst CONTENT_SEARCH_TIME_BUDGET_MS = 250;\nconst CONTENT_SEARCH_MAX_MATCHES_PER_FILE = 100;\n\nexport class WorkspaceSearchIndexCreateFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexCreateFailed>()(\n  \"WorkspaceSearchIndexCreateFailed\",\n  {\n    cwd: Schema.String,\n    reason: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Failed to create the workspace search index for '${this.cwd}'.`;\n  }\n}\n\nexport class WorkspaceSearchIndexScanTimedOut extends Schema.TaggedErrorClass<WorkspaceSearchIndexScanTimedOut>()(\n  \"WorkspaceSearchIndexScanTimedOut\",\n  {\n    cwd: Schema.String,\n    timeout: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace search index for '${this.cwd}' did not finish scanning within ${this.timeout}`;\n  }\n}\n\nexport class WorkspaceSearchIndexSearchFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexSearchFailed>()(\n  \"WorkspaceSearchIndexSearchFailed\",\n  {\n    cwd: Schema.String,\n    queryLength: Schema.Number,\n    pageSize: Schema.Number,\n    reason: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Workspace search failed for '${this.cwd}'.`;\n  }\n}\n\nexport class WorkspaceSearchIndexRefreshFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexRefreshFailed>()(\n  \"WorkspaceSearchIndexRefreshFailed\",\n  {\n    cwd: Schema.String,\n    reason: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Failed to refresh the workspace search index for '${this.cwd}'.`;\n  }\n}\n\nexport class WorkspaceSearchIndexDestroyFailed extends Schema.TaggedErrorClass<WorkspaceSearchIndexDestroyFailed>()(\n  \"WorkspaceSearchIndexDestroyFailed\",\n  {\n    cwd: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to destroy the workspace search index for '${this.cwd}'.`;\n  }\n}\n\nexport type WorkspaceSearchIndexError =\n  | WorkspaceSearchIndexCreateFailed\n  | WorkspaceSearchIndexScanTimedOut\n  | WorkspaceSearchIndexSearchFailed\n  | WorkspaceSearchIndexRefreshFailed;\n\nexport class WorkspaceSearchIndex extends Context.Service<\n  WorkspaceSearchIndex,\n  {\n    readonly list: () => Effect.Effect<ProjectListEntriesResult, WorkspaceSearchIndexSearchFailed>;\n    readonly search: (\n      query: string,\n      limit: number,\n      kind?: ProjectEntryKind,\n    ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceSearchIndexSearchFailed>;\n    readonly searchContents: (\n      input: Omit<ProjectSearchContentsInput, \"cwd\">,\n    ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceSearchIndexSearchFailed>;\n    readonly refresh: () => Effect.Effect<\n      void,\n      WorkspaceSearchIndexRefreshFailed | WorkspaceSearchIndexScanTimedOut\n    >;\n  }\n>()(\"t3/workspace/WorkspaceSearchIndex\") {}\n\nfunction toPosixPath(input: string): string {\n  return input.replaceAll(\"\\\\\", \"/\");\n}\n\nfunction trimDirectorySeparator(input: string): string {\n  return input.endsWith(\"/\") ? input.slice(0, -1) : input;\n}\n\nfunction parentPathOf(input: string): string | undefined {\n  const separatorIndex = input.lastIndexOf(\"/\");\n  return separatorIndex === -1 ? undefined : input.slice(0, separatorIndex);\n}\n\nfunction toProjectEntry(item: MixedItem): ProjectEntry | null {\n  const normalizedPath = trimDirectorySeparator(toPosixPath(item.item.relativePath));\n  if (!normalizedPath) {\n    return null;\n  }\n\n  return {\n    path: normalizedPath,\n    kind: item.type,\n  };\n}\n\nfunction toFileEntry(item: FileItem): ProjectEntry | null {\n  const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));\n  return normalizedPath ? { path: normalizedPath, kind: \"file\" } : null;\n}\n\nfunction toDirectoryEntry(item: DirItem): ProjectEntry | null {\n  const normalizedPath = trimDirectorySeparator(toPosixPath(item.relativePath));\n  return normalizedPath ? { path: normalizedPath, kind: \"directory\" } : null;\n}\n\nfunction mapFileSearchResult(result: SearchResult, limit: number): ProjectSearchEntriesResult {\n  return {\n    entries: result.items\n      .flatMap((item) => {\n        const entry = toFileEntry(item);\n        return entry ? [entry] : [];\n      })\n      .slice(0, limit),\n    truncated: result.totalMatched > limit,\n  };\n}\n\nfunction mapDirectorySearchResult(\n  result: DirSearchResult,\n  limit: number,\n): ProjectSearchEntriesResult {\n  const entries = result.items.flatMap((item) => {\n    const entry = toDirectoryEntry(item);\n    return entry ? [entry] : [];\n  });\n  const rootDirectoryCount = result.items.some((item) => item.relativePath.length === 0) ? 1 : 0;\n  return {\n    entries: entries.slice(0, limit),\n    truncated: result.totalMatched - rootDirectoryCount > limit,\n  };\n}\n\nfunction mapMixedSearchResult(\n  result: MixedSearchResult,\n  limit: number,\n): { readonly entries: ProjectEntry[]; readonly truncated: boolean } {\n  const entries: ProjectEntry[] = [];\n  for (const item of result.items) {\n    const entry = toProjectEntry(item);\n    if (entry) {\n      entries.push(entry);\n    }\n    if (entries.length >= limit) {\n      break;\n    }\n  }\n\n  const rootDirectoryCount = result.items.some(\n    (item) => item.type === \"directory\" && item.item.relativePath.length === 0,\n  )\n    ? 1\n    : 0;\n  return {\n    entries,\n    truncated: result.totalMatched - rootDirectoryCount > limit,\n  };\n}\n\nconst WORD_CHARACTER = /[\\p{Letter}\\p{Mark}\\p{Number}_]/u;\n\nfunction codePointAt(line: string, index: number): string | undefined {\n  const codePoint = line.codePointAt(index);\n  return codePoint === undefined ? undefined : String.fromCodePoint(codePoint);\n}\n\nfunction codePointBefore(line: string, index: number): string | undefined {\n  if (index <= 0) return undefined;\n  const previousCodeUnit = line.charCodeAt(index - 1);\n  const previousIndex =\n    previousCodeUnit >= 0xdc00 && previousCodeUnit <= 0xdfff ? index - 2 : index - 1;\n  return codePointAt(line, previousIndex);\n}\n\nfunction buildContentSearchQuery(input: Omit<ProjectSearchContentsInput, \"cwd\">): {\n  readonly searchQuery: string;\n  readonly regexMode: boolean;\n} {\n  if (input.caseSensitive) {\n    return { searchQuery: input.query, regexMode: input.useRegex };\n  }\n  // Plain mode relies on smart case: an all-lowercase needle matches\n  // case-insensitively. Regex mode needs an explicit inline flag instead.\n  return input.useRegex\n    ? { searchQuery: `(?i)${input.query}`, regexMode: true }\n    : { searchQuery: input.query.toLowerCase(), regexMode: false };\n}\n\nfunction mapContentMatchRanges(\n  line: string,\n  byteRanges: ReadonlyArray<readonly [number, number]>,\n): Array<{ readonly start: number; readonly end: number }> {\n  const lineBytes = Buffer.from(line);\n  const toStringIndex = (byteOffset: number) => lineBytes.subarray(0, byteOffset).toString().length;\n  return byteRanges.map(([startByte, endByte]) => ({\n    start: toStringIndex(startByte),\n    end: toStringIndex(endByte),\n  }));\n}\n\n/**\n * Whole-word filtering happens after the grep rather than by wrapping the\n * pattern in boundary regex: consuming boundaries such as `(?:^|\\W)` swallow\n * the separator between adjacent matches and widen the reported ranges, and\n * `\\b` cannot match punctuation-edged queries at all. Matching VS Code, a\n * match edge is a word boundary when it touches the line edge, the\n * neighbouring character is not a word character, or the match's own edge\n * character is not a word character.\n */\nfunction isWholeWordRange(\n  line: string,\n  range: { readonly start: number; readonly end: number },\n): boolean {\n  if (range.end <= range.start) return false;\n  const isWord = (character: string | undefined) =>\n    character !== undefined && WORD_CHARACTER.test(character);\n  const leftIsBoundary =\n    range.start === 0 ||\n    !isWord(codePointBefore(line, range.start)) ||\n    !isWord(codePointAt(line, range.start));\n  const rightIsBoundary =\n    range.end >= line.length ||\n    !isWord(codePointAt(line, range.end)) ||\n    !isWord(codePointBefore(line, range.end));\n  return leftIsBoundary && rightIsBoundary;\n}\n\nfunction withDirectoryAncestors(entries: ReadonlyArray<ProjectEntry>): ProjectEntry[] {\n  const entryByPath = new Map(entries.map((entry) => [entry.path, entry]));\n  for (const entry of entries) {\n    let parentPath = parentPathOf(entry.path);\n    while (parentPath) {\n      if (!entryByPath.has(parentPath)) {\n        entryByPath.set(parentPath, { path: parentPath, kind: \"directory\" });\n      }\n      parentPath = parentPathOf(parentPath);\n    }\n  }\n  return [...entryByPath.values()];\n}\n\nconst createFinder = Effect.fn(\"WorkspaceSearchIndex.createFinder\")(function* (\n  cwd: string,\n  variant: WorkspaceSearchIndexVariant,\n) {\n  const result = yield* Effect.try({\n    try: () =>\n      FileFinder.create({\n        basePath: cwd,\n        disableMmapCache: true,\n        // Content indexing costs scan CPU and memory, so only the on-demand\n        // content-search index pays for it; path-only consumers (file tree,\n        // composer path search, file picker) keep the lightweight index.\n        disableContentIndexing: variant !== \"content\",\n        aiMode: false,\n        enableFsRootScanning: true,\n        enableHomeDirScanning: true,\n      }),\n    catch: (cause) =>\n      new WorkspaceSearchIndexCreateFailed({\n        cwd,\n        reason: \"FileFinder.create threw unexpectedly.\",\n        cause,\n      }),\n  });\n  if (result.ok) return result.value;\n  return yield* new WorkspaceSearchIndexCreateFailed({\n    cwd,\n    reason: result.error,\n  });\n});\n\nconst waitForIndexReady = Effect.fn(\"WorkspaceSearchIndex.waitForIndexReady\")(function* <E>(\n  cwd: string,\n  finder: FileFinder,\n  onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E,\n): Effect.fn.Return<void, E | WorkspaceSearchIndexScanTimedOut> {\n  const result = yield* Effect.tryPromise({\n    try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS),\n    catch: (cause) =>\n      onFailure({\n        reason: \"FileFinder.waitForIndexReady rejected unexpectedly.\",\n        cause,\n      }),\n  });\n  if (!result.ok) {\n    return yield* Effect.fail(onFailure({ reason: result.error }));\n  }\n  if (!result.value) {\n    return yield* new WorkspaceSearchIndexScanTimedOut({\n      cwd,\n      timeout: WORKSPACE_INDEX_SCAN_TIMEOUT,\n    });\n  }\n});\n\nexport const make = Effect.fn(\"WorkspaceSearchIndex.make\")(function* (\n  cwd: string,\n  variant: WorkspaceSearchIndexVariant = \"paths\",\n) {\n  const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) =>\n    Effect.try({\n      try: () => finder.destroy(),\n      catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }),\n    }).pipe(Effect.orDie),\n  );\n  yield* waitForIndexReady(\n    cwd,\n    finder,\n    ({ reason, cause }) =>\n      new WorkspaceSearchIndexCreateFailed({\n        cwd,\n        reason,\n        cause,\n      }),\n  );\n\n  const runSearch = Effect.fn(\"WorkspaceSearchIndex.runSearch\")(function* <A>(\n    query: string,\n    pageSize: number,\n    operation: \"directorySearch\" | \"fileSearch\" | \"grep\" | \"mixedSearch\",\n    execute: () => Result<A>,\n  ): Effect.fn.Return<A, WorkspaceSearchIndexSearchFailed> {\n    const result = yield* Effect.try({\n      try: execute,\n      catch: (cause) =>\n        new WorkspaceSearchIndexSearchFailed({\n          cwd,\n          queryLength: query.length,\n          pageSize,\n          reason: `FileFinder.${operation} threw unexpectedly.`,\n          cause,\n        }),\n    });\n    if (!result.ok) {\n      return yield* new WorkspaceSearchIndexSearchFailed({\n        cwd,\n        queryLength: query.length,\n        pageSize,\n        reason: result.error,\n      });\n    }\n    return result.value;\n  });\n\n  const refresh: WorkspaceSearchIndex[\"Service\"][\"refresh\"] = Effect.fn(\n    \"WorkspaceSearchIndex.refresh\",\n  )(function* () {\n    const result = yield* Effect.try({\n      try: () => finder.scanFiles(),\n      catch: (cause) =>\n        new WorkspaceSearchIndexRefreshFailed({\n          cwd,\n          reason: \"FileFinder.scanFiles threw unexpectedly.\",\n          cause,\n        }),\n    });\n    if (!result.ok) {\n      return yield* new WorkspaceSearchIndexRefreshFailed({\n        cwd,\n        reason: result.error,\n      });\n    }\n    yield* waitForIndexReady(\n      cwd,\n      finder,\n      ({ reason, cause }) =>\n        new WorkspaceSearchIndexRefreshFailed({\n          cwd,\n          reason,\n          cause,\n        }),\n    );\n  });\n\n  const list: WorkspaceSearchIndex[\"Service\"][\"list\"] = Effect.fn(\"WorkspaceSearchIndex.list\")(\n    function* () {\n      const result = yield* runSearch(\"\", WORKSPACE_INDEX_PAGE_SIZE, \"mixedSearch\", () =>\n        finder.mixedSearch(\"\", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }),\n      );\n      const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES);\n      const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) =>\n        left.path.localeCompare(right.path),\n      );\n      const entries = sortedEntries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES);\n      return {\n        entries,\n        truncated: mapped.truncated || entries.length < sortedEntries.length,\n      };\n    },\n  );\n\n  const search: WorkspaceSearchIndex[\"Service\"][\"search\"] = Effect.fn(\n    \"WorkspaceSearchIndex.search\",\n  )(function* (query, limit, kind) {\n    const pageSize = Math.max(1, limit + 1);\n    if (kind === \"file\") {\n      const result = yield* runSearch(query, pageSize, \"fileSearch\", () =>\n        finder.fileSearch(query, { pageSize }),\n      );\n      return mapFileSearchResult(result, limit);\n    }\n    if (kind === \"directory\") {\n      const result = yield* runSearch(query, pageSize, \"directorySearch\", () =>\n        finder.directorySearch(query, { pageSize }),\n      );\n      return mapDirectorySearchResult(result, limit);\n    }\n    const result = yield* runSearch(query, pageSize, \"mixedSearch\", () =>\n      finder.mixedSearch(query, { pageSize }),\n    );\n    return mapMixedSearchResult(result, limit);\n  });\n\n  const searchContents: WorkspaceSearchIndex[\"Service\"][\"searchContents\"] = Effect.fn(\n    \"WorkspaceSearchIndex.searchContents\",\n  )(function* (input) {\n    const { searchQuery, regexMode } = buildContentSearchQuery(input);\n    const deadline = performance.now() + CONTENT_SEARCH_TIME_BUDGET_MS;\n    // Grep cursors advance by file, so whole-word post-filtering needs enough\n    // raw candidates from the current file before moving to the next one.\n    const rawPageSize = input.wholeWord\n      ? Math.max(input.limit, CONTENT_SEARCH_MAX_MATCHES_PER_FILE)\n      : input.limit;\n    const matches: Array<ProjectSearchContentsResult[\"matches\"][number]> = [];\n    let nextCursor: GrepCursor | null = null;\n    let regexFallbackError: string | undefined;\n\n    do {\n      const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now()));\n      const result = yield* runSearch(input.query, input.limit, \"grep\", () =>\n        finder.grep(searchQuery, {\n          mode: regexMode ? \"regex\" : \"plain\",\n          smartCase: !input.caseSensitive && !regexMode,\n          // A single dense file must not consume the whole result page.\n          maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize),\n          pageSize: rawPageSize,\n          cursor: nextCursor,\n          timeBudgetMs: remainingTimeBudgetMs,\n        }),\n      );\n\n      for (const match of result.items) {\n        const matchRanges = mapContentMatchRanges(match.lineContent, match.matchRanges).filter(\n          (range) => !input.wholeWord || isWholeWordRange(match.lineContent, range),\n        );\n        if (matchRanges.length === 0) continue;\n        matches.push({\n          path: toPosixPath(match.relativePath),\n          lineNumber: match.lineNumber,\n          lineContent: match.lineContent,\n          matchRanges,\n        });\n      }\n      nextCursor = result.nextCursor;\n      regexFallbackError ??= result.regexFallbackError;\n    } while (matches.length < input.limit && nextCursor !== null && performance.now() < deadline);\n\n    return {\n      matches: matches.slice(0, input.limit),\n      truncated: matches.length > input.limit || nextCursor !== null,\n      ...(regexFallbackError !== undefined ? { regexFallbackError } : {}),\n    };\n  });\n\n  return WorkspaceSearchIndex.of({ list, refresh, search, searchContents });\n});\n\nexport const WORKSPACE_SEARCH_INDEX_VARIANTS = [\"paths\", \"content\"] as const;\nexport type WorkspaceSearchIndexVariant = (typeof WORKSPACE_SEARCH_INDEX_VARIANTS)[number];\n\n/**\n * Composite LayerMap key so the lightweight path index and the on-demand\n * content-search index of the same workspace are separate resources with\n * independent lifecycles. \"\\n\" cannot appear in a filesystem path.\n */\nexport const workspaceSearchIndexKey = (cwd: string, variant: WorkspaceSearchIndexVariant) =>\n  `${variant}\\n${cwd}`;\n\nfunction parseWorkspaceSearchIndexKey(key: string): {\n  readonly cwd: string;\n  readonly variant: WorkspaceSearchIndexVariant;\n} {\n  const separatorIndex = key.indexOf(\"\\n\");\n  return {\n    variant: key.slice(0, separatorIndex) as WorkspaceSearchIndexVariant,\n    cwd: key.slice(separatorIndex + 1),\n  };\n}\n\n/**\n * A layer factory is required because every index is scoped to a concrete\n * workspace root and variant. WorkspaceSearchIndexMap owns memoization and\n * idle cleanup; using a default cwd here would mix resources from different\n * workspaces.\n */\nexport const layer = (key: string) => {\n  const { cwd, variant } = parseWorkspaceSearchIndexKey(key);\n  return Layer.effect(WorkspaceSearchIndex, make(cwd, variant));\n};\n\nexport class WorkspaceSearchIndexMap extends LayerMap.Service<WorkspaceSearchIndexMap>()(\n  \"t3/workspace/WorkspaceSearchIndexMap\",\n  {\n    lookup: layer,\n    idleTimeToLive: WORKSPACE_INDEX_IDLE_TTL,\n  },\n) {}\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFSP from \"node:fs/promises\";\nimport * as NodeOS from \"node:os\";\n\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as RcMap from \"effect/RcMap\";\nimport * as Schema from \"effect/Schema\";\n\nimport type {\n  FilesystemBrowseInput,\n  FilesystemBrowseResult,\n  ProjectListEntriesInput,\n  ProjectListEntriesResult,\n  ProjectSearchContentsInput,\n  ProjectSearchContentsResult,\n  ProjectSearchEntriesInput,\n  ProjectSearchEntriesResult,\n} from \"@t3tools/contracts\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { isExplicitRelativePath, isWindowsAbsolutePath } from \"@t3tools/shared/path\";\nimport { normalizeSearchQuery } from \"@t3tools/shared/searchRanking\";\n\nimport * as WorkspacePaths from \"./WorkspacePaths.ts\";\nimport * as WorkspaceSearchIndex from \"./WorkspaceSearchIndex.ts\";\n\nexport class WorkspaceEntriesWindowsPathUnsupportedError extends Schema.TaggedErrorClass<WorkspaceEntriesWindowsPathUnsupportedError>()(\n  \"WorkspaceEntriesWindowsPathUnsupportedError\",\n  {\n    cwd: Schema.optional(Schema.String),\n    partialPath: Schema.String,\n    platform: Schema.String,\n  },\n) {\n  override get message(): string {\n    const cwd = this.cwd ? ` from '${this.cwd}'` : \"\";\n    return `Windows-style workspace path '${this.partialPath}' is not supported on '${this.platform}'${cwd}.`;\n  }\n}\n\nexport class WorkspaceEntriesCurrentProjectRequiredError extends Schema.TaggedErrorClass<WorkspaceEntriesCurrentProjectRequiredError>()(\n  \"WorkspaceEntriesCurrentProjectRequiredError\",\n  {\n    partialPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `A current project is required to browse relative workspace path '${this.partialPath}'.`;\n  }\n}\n\nexport class WorkspaceEntriesReadDirectoryError extends Schema.TaggedErrorClass<WorkspaceEntriesReadDirectoryError>()(\n  \"WorkspaceEntriesReadDirectoryError\",\n  {\n    cwd: Schema.optional(Schema.String),\n    partialPath: Schema.String,\n    parentPath: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    const cwd = this.cwd ? ` from '${this.cwd}'` : \"\";\n    return `Failed to read workspace directory '${this.parentPath}' while browsing '${this.partialPath}'${cwd}.`;\n  }\n}\n\nexport const WorkspaceEntriesBrowseError = Schema.Union([\n  WorkspaceEntriesWindowsPathUnsupportedError,\n  WorkspaceEntriesCurrentProjectRequiredError,\n  WorkspaceEntriesReadDirectoryError,\n]);\nexport type WorkspaceEntriesBrowseError = typeof WorkspaceEntriesBrowseError.Type;\n\nexport const WorkspaceEntriesError = Schema.Union([\n  WorkspacePaths.WorkspaceRootNotExistsError,\n  WorkspacePaths.WorkspaceRootCreateFailedError,\n  WorkspacePaths.WorkspaceRootStatFailedError,\n  WorkspacePaths.WorkspaceRootNotDirectoryError,\n  WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed,\n  WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut,\n  WorkspaceSearchIndex.WorkspaceSearchIndexSearchFailed,\n]);\nexport type WorkspaceEntriesError = typeof WorkspaceEntriesError.Type;\n\nexport class WorkspaceEntries extends Context.Service<\n  WorkspaceEntries,\n  {\n    readonly browse: (\n      input: FilesystemBrowseInput,\n    ) => Effect.Effect<FilesystemBrowseResult, WorkspaceEntriesBrowseError>;\n    readonly list: (\n      input: ProjectListEntriesInput,\n    ) => Effect.Effect<ProjectListEntriesResult, WorkspaceEntriesError>;\n    readonly search: (\n      input: ProjectSearchEntriesInput,\n    ) => Effect.Effect<ProjectSearchEntriesResult, WorkspaceEntriesError>;\n    readonly searchContents: (\n      input: ProjectSearchContentsInput,\n    ) => Effect.Effect<ProjectSearchContentsResult, WorkspaceEntriesError>;\n    readonly refresh: (cwd: string) => Effect.Effect<void>;\n  }\n>()(\"t3/workspace/WorkspaceEntries\") {}\n\nfunction expandHomePath(input: string, path: Path.Path): string {\n  if (input === \"~\") {\n    return NodeOS.homedir();\n  }\n  if (input.startsWith(\"~/\") || input.startsWith(\"~\\\\\")) {\n    return path.join(NodeOS.homedir(), input.slice(2));\n  }\n  return input;\n}\n\nconst resolveBrowseTarget = Effect.fn(\"WorkspaceEntries.resolveBrowseTarget\")(function* (\n  input: FilesystemBrowseInput,\n  path: Path.Path,\n): Effect.fn.Return<string, WorkspaceEntriesBrowseError> {\n  const platform = yield* HostProcessPlatform;\n  if (platform !== \"win32\" && isWindowsAbsolutePath(input.partialPath)) {\n    return yield* new WorkspaceEntriesWindowsPathUnsupportedError({\n      cwd: input.cwd,\n      partialPath: input.partialPath,\n      platform,\n    });\n  }\n\n  if (!isExplicitRelativePath(input.partialPath)) {\n    return path.resolve(expandHomePath(input.partialPath, path));\n  }\n\n  if (!input.cwd) {\n    return yield* new WorkspaceEntriesCurrentProjectRequiredError({\n      partialPath: input.partialPath,\n    });\n  }\n  return path.resolve(expandHomePath(input.cwd, path), input.partialPath);\n});\n\nexport const make = Effect.gen(function* () {\n  const path = yield* Path.Path;\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  const workspaceSearchIndexes = yield* WorkspaceSearchIndex.WorkspaceSearchIndexMap;\n\n  const normalizeWorkspaceRoot = Effect.fn(\"WorkspaceEntries.normalizeWorkspaceRoot\")(function* (\n    cwd: string,\n  ): Effect.fn.Return<string, WorkspaceEntriesError> {\n    return yield* workspacePaths.normalizeWorkspaceRoot(cwd);\n  });\n\n  const refresh: WorkspaceEntries[\"Service\"][\"refresh\"] = Effect.fn(\"WorkspaceEntries.refresh\")(\n    function* (cwd) {\n      const normalizedCwd = yield* normalizeWorkspaceRoot(cwd).pipe(\n        Effect.orElseSucceed(() => cwd),\n      );\n      for (const variant of WorkspaceSearchIndex.WORKSPACE_SEARCH_INDEX_VARIANTS) {\n        const indexKey = WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, variant);\n        if (!(yield* RcMap.has(workspaceSearchIndexes.rcMap, indexKey))) {\n          continue;\n        }\n        const recoverRefreshFailure = (\n          cause:\n            | WorkspaceSearchIndex.WorkspaceSearchIndexCreateFailed\n            | WorkspaceSearchIndex.WorkspaceSearchIndexScanTimedOut\n            | WorkspaceSearchIndex.WorkspaceSearchIndexRefreshFailed,\n        ) =>\n          Effect.gen(function* () {\n            yield* Effect.logWarning(\"Failed to refresh workspace search index\", {\n              cwd,\n              variant,\n              cause,\n            });\n            yield* workspaceSearchIndexes.invalidate(indexKey);\n          });\n        yield* Effect.gen(function* () {\n          const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;\n          yield* searchIndex.refresh();\n        }).pipe(\n          Effect.provide(workspaceSearchIndexes.get(indexKey)),\n          Effect.catchTags({\n            WorkspaceSearchIndexCreateFailed: recoverRefreshFailure,\n            WorkspaceSearchIndexScanTimedOut: recoverRefreshFailure,\n            WorkspaceSearchIndexRefreshFailed: recoverRefreshFailure,\n          }),\n        );\n      }\n    },\n  );\n\n  const browse: WorkspaceEntries[\"Service\"][\"browse\"] = Effect.fn(\"WorkspaceEntries.browse\")(\n    function* (input) {\n      const resolvedInputPath = yield* resolveBrowseTarget(input, path);\n      const endsWithSeparator = /[\\\\/]$/.test(input.partialPath) || input.partialPath === \"~\";\n      const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);\n      const prefix = endsWithSeparator ? \"\" : path.basename(resolvedInputPath);\n\n      const dirents = yield* Effect.tryPromise({\n        try: () => NodeFSP.readdir(parentPath, { withFileTypes: true }),\n        catch: (cause) =>\n          new WorkspaceEntriesReadDirectoryError({\n            cwd: input.cwd,\n            partialPath: input.partialPath,\n            parentPath,\n            cause,\n          }),\n      }).pipe(\n        Effect.catchIf(\n          (error) => {\n            const code = (error.cause as NodeJS.ErrnoException | undefined)?.code;\n            return code === \"EACCES\" || code === \"EPERM\";\n          },\n          () => Effect.succeed([]),\n        ),\n      );\n\n      const showHidden = endsWithSeparator || prefix.startsWith(\".\");\n      const lowerPrefix = prefix.toLowerCase();\n      const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];\n      for (const dirent of dirents) {\n        if (\n          dirent.isDirectory() &&\n          dirent.name.toLowerCase().startsWith(lowerPrefix) &&\n          (showHidden || !dirent.name.startsWith(\".\"))\n        ) {\n          entries.push({\n            name: dirent.name,\n            fullPath: path.join(parentPath, dirent.name),\n          });\n        }\n      }\n\n      return {\n        parentPath,\n        entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),\n      };\n    },\n  );\n\n  const search: WorkspaceEntries[\"Service\"][\"search\"] = Effect.fn(\"WorkspaceEntries.search\")(\n    function* (input) {\n      const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);\n      const normalizedQuery = normalizeSearchQuery(input.query, {\n        trimLeadingPattern: /^[@./]+/,\n      });\n      return yield* Effect.gen(function* () {\n        const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;\n        return yield* searchIndex.search(normalizedQuery, input.limit, input.kind);\n      }).pipe(\n        Effect.provide(\n          workspaceSearchIndexes.get(\n            WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, \"paths\"),\n          ),\n        ),\n      );\n    },\n  );\n\n  const searchContents: WorkspaceEntries[\"Service\"][\"searchContents\"] = Effect.fn(\n    \"WorkspaceEntries.searchContents\",\n  )(function* (input) {\n    const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);\n    return yield* Effect.gen(function* () {\n      const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;\n      return yield* searchIndex.searchContents(input);\n    }).pipe(\n      Effect.provide(\n        workspaceSearchIndexes.get(\n          WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, \"content\"),\n        ),\n      ),\n    );\n  });\n\n  const list: WorkspaceEntries[\"Service\"][\"list\"] = Effect.fn(\"WorkspaceEntries.list\")(\n    function* (input) {\n      const normalizedCwd = yield* normalizeWorkspaceRoot(input.cwd);\n      return yield* Effect.gen(function* () {\n        const searchIndex = yield* WorkspaceSearchIndex.WorkspaceSearchIndex;\n        return yield* searchIndex.list();\n      }).pipe(\n        Effect.provide(\n          workspaceSearchIndexes.get(\n            WorkspaceSearchIndex.workspaceSearchIndexKey(normalizedCwd, \"paths\"),\n          ),\n        ),\n      );\n    },\n  );\n\n  return WorkspaceEntries.of({ browse, list, refresh, search, searchContents });\n});\n\nexport const layer = Layer.effect(WorkspaceEntries, make).pipe(\n  Layer.provide(WorkspaceSearchIndex.WorkspaceSearchIndexMap.layer),\n);\n","// @effect-diagnostics nodeBuiltinImport:off\n/**\n * WorkspaceFileSystem - Effect service contract for workspace file mutations.\n *\n * Owns workspace-root-relative file read/write operations and their associated\n * safety checks and cache invalidation hooks.\n *\n * @module WorkspaceFileSystem\n */\nimport * as NodeFSP from \"node:fs/promises\";\n\nimport type {\n  ProjectReadFileInput,\n  ProjectReadFileResult,\n  ProjectWriteFileInput,\n  ProjectWriteFileResult,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as WorkspaceEntries from \"./WorkspaceEntries.ts\";\nimport * as WorkspacePaths from \"./WorkspacePaths.ts\";\n\nconst PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;\n\nexport class WorkspaceFileSystemOperationError extends Schema.TaggedErrorClass<WorkspaceFileSystemOperationError>()(\n  \"WorkspaceFileSystemOperationError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    resolvedPath: Schema.String,\n    operationPath: Schema.String,\n    operation: Schema.Literals([\n      \"realpath-workspace-root\",\n      \"realpath-target\",\n      \"open\",\n      \"stat\",\n      \"read\",\n      \"close\",\n      \"make-directory\",\n      \"write-file\",\n    ]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Workspace file operation '${this.operation}' failed at '${this.operationPath}' for resolved path '${this.resolvedPath}' (requested as '${this.relativePath}' in '${this.workspaceRoot}').`;\n  }\n}\n\nexport class WorkspaceFilePathEscapeError extends Schema.TaggedErrorClass<WorkspaceFilePathEscapeError>()(\n  \"WorkspaceFilePathEscapeError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    resolvedWorkspaceRoot: Schema.String,\n    resolvedPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace file '${this.relativePath}' resolves outside workspace root '${this.workspaceRoot}': ${this.resolvedPath}`;\n  }\n}\n\nexport class WorkspacePathNotFileError extends Schema.TaggedErrorClass<WorkspacePathNotFileError>()(\n  \"WorkspacePathNotFileError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    resolvedPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace path '${this.relativePath}' in '${this.workspaceRoot}' is not a file: ${this.resolvedPath}`;\n  }\n}\n\nexport class WorkspaceBinaryFileError extends Schema.TaggedErrorClass<WorkspaceBinaryFileError>()(\n  \"WorkspaceBinaryFileError\",\n  {\n    workspaceRoot: Schema.String,\n    relativePath: Schema.String,\n    resolvedPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Workspace file '${this.relativePath}' in '${this.workspaceRoot}' is binary and cannot be previewed as text.`;\n  }\n}\n\nexport const WorkspaceFileSystemError = Schema.Union([\n  WorkspaceFileSystemOperationError,\n  WorkspaceFilePathEscapeError,\n  WorkspacePathNotFileError,\n  WorkspaceBinaryFileError,\n]);\nexport type WorkspaceFileSystemError = typeof WorkspaceFileSystemError.Type;\n\n/** Service tag for workspace file operations. */\nexport class WorkspaceFileSystem extends Context.Service<\n  WorkspaceFileSystem,\n  {\n    /** Read a UTF-8 text file relative to the workspace root. */\n    readonly readFile: (\n      input: ProjectReadFileInput,\n    ) => Effect.Effect<\n      ProjectReadFileResult,\n      WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError\n    >;\n    /**\n     * Write a file relative to the workspace root.\n     *\n     * Creates parent directories as needed and rejects paths that escape the\n     * workspace root.\n     */\n    readonly writeFile: (\n      input: ProjectWriteFileInput,\n    ) => Effect.Effect<\n      ProjectWriteFileResult,\n      WorkspaceFileSystemError | WorkspacePaths.WorkspacePathOutsideRootError\n    >;\n  }\n>()(\"t3/workspace/WorkspaceFileSystem\") {}\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const workspacePaths = yield* WorkspacePaths.WorkspacePaths;\n  const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;\n\n  const readFile: WorkspaceFileSystem[\"Service\"][\"readFile\"] = Effect.fn(\n    \"WorkspaceFileSystem.readFile\",\n  )(function* (input) {\n    const target = yield* workspacePaths.resolveRelativePathWithinRoot({\n      workspaceRoot: input.cwd,\n      relativePath: input.relativePath,\n    });\n\n    const realWorkspaceRoot = yield* Effect.tryPromise({\n      try: () => NodeFSP.realpath(input.cwd),\n      catch: (cause) =>\n        new WorkspaceFileSystemOperationError({\n          workspaceRoot: input.cwd,\n          relativePath: input.relativePath,\n          resolvedPath: target.absolutePath,\n          operationPath: input.cwd,\n          operation: \"realpath-workspace-root\",\n          cause,\n        }),\n    });\n    const realTargetPath = yield* Effect.tryPromise({\n      try: () => NodeFSP.realpath(target.absolutePath),\n      catch: (cause) =>\n        new WorkspaceFileSystemOperationError({\n          workspaceRoot: input.cwd,\n          relativePath: input.relativePath,\n          resolvedPath: target.absolutePath,\n          operationPath: target.absolutePath,\n          operation: \"realpath-target\",\n          cause,\n        }),\n    });\n    const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);\n    if (\n      relativeRealPath.startsWith(`..${path.sep}`) ||\n      relativeRealPath === \"..\" ||\n      path.isAbsolute(relativeRealPath)\n    ) {\n      return yield* new WorkspaceFilePathEscapeError({\n        workspaceRoot: input.cwd,\n        relativePath: input.relativePath,\n        resolvedWorkspaceRoot: realWorkspaceRoot,\n        resolvedPath: realTargetPath,\n      });\n    }\n\n    return yield* Effect.acquireUseRelease(\n      Effect.tryPromise({\n        try: () => NodeFSP.open(realTargetPath, \"r\"),\n        catch: (cause) =>\n          new WorkspaceFileSystemOperationError({\n            workspaceRoot: input.cwd,\n            relativePath: input.relativePath,\n            resolvedPath: realTargetPath,\n            operationPath: realTargetPath,\n            operation: \"open\",\n            cause,\n          }),\n      }),\n      (handle) =>\n        Effect.gen(function* () {\n          const stat = yield* Effect.tryPromise({\n            try: () => handle.stat(),\n            catch: (cause) =>\n              new WorkspaceFileSystemOperationError({\n                workspaceRoot: input.cwd,\n                relativePath: input.relativePath,\n                resolvedPath: realTargetPath,\n                operationPath: realTargetPath,\n                operation: \"stat\",\n                cause,\n              }),\n          });\n          if (!stat.isFile()) {\n            return yield* new WorkspacePathNotFileError({\n              workspaceRoot: input.cwd,\n              relativePath: input.relativePath,\n              resolvedPath: realTargetPath,\n            });\n          }\n\n          const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);\n          const buffer = Buffer.alloc(bytesToRead);\n          const { bytesRead } = yield* Effect.tryPromise({\n            try: () => handle.read(buffer, 0, bytesToRead, 0),\n            catch: (cause) =>\n              new WorkspaceFileSystemOperationError({\n                workspaceRoot: input.cwd,\n                relativePath: input.relativePath,\n                resolvedPath: realTargetPath,\n                operationPath: realTargetPath,\n                operation: \"read\",\n                cause,\n              }),\n          });\n          const fileBytes = buffer.subarray(0, bytesRead);\n          if (fileBytes.includes(0)) {\n            return yield* new WorkspaceBinaryFileError({\n              workspaceRoot: input.cwd,\n              relativePath: input.relativePath,\n              resolvedPath: realTargetPath,\n            });\n          }\n\n          return {\n            relativePath: target.relativePath,\n            contents: new TextDecoder(\"utf-8\").decode(fileBytes),\n            byteLength: stat.size,\n            truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,\n          };\n        }),\n      (handle) =>\n        Effect.tryPromise({\n          try: () => handle.close(),\n          catch: (cause) =>\n            new WorkspaceFileSystemOperationError({\n              workspaceRoot: input.cwd,\n              relativePath: input.relativePath,\n              resolvedPath: realTargetPath,\n              operationPath: realTargetPath,\n              operation: \"close\",\n              cause,\n            }),\n        }),\n    );\n  });\n\n  const writeFile: WorkspaceFileSystem[\"Service\"][\"writeFile\"] = Effect.fn(\n    \"WorkspaceFileSystem.writeFile\",\n  )(function* (input) {\n    const target = yield* workspacePaths.resolveRelativePathWithinRoot({\n      workspaceRoot: input.cwd,\n      relativePath: input.relativePath,\n    });\n\n    yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new WorkspaceFileSystemOperationError({\n            workspaceRoot: input.cwd,\n            relativePath: input.relativePath,\n            resolvedPath: target.absolutePath,\n            operationPath: path.dirname(target.absolutePath),\n            operation: \"make-directory\",\n            cause,\n          }),\n      ),\n    );\n    yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(\n      Effect.mapError(\n        (cause) =>\n          new WorkspaceFileSystemOperationError({\n            workspaceRoot: input.cwd,\n            relativePath: input.relativePath,\n            resolvedPath: target.absolutePath,\n            operationPath: target.absolutePath,\n            operation: \"write-file\",\n            cause,\n          }),\n      ),\n    );\n    yield* workspaceEntries.refresh(input.cwd);\n    return { relativePath: target.relativePath };\n  });\n\n  return WorkspaceFileSystem.of({ readFile, writeFile });\n});\n\nexport const layer = Layer.effect(WorkspaceFileSystem, make);\n","// @effect-diagnostics nodeBuiltinImport:off\n/**\n * Read-only access to persisted workflow scripts for the Agents surface's\n * \"{} script\" affordance.\n *\n * Containment rules (lifted from the reviewed #3650 inspection service):\n * - the resolved realpath must live under ~/.claude/projects (where the\n *   Claude harness persists workflow scripts) — realpath re-containment\n *   defeats symlink escapes, including a symlinked leaf file;\n * - only .js leaf files are served;\n * - reads are size-capped rather than failed, with a truncation marker.\n *\n * The client-supplied path is a hint from the workflow's runHandles; it is\n * never trusted beyond these checks.\n */\nimport * as NodeFSP from \"node:fs/promises\";\nimport * as NodeOS from \"node:os\";\nimport * as NodePath from \"node:path\";\n\nimport { OrchestrationGetWorkflowScriptError } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\n\nconst SCRIPT_BYTE_CAP = 256 * 1024;\n\nfunction scriptsRoot(): string {\n  return NodePath.join(NodeOS.homedir(), \".claude\", \"projects\");\n}\n\nexport const readWorkflowScript = Effect.fn(\"orchestration.readWorkflowScript\")(function* (input: {\n  readonly scriptPath: string;\n}) {\n  const requested = input.scriptPath;\n\n  if (!NodePath.isAbsolute(requested) || NodePath.extname(requested) !== \".js\") {\n    return yield* Effect.fail(\n      new OrchestrationGetWorkflowScriptError({ reason: \"invalid-path\", scriptPath: requested }),\n    );\n  }\n\n  const root = yield* Effect.tryPromise({\n    try: () => NodeFSP.realpath(scriptsRoot()),\n    catch: (cause) =>\n      new OrchestrationGetWorkflowScriptError({\n        reason: \"root-unavailable\",\n        scriptPath: requested,\n        cause,\n      }),\n  });\n\n  // Realpath the FILE itself (not just its directory): a symlink named\n  // like a script inside a contained directory must not escape.\n  const resolved = yield* Effect.tryPromise({\n    try: () => NodeFSP.realpath(requested),\n    catch: (cause) =>\n      new OrchestrationGetWorkflowScriptError({\n        reason: \"not-found\",\n        scriptPath: requested,\n        cause,\n      }),\n  });\n\n  if (resolved !== root && !resolved.startsWith(`${root}${NodePath.sep}`)) {\n    return yield* Effect.fail(\n      new OrchestrationGetWorkflowScriptError({ reason: \"outside-root\", scriptPath: resolved }),\n    );\n  }\n  if (NodePath.extname(resolved) !== \".js\") {\n    return yield* Effect.fail(\n      new OrchestrationGetWorkflowScriptError({ reason: \"not-js\", scriptPath: resolved }),\n    );\n  }\n\n  // TOCTOU-safe read (review finding): open FIRST, then verify what was\n  // actually opened via the file descriptor. Re-checking the path after\n  // open would race against a swap; fstat on the handle cannot. The two\n  // containment checks fail with their own tagged reasons (not manufactured\n  // Errors folded into read-failed); \"read-failed\" is reserved for genuine\n  // platform failures with the real cause attached.\n  const read = yield* Effect.tryPromise({\n    try: async () => {\n      const handle = await NodeFSP.open(resolved, \"r\");\n      try {\n        const stat = await handle.stat();\n        if (!stat.isFile()) {\n          return { failure: \"not-regular-file\" as const };\n        }\n        // The opened inode must be the same one realpath resolved to: a\n        // process swapping the path between realpath and open changes the\n        // inode, which this comparison catches.\n        const pathStat = await NodeFSP.lstat(resolved);\n        if (stat.ino !== pathStat.ino || stat.dev !== pathStat.dev) {\n          return { failure: \"changed-during-read\" as const };\n        }\n        const truncated = stat.size > SCRIPT_BYTE_CAP;\n        const buffer = Buffer.alloc(Math.min(stat.size, SCRIPT_BYTE_CAP));\n        const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);\n        return {\n          contents: buffer.subarray(0, bytesRead).toString(\"utf8\"),\n          truncated,\n        };\n      } finally {\n        await handle.close();\n      }\n    },\n    catch: (cause) =>\n      new OrchestrationGetWorkflowScriptError({\n        reason: \"read-failed\",\n        scriptPath: resolved,\n        cause,\n      }),\n  });\n  if (\"failure\" in read) {\n    return yield* new OrchestrationGetWorkflowScriptError({\n      reason: read.failure,\n      scriptPath: resolved,\n    });\n  }\n\n  return {\n    scriptPath: resolved,\n    contents: read.contents,\n    truncated: read.truncated,\n  };\n});\n","/**\n * ProviderInstanceRegistry — the single Effect service in the new model.\n *\n * Owns a `Map<ProviderInstanceId, ProviderInstance>` produced by running\n * registered driver factories against `ServerSettings.providerInstances`.\n * The registry watches settings; when an instance's config changes (or\n * the entry disappears), the registry tears down the affected instance's\n * scope and rebuilds — that's the entire hot-reload story.\n *\n * What rest-of-server reads from here:\n *   - `getInstance(instanceId)` — for routing turn/session calls.\n *   - `listInstances` — for snapshot aggregation in `ProviderRegistry`.\n *   - `listUnavailable` — `ServerProvider` shadows for instances whose\n *     driver is not registered in this build (rollback / fork tolerance).\n *   - `streamChanges` — coalesced \"registry mutated\" pings so consumers\n *     can re-pull lists or re-broadcast.\n *\n * @module provider/Services/ProviderInstanceRegistry\n */\nimport type { ProviderInstanceId, ServerProvider } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { ProviderInstance } from \"../ProviderDriver.ts\";\n\nexport interface ProviderInstanceRegistryShape {\n  /**\n   * Look up one instance by id. Returns `undefined` (not Option) when the\n   * id is unknown — callers branch on falsy and emit\n   * `ProviderInstanceNotFoundError`.\n   */\n  readonly getInstance: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderInstance | undefined>;\n  /**\n   * Every available (driver-registered, successfully created) instance,\n   * in stable settings-author order.\n   */\n  readonly listInstances: Effect.Effect<ReadonlyArray<ProviderInstance>>;\n  /**\n   * Wire-shape shadow snapshots for instances whose driver is unknown to\n   * this build (or whose config failed to decode). Suitable for merging\n   * directly into `ProviderRegistry` output.\n   */\n  readonly listUnavailable: Effect.Effect<ReadonlyArray<ServerProvider>>;\n  /**\n   * Push notification stream emitted whenever the registry's contents\n   * change — instance added, removed, or rebuilt. The payload is `void`\n   * because consumers always want to re-pull `listInstances` /\n   * `listUnavailable` together.\n   *\n   * NOTE: because `Stream.fromPubSub` defers `PubSub.subscribe` until the\n   * stream starts running, forking a consumer via\n   * `Stream.runForEach(...).pipe(Effect.forkScoped)` races the next\n   * publish — the forked fiber may not have subscribed yet when the\n   * publish lands. Hot-reload consumers that must not miss a publish\n   * should use `subscribeChanges` below instead, which acquires the\n   * subscription synchronously in the caller's fiber before the consumer\n   * loop is forked.\n   */\n  readonly streamChanges: Stream.Stream<void>;\n  /**\n   * Acquire a subscription to the registry's change channel synchronously\n   * in the caller's fiber. Returns a `PubSub.Subscription<void>` whose\n   * lifetime is scoped to the provided `Scope` (the subscription is\n   * released when the scope closes). Consumers typically `yield*` this\n   * in the same fiber that forks their consumer loop, then drain with\n   * `PubSub.take(subscription)` inside `Effect.forever`. Because the\n   * subscription is registered with the PubSub before this `yield*`\n   * returns, no subsequent publish can land in a gap.\n   *\n   * This exists because the `ProviderInstanceRegistry` publishes on a\n   * PubSub and `Stream.fromPubSub` defers subscription until the stream\n   * starts executing — a consumer that `forkScoped`s the stream\n   * consumption can miss a publish that lands in the narrow window\n   * between \"fiber scheduled\" and \"fiber starts running\".\n   */\n  readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;\n}\n\nexport class ProviderInstanceRegistry extends Context.Service<\n  ProviderInstanceRegistry,\n  ProviderInstanceRegistryShape\n>()(\"t3/provider/Services/ProviderInstanceRegistry\") {}\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport type { ChatAttachment, ModelSelection, ProviderInstanceId } from \"@t3tools/contracts\";\nimport { TextGenerationError } from \"@t3tools/contracts\";\n\nimport * as ProviderInstanceRegistry from \"../provider/Services/ProviderInstanceRegistry.ts\";\nimport type { ProviderInstance } from \"../provider/ProviderDriver.ts\";\nimport type { TextGenerationPolicy } from \"./TextGenerationPolicy.ts\";\n\nexport type TextGenerationProvider = \"codex\" | \"claudeAgent\" | \"cursor\" | \"grok\" | \"opencode\";\n\nexport interface CommitMessageGenerationInput {\n  cwd: string;\n  branch: string | null;\n  stagedSummary: string;\n  stagedPatch: string;\n  /** When true, the model also returns a semantic branch name for the change. */\n  includeBranch?: boolean;\n  policy?: TextGenerationPolicy | undefined;\n  /** What model and provider to use for generation. */\n  modelSelection: ModelSelection;\n}\n\nexport interface CommitMessageGenerationResult {\n  subject: string;\n  body: string;\n  /** Only present when `includeBranch` was set on the input. */\n  branch?: string | undefined;\n}\n\nexport interface PrContentGenerationInput {\n  cwd: string;\n  baseBranch: string;\n  headBranch: string;\n  commitSummary: string;\n  diffSummary: string;\n  diffPatch: string;\n  changeRequestTemplate?: string | undefined;\n  policy?: TextGenerationPolicy | undefined;\n  /** What model and provider to use for generation. */\n  modelSelection: ModelSelection;\n}\n\nexport interface PrContentGenerationResult {\n  title: string;\n  body: string;\n}\n\nexport interface BranchNameGenerationInput {\n  cwd: string;\n  message: string;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  /** What model and provider to use for generation. */\n  modelSelection: ModelSelection;\n}\n\nexport interface BranchNameGenerationResult {\n  branch: string;\n}\n\nexport interface ThreadTitleGenerationInput {\n  cwd: string;\n  message: string;\n  /** Present when replacing an existing title from the current thread history. */\n  previousTitle?: string | undefined;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  /** What model and provider to use for generation. */\n  modelSelection: ModelSelection;\n}\n\nexport interface ThreadTitleGenerationResult {\n  title: string;\n}\n\nexport interface TextGenerationService {\n  generateCommitMessage(\n    input: CommitMessageGenerationInput,\n  ): Promise<CommitMessageGenerationResult>;\n  generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;\n  generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;\n  generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;\n}\n\n/**\n * TextGeneration - Service tag for commit and change request text generation.\n */\nexport class TextGeneration extends Context.Service<\n  TextGeneration,\n  {\n    /**\n     * Generate a commit message from staged change context.\n     */\n    readonly generateCommitMessage: (\n      input: CommitMessageGenerationInput,\n    ) => Effect.Effect<CommitMessageGenerationResult, TextGenerationError>;\n\n    /**\n     * Generate change request title/body from branch and diff context.\n     */\n    readonly generatePrContent: (\n      input: PrContentGenerationInput,\n    ) => Effect.Effect<PrContentGenerationResult, TextGenerationError>;\n\n    /**\n     * Generate a concise branch name from a user message.\n     */\n    readonly generateBranchName: (\n      input: BranchNameGenerationInput,\n    ) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;\n\n    /** Generate a concise thread title from a first message or thread history. */\n    readonly generateThreadTitle: (\n      input: ThreadTitleGenerationInput,\n    ) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;\n  }\n>()(\"t3/textGeneration/TextGeneration\") {}\n\n/** @deprecated Use `TextGeneration[\"Service\"]`. */\nexport type TextGenerationShape = TextGeneration[\"Service\"];\n\ntype TextGenerationOp =\n  | \"generateCommitMessage\"\n  | \"generatePrContent\"\n  | \"generateBranchName\"\n  | \"generateThreadTitle\";\n\nconst resolveInstance = (\n  registry: ProviderInstanceRegistry.ProviderInstanceRegistry[\"Service\"],\n  operation: TextGenerationOp,\n  instanceId: ProviderInstanceId,\n): Effect.Effect<ProviderInstance[\"textGeneration\"], TextGenerationError> =>\n  registry.getInstance(instanceId).pipe(\n    Effect.flatMap((instance) =>\n      instance\n        ? Effect.succeed(instance.textGeneration)\n        : Effect.fail(\n            new TextGenerationError({\n              operation,\n              detail: `No provider instance registered for id '${instanceId}'.`,\n            }),\n          ),\n    ),\n  );\n\nexport const makeTextGenerationFromRegistry = (\n  registry: ProviderInstanceRegistry.ProviderInstanceRegistry[\"Service\"],\n): TextGeneration[\"Service\"] =>\n  TextGeneration.of({\n    generateCommitMessage: (input) =>\n      resolveInstance(registry, \"generateCommitMessage\", input.modelSelection.instanceId).pipe(\n        Effect.flatMap((textGeneration) => textGeneration.generateCommitMessage(input)),\n      ),\n    generatePrContent: (input) =>\n      resolveInstance(registry, \"generatePrContent\", input.modelSelection.instanceId).pipe(\n        Effect.flatMap((textGeneration) => textGeneration.generatePrContent(input)),\n      ),\n    generateBranchName: (input) =>\n      resolveInstance(registry, \"generateBranchName\", input.modelSelection.instanceId).pipe(\n        Effect.flatMap((textGeneration) => textGeneration.generateBranchName(input)),\n      ),\n    generateThreadTitle: (input) =>\n      resolveInstance(registry, \"generateThreadTitle\", input.modelSelection.instanceId).pipe(\n        Effect.flatMap((textGeneration) => textGeneration.generateThreadTitle(input)),\n      ),\n  });\n\nexport const make = Effect.gen(function* () {\n  const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;\n  return makeTextGenerationFromRegistry(registry);\n});\n\nexport const layer = Layer.effect(TextGeneration, make);\n","import type { TextGenerationPolicy, TextGenerationPolicyKind } from \"./TextGenerationPolicy.ts\";\n\nexport const defaultTextGenerationPolicy: TextGenerationPolicy = {\n  kind: \"default\",\n  inferRepositoryConventions: false,\n};\n\nexport const conventionalCommitsTextGenerationPolicy: TextGenerationPolicy = {\n  kind: \"conventional_commits\",\n  commitInstructions:\n    \"Use Conventional Commits when generating commit subjects. Prefer the narrowest accurate type and include a scope only when it is obvious from the diff.\",\n  changeRequestInstructions:\n    \"Keep the change request title concise. Do not force Conventional Commit syntax into the title unless the repository already uses it.\",\n  inferRepositoryConventions: false,\n};\n\nexport const repositoryConventionsTextGenerationPolicy: TextGenerationPolicy = {\n  kind: \"repo_conventions\",\n  commitInstructions:\n    \"Follow the repository's established commit message style when examples are available.\",\n  changeRequestInstructions:\n    \"Follow the repository's established change request title and body style when examples are available.\",\n  inferRepositoryConventions: true,\n};\n\nexport const customTextGenerationPolicy = (\n  overrides: Omit<Partial<TextGenerationPolicy>, \"kind\">,\n): TextGenerationPolicy => ({\n  kind: \"custom\",\n  inferRepositoryConventions: false,\n  ...overrides,\n});\n\nexport const textGenerationPresets: Record<\n  Exclude<TextGenerationPolicyKind, \"custom\">,\n  TextGenerationPolicy\n> = {\n  default: defaultTextGenerationPolicy,\n  conventional_commits: conventionalCommitsTextGenerationPolicy,\n  repo_conventions: repositoryConventionsTextGenerationPolicy,\n};\n","import type { ProjectScript } from \"@t3tools/contracts\";\n\ninterface ProjectScriptRuntimeEnvInput {\n  project: {\n    cwd: string;\n  };\n  worktreePath?: string | null;\n  extraEnv?: Record<string, string>;\n}\n\nexport function projectScriptCwd(input: {\n  project: {\n    cwd: string;\n  };\n  worktreePath?: string | null;\n}): string {\n  return input.worktreePath ?? input.project.cwd;\n}\n\nexport function projectScriptRuntimeEnv(\n  input: ProjectScriptRuntimeEnvInput,\n): Record<string, string> {\n  const env: Record<string, string> = {\n    SYNAPTIC_PROJECT_ROOT: input.project.cwd,\n  };\n  if (input.worktreePath) {\n    env.SYNAPTIC_WORKTREE_PATH = input.worktreePath;\n  }\n  if (input.extraEnv) {\n    return { ...env, ...input.extraEnv };\n  }\n  return env;\n}\n\nexport function setupProjectScript(scripts: readonly ProjectScript[]): ProjectScript | null {\n  return scripts.find((script) => script.runOnWorktreeCreate) ?? null;\n}\n","import { ProjectId } from \"@t3tools/contracts\";\nimport { projectScriptRuntimeEnv, setupProjectScript } from \"@t3tools/shared/projectScripts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ProjectionSnapshotQuery from \"../orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport * as TerminalManager from \"../terminal/Manager.ts\";\n\nexport interface ProjectSetupScriptRunnerResultNoScript {\n  readonly status: \"no-script\";\n}\n\nexport interface ProjectSetupScriptRunnerResultStarted {\n  readonly status: \"started\";\n  readonly scriptId: string;\n  readonly scriptName: string;\n  readonly terminalId: string;\n  readonly cwd: string;\n}\n\nexport type ProjectSetupScriptRunnerResult =\n  | ProjectSetupScriptRunnerResultNoScript\n  | ProjectSetupScriptRunnerResultStarted;\n\nexport interface ProjectSetupScriptRunnerInput {\n  readonly threadId: string;\n  readonly projectId?: string;\n  readonly projectCwd?: string;\n  readonly worktreePath: string;\n  readonly preferredTerminalId?: string;\n}\n\nexport class ProjectSetupScriptOperationError extends Schema.TaggedErrorClass<ProjectSetupScriptOperationError>()(\n  \"ProjectSetupScriptOperationError\",\n  {\n    threadId: Schema.String,\n    projectId: Schema.optional(Schema.String),\n    projectCwd: Schema.optional(Schema.String),\n    worktreePath: Schema.String,\n    operation: Schema.Literals([\"resolveProject\", \"openTerminal\", \"writeCommand\"]),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Project setup script operation '${this.operation}' failed for thread '${this.threadId}' in '${this.worktreePath}'.`;\n  }\n}\n\nexport class ProjectSetupScriptProjectNotFoundError extends Schema.TaggedErrorClass<ProjectSetupScriptProjectNotFoundError>()(\n  \"ProjectSetupScriptProjectNotFoundError\",\n  {\n    threadId: Schema.String,\n    projectId: Schema.optional(Schema.String),\n    projectCwd: Schema.optional(Schema.String),\n    worktreePath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Project was not found for setup script execution for thread '${this.threadId}' in '${this.worktreePath}'.`;\n  }\n}\n\nexport const ProjectSetupScriptRunnerError = Schema.Union([\n  ProjectSetupScriptOperationError,\n  ProjectSetupScriptProjectNotFoundError,\n]);\nexport type ProjectSetupScriptRunnerError = typeof ProjectSetupScriptRunnerError.Type;\n\nexport class ProjectSetupScriptRunner extends Context.Service<\n  ProjectSetupScriptRunner,\n  {\n    readonly runForThread: (\n      input: ProjectSetupScriptRunnerInput,\n    ) => Effect.Effect<ProjectSetupScriptRunnerResult, ProjectSetupScriptRunnerError>;\n  }\n>()(\"t3/project/ProjectSetupScriptRunner\") {}\n\nexport const make = Effect.gen(function* () {\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n  const terminalManager = yield* TerminalManager.TerminalManager;\n\n  const runForThread: ProjectSetupScriptRunner[\"Service\"][\"runForThread\"] = Effect.fn(\n    \"ProjectSetupScriptRunner.runForThread\",\n  )(function* (input) {\n    const errorContext = {\n      threadId: input.threadId,\n      worktreePath: input.worktreePath,\n      ...(input.projectId === undefined ? {} : { projectId: input.projectId }),\n      ...(input.projectCwd === undefined ? {} : { projectCwd: input.projectCwd }),\n    };\n    const projectById = input.projectId\n      ? yield* projectionSnapshotQuery.getProjectShellById(ProjectId.make(input.projectId)).pipe(\n          Effect.map(Option.getOrUndefined),\n          Effect.mapError(\n            (cause) =>\n              new ProjectSetupScriptOperationError({\n                ...errorContext,\n                operation: \"resolveProject\",\n                cause,\n              }),\n          ),\n        )\n      : null;\n    const project =\n      projectById ??\n      (input.projectCwd\n        ? yield* projectionSnapshotQuery.getActiveProjectByWorkspaceRoot(input.projectCwd).pipe(\n            Effect.map(Option.getOrUndefined),\n            Effect.mapError(\n              (cause) =>\n                new ProjectSetupScriptOperationError({\n                  ...errorContext,\n                  operation: \"resolveProject\",\n                  cause,\n                }),\n            ),\n          )\n        : null);\n\n    if (!project) {\n      return yield* new ProjectSetupScriptProjectNotFoundError(errorContext);\n    }\n\n    const script = setupProjectScript(project.scripts);\n    if (!script) {\n      return {\n        status: \"no-script\",\n      } as const;\n    }\n\n    const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;\n    const cwd = input.worktreePath;\n    const env = projectScriptRuntimeEnv({\n      project: { cwd: project.workspaceRoot },\n      worktreePath: input.worktreePath,\n    });\n\n    yield* terminalManager\n      .open({\n        threadId: input.threadId,\n        terminalId,\n        cwd,\n        worktreePath: input.worktreePath,\n        env,\n      })\n      .pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProjectSetupScriptOperationError({\n              ...errorContext,\n              operation: \"openTerminal\",\n              cause,\n            }),\n        ),\n      );\n    yield* terminalManager\n      .write({\n        threadId: input.threadId,\n        terminalId,\n        data: `${script.command}\\r`,\n      })\n      .pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProjectSetupScriptOperationError({\n              ...errorContext,\n              operation: \"writeCommand\",\n              cause,\n            }),\n        ),\n      );\n\n    return {\n      status: \"started\",\n      scriptId: script.id,\n      scriptName: script.name,\n      terminalId,\n      cwd,\n    } as const;\n  });\n\n  return ProjectSetupScriptRunner.of({ runForThread });\n});\n\nexport const layer = Layer.effect(ProjectSetupScriptRunner, make);\n","import * as Cause from \"effect/Cause\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { PositiveInt, TrimmedNonEmptyString } from \"@t3tools/contracts\";\nimport { decodeJsonResult, formatSchemaError } from \"@t3tools/shared/schemaJson\";\n\nexport interface NormalizedAzureDevOpsPullRequestRecord {\n  readonly number: number;\n  readonly title: string;\n  readonly url: string;\n  readonly baseRefName: string;\n  readonly headRefName: string;\n  readonly state: \"open\" | \"closed\" | \"merged\";\n  readonly updatedAt: Option.Option<DateTime.Utc>;\n}\n\nconst AzureDevOpsPullRequestSchema = Schema.Struct({\n  pullRequestId: PositiveInt,\n  title: TrimmedNonEmptyString,\n  url: Schema.optional(Schema.String),\n  repository: Schema.optional(\n    Schema.Struct({\n      name: Schema.optional(Schema.String),\n      webUrl: Schema.optional(Schema.String),\n      project: Schema.optional(\n        Schema.Struct({\n          name: Schema.optional(Schema.String),\n        }),\n      ),\n    }),\n  ),\n  sourceRefName: TrimmedNonEmptyString,\n  targetRefName: TrimmedNonEmptyString,\n  status: Schema.String,\n  creationDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),\n  closedDate: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),\n  _links: Schema.optional(\n    Schema.Struct({\n      web: Schema.optional(\n        Schema.Struct({\n          href: Schema.String,\n        }),\n      ),\n    }),\n  ),\n});\n\nfunction trimOptionalString(value: string | null | undefined): string | null {\n  const trimmed = value?.trim() ?? \"\";\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeRefName(refName: string): string {\n  return refName.trim().replace(/^refs\\/heads\\//, \"\");\n}\n\nfunction normalizeAzureDevOpsPullRequestState(status: string): \"open\" | \"closed\" | \"merged\" {\n  switch (status.trim().toLowerCase()) {\n    case \"completed\":\n      return \"merged\";\n    case \"abandoned\":\n      return \"closed\";\n    default:\n      return \"open\";\n  }\n}\n\nfunction encodeAzureDevOpsPathSegment(segment: string): string {\n  return encodeURIComponent(segment);\n}\n\nfunction azureDevOpsOrganizationBaseFromRestApiUrl(\n  value: string | null | undefined,\n): string | null {\n  const rawUrl = trimOptionalString(value);\n  if (!rawUrl) {\n    return null;\n  }\n\n  try {\n    const url = new URL(rawUrl);\n    const hostname = url.hostname.toLowerCase();\n    const pathSegments = url.pathname.split(\"/\").filter((segment) => segment.length > 0);\n    const isAzureRestUrl = pathSegments.some((segment) => segment.toLowerCase() === \"_apis\");\n    if (!isAzureRestUrl) {\n      return null;\n    }\n\n    if (hostname === \"dev.azure.com\") {\n      const organization = pathSegments[0];\n      return organization ? `${url.origin}/${organization}` : null;\n    }\n\n    if (hostname.endsWith(\".visualstudio.com\")) {\n      return url.origin;\n    }\n\n    return null;\n  } catch {\n    return null;\n  }\n}\n\nfunction normalizeAzureDevOpsPullRequestUrl(\n  raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,\n): string {\n  const webLink = trimOptionalString(raw._links?.web?.href);\n  if (webLink) {\n    return webLink;\n  }\n\n  const repositoryWebUrl = trimOptionalString(raw.repository?.webUrl);\n  if (repositoryWebUrl) {\n    return `${repositoryWebUrl.replace(/\\/+$/, \"\")}/pullrequest/${raw.pullRequestId}`;\n  }\n\n  const organizationBase = azureDevOpsOrganizationBaseFromRestApiUrl(raw.url);\n  const projectName = trimOptionalString(raw.repository?.project?.name);\n  const repositoryName = trimOptionalString(raw.repository?.name);\n  if (organizationBase && projectName && repositoryName) {\n    const encodedProjectName = encodeAzureDevOpsPathSegment(projectName);\n    const encodedRepositoryName = encodeAzureDevOpsPathSegment(repositoryName);\n    return `${organizationBase}/${encodedProjectName}/_git/${encodedRepositoryName}/pullrequest/${raw.pullRequestId}`;\n  }\n\n  return trimOptionalString(raw.url) ?? \"\";\n}\n\nfunction normalizeAzureDevOpsPullRequestRecord(\n  raw: Schema.Schema.Type<typeof AzureDevOpsPullRequestSchema>,\n): NormalizedAzureDevOpsPullRequestRecord {\n  return {\n    number: raw.pullRequestId,\n    title: raw.title,\n    url: normalizeAzureDevOpsPullRequestUrl(raw),\n    baseRefName: normalizeRefName(raw.targetRefName),\n    headRefName: normalizeRefName(raw.sourceRefName),\n    state: normalizeAzureDevOpsPullRequestState(raw.status),\n    updatedAt: (raw.closedDate ?? Option.none()).pipe(\n      Option.orElse(() => raw.creationDate ?? Option.none()),\n    ),\n  };\n}\n\nconst decodeAzureDevOpsPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));\nconst decodeAzureDevOpsPullRequest = decodeJsonResult(AzureDevOpsPullRequestSchema);\nconst decodeAzureDevOpsPullRequestEntry = Schema.decodeUnknownExit(AzureDevOpsPullRequestSchema);\n\nexport const formatAzureDevOpsJsonDecodeError = formatSchemaError;\n\nexport function decodeAzureDevOpsPullRequestListJson(\n  raw: string,\n): Result.Result<\n  ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>,\n  Cause.Cause<Schema.SchemaError>\n> {\n  const result = decodeAzureDevOpsPullRequestList(raw);\n  if (Result.isSuccess(result)) {\n    const pullRequests: NormalizedAzureDevOpsPullRequestRecord[] = [];\n    for (const entry of result.success) {\n      const decodedEntry = decodeAzureDevOpsPullRequestEntry(entry);\n      if (Exit.isFailure(decodedEntry)) {\n        continue;\n      }\n      pullRequests.push(normalizeAzureDevOpsPullRequestRecord(decodedEntry.value));\n    }\n    return Result.succeed(pullRequests);\n  }\n  return Result.fail(result.failure);\n}\n\nexport function decodeAzureDevOpsPullRequestJson(\n  raw: string,\n): Result.Result<NormalizedAzureDevOpsPullRequestRecord, Cause.Cause<Schema.SchemaError>> {\n  const result = decodeAzureDevOpsPullRequest(raw);\n  if (Result.isSuccess(result)) {\n    return Result.succeed(normalizeAzureDevOpsPullRequestRecord(result.success));\n  }\n  return Result.fail(result.failure);\n}\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport type {\n  ChangeRequest,\n  ChangeRequestState,\n  SourceControlProviderError,\n  SourceControlProviderInfo,\n  SourceControlProviderKind,\n  SourceControlRepositoryCloneUrls,\n  SourceControlRepositoryVisibility,\n} from \"@t3tools/contracts\";\n\nexport interface SourceControlProviderContext {\n  readonly provider: SourceControlProviderInfo;\n  readonly remoteName: string;\n  readonly remoteUrl: string;\n}\n\nexport interface SourceControlRefSelector {\n  readonly refName: string;\n  readonly owner?: string;\n  readonly repository?: string;\n}\n\nconst MAX_ERROR_TRANSPORT_VALUE_LENGTH = 256;\n\n/**\n * Sanitizes user-provided source-control identifiers before attaching them to\n * contract errors. This is intentionally narrower than request validation: it\n * only strips URL secrets and bounds diagnostic values sent over transport.\n */\nexport function transportSafeSourceControlErrorValue(value: string): string {\n  let printable = \"\";\n  for (const character of value) {\n    const codePoint = character.codePointAt(0);\n    printable += codePoint !== undefined && (codePoint < 32 || codePoint === 127) ? \" \" : character;\n  }\n  const normalized = printable.trim().replace(/\\s+/gu, \" \");\n\n  let safe = normalized;\n  try {\n    const url = new URL(normalized);\n    url.username = \"\";\n    url.password = \"\";\n    url.search = \"\";\n    url.hash = \"\";\n    safe = url.toString();\n  } catch {\n    // Plain repository and change-request identifiers are not URLs.\n  }\n\n  return safe.slice(0, MAX_ERROR_TRANSPORT_VALUE_LENGTH);\n}\n\nexport function parseSourceControlOwnerRef(\n  headSelector: string,\n): SourceControlRefSelector | undefined {\n  const match = /^([^:/\\s]+):(.+)$/u.exec(headSelector.trim());\n  const owner = match?.[1]?.trim();\n  const refName = match?.[2]?.trim();\n  return owner && refName ? { owner, refName } : undefined;\n}\n\nexport function normalizeSourceBranch(headSelector: string): string {\n  return parseSourceControlOwnerRef(headSelector)?.refName ?? headSelector.trim();\n}\n\nexport function sourceBranch(input: {\n  readonly headSelector: string;\n  readonly source?: SourceControlRefSelector;\n}): string {\n  return input.source?.refName ?? normalizeSourceBranch(input.headSelector);\n}\n\nexport function sourceControlRefFromInput(input: {\n  readonly headSelector: string;\n  readonly source?: SourceControlRefSelector;\n}): SourceControlRefSelector | undefined {\n  return input.source ?? parseSourceControlOwnerRef(input.headSelector);\n}\n\nexport class SourceControlProvider extends Context.Service<\n  SourceControlProvider,\n  {\n    readonly kind: SourceControlProviderKind;\n    readonly listChangeRequests: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProviderContext;\n      readonly source?: SourceControlRefSelector;\n      readonly headSelector: string;\n      readonly state: ChangeRequestState | \"all\";\n      readonly limit?: number;\n    }) => Effect.Effect<ReadonlyArray<ChangeRequest>, SourceControlProviderError>;\n    readonly getChangeRequest: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProviderContext;\n      readonly reference: string;\n    }) => Effect.Effect<ChangeRequest, SourceControlProviderError>;\n    readonly createChangeRequest: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProviderContext;\n      readonly source?: SourceControlRefSelector;\n      readonly target?: SourceControlRefSelector;\n      readonly baseRefName: string;\n      readonly headSelector: string;\n      readonly title: string;\n      readonly bodyFile: string;\n    }) => Effect.Effect<void, SourceControlProviderError>;\n    readonly getRepositoryCloneUrls: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProviderContext;\n      readonly repository: string;\n    }) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;\n    readonly createRepository: (input: {\n      readonly cwd: string;\n      readonly repository: string;\n      readonly visibility: SourceControlRepositoryVisibility;\n    }) => Effect.Effect<SourceControlRepositoryCloneUrls, SourceControlProviderError>;\n    readonly getDefaultBranch: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProviderContext;\n    }) => Effect.Effect<string | null, SourceControlProviderError>;\n    readonly checkoutChangeRequest: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProviderContext;\n      readonly reference: string;\n      readonly force?: boolean;\n    }) => Effect.Effect<void, SourceControlProviderError>;\n  }\n>()(\"t3/sourceControl/SourceControlProvider\") {}\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport {\n  NonNegativeInt,\n  TrimmedNonEmptyString,\n  type SourceControlRepositoryVisibility,\n  type VcsError,\n} from \"@t3tools/contracts\";\n\nimport * as VcsProcess from \"../vcs/VcsProcess.ts\";\nimport {\n  decodeAzureDevOpsPullRequestJson,\n  decodeAzureDevOpsPullRequestListJson,\n  type NormalizedAzureDevOpsPullRequestRecord,\n} from \"./azureDevOpsPullRequests.ts\";\nimport * as SourceControlProvider from \"./SourceControlProvider.ts\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\nconst azureDevOpsCommandErrorFields = {\n  operation: Schema.Literal(\"execute\"),\n  command: Schema.Literal(\"az\"),\n  cwd: Schema.String,\n  argumentCount: NonNegativeInt,\n  cause: Schema.Defect(),\n};\n\nexport class AzureDevOpsCliUnavailableError extends Schema.TaggedErrorClass<AzureDevOpsCliUnavailableError>()(\n  \"AzureDevOpsCliUnavailableError\",\n  azureDevOpsCommandErrorFields,\n) {\n  get detail(): string {\n    return \"Azure CLI (`az`) with the Azure DevOps extension is required but not available on PATH.\";\n  }\n\n  override get message(): string {\n    return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class AzureDevOpsCliAuthenticationError extends Schema.TaggedErrorClass<AzureDevOpsCliAuthenticationError>()(\n  \"AzureDevOpsCliAuthenticationError\",\n  azureDevOpsCommandErrorFields,\n) {\n  get detail(): string {\n    return \"Azure DevOps CLI is not authenticated. Run `az devops login` and retry.\";\n  }\n\n  override get message(): string {\n    return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class AzureDevOpsPullRequestNotFoundError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestNotFoundError>()(\n  \"AzureDevOpsPullRequestNotFoundError\",\n  azureDevOpsCommandErrorFields,\n) {\n  get detail(): string {\n    return \"Pull request not found. Check the PR number or URL and try again.\";\n  }\n\n  override get message(): string {\n    return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class AzureDevOpsCommandFailedError extends Schema.TaggedErrorClass<AzureDevOpsCommandFailedError>()(\n  \"AzureDevOpsCommandFailedError\",\n  azureDevOpsCommandErrorFields,\n) {\n  get detail(): string {\n    return \"Azure DevOps CLI command failed.\";\n  }\n\n  override get message(): string {\n    return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;\n  }\n\n  static fromVcsError(\n    context: {\n      readonly operation: \"execute\";\n      readonly command: \"az\";\n      readonly cwd: string;\n      readonly argumentCount: number;\n    },\n    cause: VcsError,\n  ): AzureDevOpsCliError {\n    const fields = { ...context, cause };\n\n    if (\n      cause._tag === \"VcsProcessSpawnError\" &&\n      cause.cause instanceof PlatformError.PlatformError &&\n      cause.cause.reason._tag === \"NotFound\" &&\n      cause.cause.reason.pathOrDescriptor !== context.cwd &&\n      cause.cause.reason.syscall !== \"chdir\"\n    ) {\n      return new AzureDevOpsCliUnavailableError(fields);\n    }\n\n    if (cause._tag === \"VcsProcessExitError\") {\n      if (cause.failureKind === \"authentication\") {\n        return new AzureDevOpsCliAuthenticationError(fields);\n      }\n      if (cause.failureKind === \"not-found\") {\n        return new AzureDevOpsPullRequestNotFoundError(fields);\n      }\n    }\n\n    return new AzureDevOpsCommandFailedError(fields);\n  }\n}\n\nconst azureDevOpsDecodeErrorFields = {\n  command: Schema.Literal(\"az\"),\n  cwd: Schema.String,\n  outputLength: NonNegativeInt,\n  cause: Schema.Defect(),\n};\n\nexport class AzureDevOpsPullRequestListDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestListDecodeError>()(\n  \"AzureDevOpsPullRequestListDecodeError\",\n  {\n    operation: Schema.Literal(\"listPullRequests\"),\n    ...azureDevOpsDecodeErrorFields,\n  },\n) {\n  get detail(): string {\n    return \"Azure DevOps CLI returned invalid PR list JSON.\";\n  }\n\n  override get message(): string {\n    return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class AzureDevOpsPullRequestDecodeError extends Schema.TaggedErrorClass<AzureDevOpsPullRequestDecodeError>()(\n  \"AzureDevOpsPullRequestDecodeError\",\n  {\n    operation: Schema.Literal(\"getPullRequest\"),\n    ...azureDevOpsDecodeErrorFields,\n  },\n) {\n  get detail(): string {\n    return \"Azure DevOps CLI returned invalid pull request JSON.\";\n  }\n\n  override get message(): string {\n    return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nconst AzureDevOpsRepositoryDecodeOperation = Schema.Literals([\n  \"getRepositoryCloneUrls\",\n  \"getDefaultBranch\",\n  \"createRepository\",\n]);\n\nexport class AzureDevOpsRepositoryDecodeError extends Schema.TaggedErrorClass<AzureDevOpsRepositoryDecodeError>()(\n  \"AzureDevOpsRepositoryDecodeError\",\n  {\n    operation: AzureDevOpsRepositoryDecodeOperation,\n    ...azureDevOpsDecodeErrorFields,\n  },\n) {\n  get detail(): string {\n    return \"Azure DevOps CLI returned invalid repository JSON.\";\n  }\n\n  override get message(): string {\n    return `Azure DevOps CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport const AzureDevOpsCliError = Schema.Union([\n  AzureDevOpsCliUnavailableError,\n  AzureDevOpsCliAuthenticationError,\n  AzureDevOpsPullRequestNotFoundError,\n  AzureDevOpsCommandFailedError,\n  AzureDevOpsPullRequestListDecodeError,\n  AzureDevOpsPullRequestDecodeError,\n  AzureDevOpsRepositoryDecodeError,\n]);\nexport type AzureDevOpsCliError = typeof AzureDevOpsCliError.Type;\n\nexport const isAzureDevOpsCliError = Schema.is(AzureDevOpsCliError);\n\nexport interface AzureDevOpsRepositoryCloneUrls {\n  readonly nameWithOwner: string;\n  readonly url: string;\n  readonly sshUrl: string;\n}\n\nexport class AzureDevOpsCli extends Context.Service<\n  AzureDevOpsCli,\n  {\n    readonly execute: (input: {\n      readonly cwd: string;\n      readonly args: ReadonlyArray<string>;\n      readonly timeoutMs?: number;\n    }) => Effect.Effect<VcsProcess.VcsProcessOutput, AzureDevOpsCliError>;\n\n    readonly listPullRequests: (input: {\n      readonly cwd: string;\n      readonly headSelector: string;\n      readonly source?: SourceControlProvider.SourceControlRefSelector;\n      readonly state: \"open\" | \"closed\" | \"merged\" | \"all\";\n      readonly limit?: number;\n    }) => Effect.Effect<ReadonlyArray<NormalizedAzureDevOpsPullRequestRecord>, AzureDevOpsCliError>;\n\n    readonly getPullRequest: (input: {\n      readonly cwd: string;\n      readonly reference: string;\n    }) => Effect.Effect<NormalizedAzureDevOpsPullRequestRecord, AzureDevOpsCliError>;\n\n    readonly getRepositoryCloneUrls: (input: {\n      readonly cwd: string;\n      readonly repository: string;\n    }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;\n\n    readonly createRepository: (input: {\n      readonly cwd: string;\n      readonly repository: string;\n      readonly visibility: SourceControlRepositoryVisibility;\n    }) => Effect.Effect<AzureDevOpsRepositoryCloneUrls, AzureDevOpsCliError>;\n\n    readonly createPullRequest: (input: {\n      readonly cwd: string;\n      readonly baseBranch: string;\n      readonly headSelector: string;\n      readonly source?: SourceControlProvider.SourceControlRefSelector;\n      readonly target?: SourceControlProvider.SourceControlRefSelector;\n      readonly title: string;\n      readonly bodyFile: string;\n    }) => Effect.Effect<void, AzureDevOpsCliError>;\n\n    readonly getDefaultBranch: (input: {\n      readonly cwd: string;\n    }) => Effect.Effect<string | null, AzureDevOpsCliError>;\n\n    readonly checkoutPullRequest: (input: {\n      readonly cwd: string;\n      readonly reference: string;\n      readonly remoteName?: string;\n    }) => Effect.Effect<void, AzureDevOpsCliError>;\n  }\n>()(\"t3/sourceControl/AzureDevOpsCli\") {}\n\nfunction normalizeChangeRequestId(reference: string): string {\n  const trimmed = reference.trim().replace(/^#/, \"\");\n  const urlMatch = /(?:pullrequest|pull-request|pull|_pulls?)\\/(\\d+)(?:\\D.*)?$/i.exec(trimmed);\n  return urlMatch?.[1] ?? trimmed;\n}\n\nfunction toAzureStatus(state: \"open\" | \"closed\" | \"merged\" | \"all\"): string {\n  switch (state) {\n    case \"open\":\n      return \"active\";\n    case \"closed\":\n      return \"abandoned\";\n    case \"merged\":\n      return \"completed\";\n    case \"all\":\n      return \"all\";\n  }\n}\n\nconst RawAzureDevOpsRepositorySchema = Schema.Struct({\n  name: TrimmedNonEmptyString,\n  webUrl: TrimmedNonEmptyString,\n  remoteUrl: TrimmedNonEmptyString,\n  sshUrl: TrimmedNonEmptyString,\n  project: Schema.optional(\n    Schema.Struct({\n      name: TrimmedNonEmptyString,\n    }),\n  ),\n  defaultBranch: Schema.optional(Schema.NullOr(Schema.String)),\n});\n\nfunction normalizeDefaultBranch(value: string | null | undefined): string | null {\n  const trimmed = value?.trim().replace(/^refs\\/heads\\//, \"\") ?? \"\";\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeRepositoryCloneUrls(\n  raw: Schema.Schema.Type<typeof RawAzureDevOpsRepositorySchema>,\n): AzureDevOpsRepositoryCloneUrls {\n  const projectName = raw.project?.name.trim();\n  return {\n    nameWithOwner: projectName ? `${projectName}/${raw.name}` : raw.name,\n    url: raw.remoteUrl,\n    sshUrl: raw.sshUrl,\n  };\n}\n\nfunction parseRepositorySpecifier(repository: string): {\n  readonly project: string | null;\n  readonly name: string;\n} {\n  const parts: Array<string> = [];\n  for (const part of repository.split(\"/\")) {\n    const trimmed = part.trim();\n    if (trimmed.length > 0) {\n      parts.push(trimmed);\n    }\n  }\n  return {\n    project: parts.length > 1 ? (parts.at(-2) ?? null) : null,\n    name: parts.at(-1) ?? repository.trim(),\n  };\n}\n\nfunction decodeAzureDevOpsJson<S extends Schema.Top>(\n  raw: string,\n  schema: S,\n  operation: typeof AzureDevOpsRepositoryDecodeOperation.Type,\n  cwd: string,\n): Effect.Effect<S[\"Type\"], AzureDevOpsRepositoryDecodeError, S[\"DecodingServices\"]> {\n  return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(\n    Effect.mapError(\n      (cause) =>\n        new AzureDevOpsRepositoryDecodeError({\n          operation,\n          command: \"az\",\n          cwd,\n          outputLength: raw.length,\n          cause,\n        }),\n    ),\n  );\n}\n\nexport const make = Effect.gen(function* () {\n  const process = yield* VcsProcess.VcsProcess;\n\n  const execute: AzureDevOpsCli[\"Service\"][\"execute\"] = (input) =>\n    process\n      .run({\n        operation: \"AzureDevOpsCli.execute\",\n        command: \"az\",\n        args: input.args,\n        cwd: input.cwd,\n        timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n      })\n      .pipe(\n        Effect.mapError((error) =>\n          AzureDevOpsCommandFailedError.fromVcsError(\n            {\n              operation: \"execute\",\n              command: \"az\",\n              cwd: input.cwd,\n              argumentCount: input.args.length,\n            },\n            error,\n          ),\n        ),\n      );\n\n  const executeJson = (input: Parameters<AzureDevOpsCli[\"Service\"][\"execute\"]>[0]) =>\n    execute({\n      ...input,\n      args: [...input.args, \"--only-show-errors\", \"--output\", \"json\"],\n    });\n\n  return AzureDevOpsCli.of({\n    execute,\n    listPullRequests: (input) =>\n      executeJson({\n        cwd: input.cwd,\n        args: [\n          \"repos\",\n          \"pr\",\n          \"list\",\n          \"--detect\",\n          \"true\",\n          \"--source-branch\",\n          SourceControlProvider.sourceBranch(input),\n          \"--status\",\n          toAzureStatus(input.state),\n          \"--top\",\n          String(input.limit ?? 20),\n        ],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          raw.length === 0\n            ? Effect.succeed([])\n            : Effect.sync(() => decodeAzureDevOpsPullRequestListJson(raw)).pipe(\n                Effect.flatMap((decoded) => {\n                  if (!Result.isSuccess(decoded)) {\n                    return Effect.fail(\n                      new AzureDevOpsPullRequestListDecodeError({\n                        operation: \"listPullRequests\",\n                        command: \"az\",\n                        cwd: input.cwd,\n                        outputLength: raw.length,\n                        cause: decoded.failure,\n                      }),\n                    );\n                  }\n\n                  return Effect.succeed(decoded.success);\n                }),\n              ),\n        ),\n      ),\n    getPullRequest: (input) =>\n      executeJson({\n        cwd: input.cwd,\n        args: [\n          \"repos\",\n          \"pr\",\n          \"show\",\n          \"--detect\",\n          \"true\",\n          \"--id\",\n          normalizeChangeRequestId(input.reference),\n        ],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          Effect.sync(() => decodeAzureDevOpsPullRequestJson(raw)).pipe(\n            Effect.flatMap((decoded) => {\n              if (!Result.isSuccess(decoded)) {\n                return Effect.fail(\n                  new AzureDevOpsPullRequestDecodeError({\n                    operation: \"getPullRequest\",\n                    command: \"az\",\n                    cwd: input.cwd,\n                    outputLength: raw.length,\n                    cause: decoded.failure,\n                  }),\n                );\n              }\n\n              return Effect.succeed(decoded.success);\n            }),\n          ),\n        ),\n      ),\n    getRepositoryCloneUrls: (input) =>\n      executeJson({\n        cwd: input.cwd,\n        args: [\"repos\", \"show\", \"--detect\", \"true\", \"--repository\", input.repository],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          decodeAzureDevOpsJson(\n            raw,\n            RawAzureDevOpsRepositorySchema,\n            \"getRepositoryCloneUrls\",\n            input.cwd,\n          ),\n        ),\n        Effect.map(normalizeRepositoryCloneUrls),\n      ),\n    createRepository: (input) => {\n      const repository = parseRepositorySpecifier(input.repository);\n      // Azure Repos access is governed by project/organization permissions.\n      // `az repos create` does not expose a per-repository visibility flag, so\n      // the generic source-control visibility input is intentionally not\n      // translated into CLI args for this provider.\n      return executeJson({\n        cwd: input.cwd,\n        args: [\n          \"repos\",\n          \"create\",\n          \"--detect\",\n          \"true\",\n          \"--name\",\n          repository.name,\n          ...(repository.project ? [\"--project\", repository.project] : []),\n        ],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, \"createRepository\", input.cwd),\n        ),\n        Effect.map(normalizeRepositoryCloneUrls),\n      );\n    },\n    createPullRequest: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\n          \"repos\",\n          \"pr\",\n          \"create\",\n          \"--only-show-errors\",\n          \"--detect\",\n          \"true\",\n          \"--target-branch\",\n          input.target?.refName ?? input.baseBranch,\n          \"--source-branch\",\n          SourceControlProvider.sourceBranch(input),\n          \"--title\",\n          input.title,\n          \"--description\",\n          `@${input.bodyFile}`,\n        ],\n      }).pipe(Effect.asVoid),\n    getDefaultBranch: (input) =>\n      executeJson({\n        cwd: input.cwd,\n        args: [\"repos\", \"show\", \"--detect\", \"true\"],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          decodeAzureDevOpsJson(raw, RawAzureDevOpsRepositorySchema, \"getDefaultBranch\", input.cwd),\n        ),\n        Effect.map((repo) => normalizeDefaultBranch(repo.defaultBranch)),\n      ),\n    checkoutPullRequest: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\n          \"repos\",\n          \"pr\",\n          \"checkout\",\n          \"--only-show-errors\",\n          \"--detect\",\n          \"true\",\n          \"--id\",\n          normalizeChangeRequestId(input.reference),\n          \"--remote-name\",\n          input.remoteName ?? \"origin\",\n        ],\n      }).pipe(Effect.asVoid),\n  });\n});\n\nexport const layer = Layer.effect(AzureDevOpsCli, make);\n","import type {\n  SourceControlProviderAuth,\n  SourceControlProviderDiscoveryItem,\n  SourceControlProviderInfo,\n  SourceControlProviderKind,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\n\nimport type * as SourceControlProvider from \"./SourceControlProvider.ts\";\nimport type * as VcsProcess from \"../vcs/VcsProcess.ts\";\n\nexport interface SourceControlAuthProbeInput {\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly exitCode: VcsProcess.VcsProcessOutput[\"exitCode\"];\n}\n\nexport interface SourceControlUnknownRemoteRefinementInput {\n  readonly cwd: string;\n  readonly context: SourceControlProvider.SourceControlProviderContext;\n  readonly auth: SourceControlAuthProbeInput;\n}\n\ninterface SourceControlDiscoverySpecBase {\n  readonly kind: SourceControlProviderKind;\n  readonly label: string;\n  readonly installHint: string;\n}\n\nexport type SourceControlCliDiscoverySpec = SourceControlDiscoverySpecBase & {\n  readonly type: \"cli\";\n  readonly executable: string;\n  readonly versionArgs: ReadonlyArray<string>;\n  readonly authArgs: ReadonlyArray<string>;\n  readonly parseAuth: (input: SourceControlAuthProbeInput) => SourceControlProviderAuth;\n  readonly refineUnknownRemote?: (\n    input: SourceControlUnknownRemoteRefinementInput,\n  ) => SourceControlProviderInfo | null;\n};\n\nexport type SourceControlApiDiscoverySpec = SourceControlDiscoverySpecBase & {\n  readonly type: \"api\";\n  readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;\n};\n\nexport type SourceControlProviderDiscoverySpec =\n  | SourceControlCliDiscoverySpec\n  | SourceControlApiDiscoverySpec;\n\ntype SourceControlCliRemoteRefinementSpec = SourceControlCliDiscoverySpec & {\n  readonly refineUnknownRemote: NonNullable<SourceControlCliDiscoverySpec[\"refineUnknownRemote\"]>;\n};\n\ninterface DiscoveryProbeResult {\n  readonly kind: SourceControlProviderKind;\n  readonly label: string;\n  readonly executable: string;\n  readonly status: \"available\" | \"missing\";\n  readonly version: Option.Option<string>;\n  readonly installHint: string;\n  readonly detail: Option.Option<string>;\n}\n\nexport function firstNonEmptyLine(text: string): Option.Option<string> {\n  const line = text\n    .split(/\\r?\\n/)\n    .map((entry) => entry.trim())\n    .find((entry) => entry.length > 0);\n  return line === undefined ? Option.none() : Option.some(line);\n}\n\nexport function detailFromCause(cause: unknown): Option.Option<string> {\n  if (cause instanceof Error && cause.message.trim().length > 0) {\n    return Option.some(cause.message.trim());\n  }\n  return Option.none();\n}\n\nfunction authAccount(account: string | undefined): Option.Option<string> {\n  const trimmed = account?.trim();\n  return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);\n}\n\nfunction authHost(host: string | undefined): Option.Option<string> {\n  const trimmed = host?.trim();\n  return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);\n}\n\nfunction authDetail(detail: string | undefined): Option.Option<string> {\n  const trimmed = detail?.trim();\n  return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);\n}\n\nexport function providerAuth(input: {\n  readonly status: SourceControlProviderAuth[\"status\"];\n  readonly account?: string | undefined;\n  readonly host?: string | undefined;\n  readonly detail?: string | undefined;\n}): SourceControlProviderAuth {\n  return {\n    status: input.status,\n    account: authAccount(input.account),\n    host: authHost(input.host),\n    detail: authDetail(input.detail),\n  };\n}\n\nexport function unknownAuth(detail?: string): SourceControlProviderAuth {\n  return providerAuth({ status: \"unknown\", detail });\n}\n\nexport function combinedAuthOutput(input: SourceControlAuthProbeInput): string {\n  const parts: string[] = [];\n  for (const entry of [input.stdout, input.stderr]) {\n    if (entry.trim().length > 0) {\n      parts.push(entry);\n    }\n  }\n  return parts.join(\"\\n\");\n}\n\nfunction sanitizedAuthLines(text: string): ReadonlyArray<string> {\n  const lines: string[] = [];\n  for (const entry of text.split(/\\r?\\n/)) {\n    const line = entry.trim();\n    if (line.length === 0) continue;\n    if (/^[-\\s]*token(?:\\s+scopes?)?:/iu.test(line)) continue;\n    lines.push(line);\n  }\n  return lines;\n}\n\nexport function firstSafeAuthLine(text: string): string | undefined {\n  return sanitizedAuthLines(text)[0];\n}\n\nexport function parseCliHost(text: string): string | undefined {\n  return sanitizedAuthLines(text)\n    .map((line) => line.replace(/^[^a-z0-9]+/iu, \"\"))\n    .find((line) => /^[a-z0-9][a-z0-9.-]*(?::\\d+)?$/iu.test(line));\n}\n\nexport function matchFirst(text: string, patterns: ReadonlyArray<RegExp>): string | undefined {\n  for (const pattern of patterns) {\n    const match = pattern.exec(text);\n    const value = match?.[1]?.trim();\n    if (value && value.length > 0) return value;\n  }\n  return undefined;\n}\n\nfunction isCliRemoteRefinementSpec(\n  spec: SourceControlProviderDiscoverySpec,\n): spec is SourceControlCliRemoteRefinementSpec {\n  return spec.type === \"cli\" && spec.refineUnknownRemote !== undefined;\n}\n\nfunction probeCli(input: {\n  readonly spec: SourceControlCliDiscoverySpec;\n  readonly process: VcsProcess.VcsProcess[\"Service\"];\n  readonly cwd: string;\n}): Effect.Effect<DiscoveryProbeResult> {\n  return input.process\n    .run({\n      operation: \"source-control.discovery.probe\",\n      command: input.spec.executable,\n      args: input.spec.versionArgs,\n      cwd: input.cwd,\n      timeoutMs: 5_000,\n      maxOutputBytes: 8_000,\n      appendTruncationMarker: true,\n    })\n    .pipe(\n      Effect.map(\n        (result) =>\n          ({\n            kind: input.spec.kind,\n            label: input.spec.label,\n            executable: input.spec.executable,\n            status: \"available\" as const,\n            version: Option.orElse(firstNonEmptyLine(result.stdout), () =>\n              firstNonEmptyLine(result.stderr),\n            ),\n            installHint: input.spec.installHint,\n            detail: Option.none<string>(),\n          }) satisfies DiscoveryProbeResult,\n      ),\n      Effect.catch((cause) =>\n        Effect.succeed({\n          kind: input.spec.kind,\n          label: input.spec.label,\n          executable: input.spec.executable,\n          status: \"missing\" as const,\n          version: Option.none<string>(),\n          installHint: input.spec.installHint,\n          detail: detailFromCause(cause),\n        } satisfies DiscoveryProbeResult),\n      ),\n    );\n}\n\nexport function probeSourceControlProvider(input: {\n  readonly spec: SourceControlProviderDiscoverySpec;\n  readonly process: VcsProcess.VcsProcess[\"Service\"];\n  readonly cwd: string;\n}): Effect.Effect<SourceControlProviderDiscoveryItem> {\n  if (input.spec.type === \"api\") {\n    return input.spec.probeAuth.pipe(\n      Effect.map(\n        (auth) =>\n          ({\n            kind: input.spec.kind,\n            label: input.spec.label,\n            status: \"available\" as const,\n            version: Option.none<string>(),\n            installHint: input.spec.installHint,\n            detail: Option.none<string>(),\n            auth,\n          }) satisfies SourceControlProviderDiscoveryItem,\n      ),\n    );\n  }\n\n  const spec = input.spec;\n\n  return probeCli({\n    spec,\n    process: input.process,\n    cwd: input.cwd,\n  }).pipe(\n    Effect.flatMap((item) => {\n      if (item.status !== \"available\") {\n        return Effect.succeed({\n          ...item,\n          auth: unknownAuth(\"Hosting integration command was not found on the server PATH.\"),\n        } satisfies SourceControlProviderDiscoveryItem);\n      }\n\n      return input.process\n        .run({\n          operation: \"source-control.discovery.auth\",\n          command: spec.executable,\n          args: spec.authArgs,\n          cwd: input.cwd,\n          allowNonZeroExit: true,\n          timeoutMs: 5_000,\n          maxOutputBytes: 8_000,\n          appendTruncationMarker: true,\n        })\n        .pipe(\n          Effect.map(\n            (result) =>\n              ({\n                ...item,\n                auth: spec.parseAuth(result),\n              }) satisfies SourceControlProviderDiscoveryItem,\n          ),\n          Effect.catch((cause) =>\n            Effect.succeed({\n              ...item,\n              auth: unknownAuth(Option.getOrUndefined(detailFromCause(cause))),\n            } satisfies SourceControlProviderDiscoveryItem),\n          ),\n        );\n    }),\n  );\n}\n\nexport const refineUnknownRemoteProvider = Effect.fn(\"refineUnknownRemoteProvider\")(\n  function* (input: {\n    readonly specs: ReadonlyArray<SourceControlProviderDiscoverySpec>;\n    readonly process: VcsProcess.VcsProcess[\"Service\"];\n    readonly cwd: string;\n    readonly context: SourceControlProvider.SourceControlProviderContext | null;\n  }): Effect.fn.Return<SourceControlProvider.SourceControlProviderContext | null> {\n    if (input.context === null || input.context.provider.kind !== \"unknown\") {\n      return input.context;\n    }\n    const context = input.context;\n\n    const providers = yield* Effect.forEach(input.specs.filter(isCliRemoteRefinementSpec), (spec) =>\n      input.process\n        .run({\n          operation: \"source-control.discovery.refine-unknown-remote\",\n          command: spec.executable,\n          args: spec.authArgs,\n          cwd: input.cwd,\n          allowNonZeroExit: true,\n          timeoutMs: 5_000,\n          maxOutputBytes: 8_000,\n          appendTruncationMarker: true,\n        })\n        .pipe(\n          Effect.map((auth) =>\n            spec.refineUnknownRemote({\n              cwd: input.cwd,\n              context,\n              auth,\n            }),\n          ),\n          Effect.orElseSucceed(() => null),\n        ),\n    );\n    const provider = providers.find((candidate) => candidate !== null);\n\n    return provider ? { ...context, provider } : context;\n  },\n);\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { SourceControlProviderError, type ChangeRequest } from \"@t3tools/contracts\";\n\nimport * as AzureDevOpsCli from \"./AzureDevOpsCli.ts\";\nimport * as SourceControlProvider from \"./SourceControlProvider.ts\";\nimport {\n  combinedAuthOutput,\n  firstSafeAuthLine,\n  providerAuth,\n  type SourceControlAuthProbeInput,\n  type SourceControlCliDiscoverySpec,\n} from \"./SourceControlProviderDiscovery.ts\";\n\nfunction parseAzureAuth(input: SourceControlAuthProbeInput) {\n  const account = input.stdout.trim().split(/\\r?\\n/)[0]?.trim();\n\n  if (input.exitCode !== 0) {\n    return providerAuth({\n      status: \"unauthenticated\",\n      detail:\n        firstSafeAuthLine(combinedAuthOutput(input)) ?? \"Run `az login` to authenticate Azure CLI.\",\n    });\n  }\n\n  if (account !== undefined && account.length > 0) {\n    return providerAuth({\n      status: \"authenticated\",\n      account,\n      host: \"dev.azure.com\",\n    });\n  }\n\n  return providerAuth({\n    status: \"unknown\",\n    host: \"dev.azure.com\",\n    detail: \"Azure CLI account status could not be parsed.\",\n  });\n}\n\nexport const discovery = {\n  type: \"cli\",\n  kind: \"azure-devops\",\n  label: \"Azure DevOps\",\n  executable: \"az\",\n  versionArgs: [\"--version\"],\n  authArgs: [\"account\", \"show\", \"--query\", \"user.name\", \"-o\", \"tsv\"],\n  parseAuth: parseAzureAuth,\n  installHint:\n    \"Install the Azure command-line tools (`az`), then enable Azure DevOps support with `az extension add --name azure-devops`.\",\n} satisfies SourceControlCliDiscoverySpec;\n\nfunction toChangeRequest(summary: {\n  readonly number: number;\n  readonly title: string;\n  readonly url: string;\n  readonly baseRefName: string;\n  readonly headRefName: string;\n  readonly state: \"open\" | \"closed\" | \"merged\";\n  readonly updatedAt: ChangeRequest[\"updatedAt\"];\n}): ChangeRequest {\n  return {\n    provider: \"azure-devops\",\n    number: summary.number,\n    title: summary.title,\n    url: summary.url,\n    baseRefName: summary.baseRefName,\n    headRefName: summary.headRefName,\n    state: summary.state,\n    updatedAt: summary.updatedAt,\n    isCrossRepository: false,\n  };\n}\n\nexport const make = Effect.gen(function* () {\n  const azure = yield* AzureDevOpsCli.AzureDevOpsCli;\n\n  return SourceControlProvider.SourceControlProvider.of({\n    kind: \"azure-devops\",\n    listChangeRequests: (input) => {\n      const source = SourceControlProvider.sourceControlRefFromInput(input);\n      return azure\n        .listPullRequests({\n          cwd: input.cwd,\n          headSelector: input.headSelector,\n          ...(source !== undefined ? { source } : {}),\n          state: input.state,\n          ...(input.limit !== undefined ? { limit: input.limit } : {}),\n        })\n        .pipe(\n          Effect.map((items) => items.map(toChangeRequest)),\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"azure-devops\",\n                operation: \"listChangeRequests\",\n                command: error.command,\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.headSelector,\n                ),\n                detail: error.detail,\n                cause: error,\n              }),\n          ),\n        );\n    },\n    getChangeRequest: (input) =>\n      azure.getPullRequest(input).pipe(\n        Effect.map(toChangeRequest),\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"azure-devops\",\n              operation: \"getChangeRequest\",\n              command: error.command,\n              cwd: input.cwd,\n              reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.reference,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    createChangeRequest: (input) => {\n      const source = SourceControlProvider.sourceControlRefFromInput(input);\n      return azure\n        .createPullRequest({\n          cwd: input.cwd,\n          baseBranch: input.baseRefName,\n          headSelector: input.headSelector,\n          ...(source !== undefined ? { source } : {}),\n          ...(input.target !== undefined ? { target: input.target } : {}),\n          title: input.title,\n          bodyFile: input.bodyFile,\n        })\n        .pipe(\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"azure-devops\",\n                operation: \"createChangeRequest\",\n                command: error.command,\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.headSelector,\n                ),\n                detail: error.detail,\n                cause: error,\n              }),\n          ),\n        );\n    },\n    getRepositoryCloneUrls: (input) =>\n      azure.getRepositoryCloneUrls(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"azure-devops\",\n              operation: \"getRepositoryCloneUrls\",\n              command: error.command,\n              cwd: input.cwd,\n              repository: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.repository,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    createRepository: (input) =>\n      azure.createRepository(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"azure-devops\",\n              operation: \"createRepository\",\n              command: error.command,\n              cwd: input.cwd,\n              repository: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.repository,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    getDefaultBranch: (input) =>\n      azure.getDefaultBranch({ cwd: input.cwd }).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"azure-devops\",\n              operation: \"getDefaultBranch\",\n              command: error.command,\n              cwd: input.cwd,\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    checkoutChangeRequest: (input) =>\n      azure\n        .checkoutPullRequest({\n          cwd: input.cwd,\n          reference: input.reference,\n          ...(input.context !== undefined ? { remoteName: input.context.remoteName } : {}),\n        })\n        .pipe(\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"azure-devops\",\n                operation: \"checkoutChangeRequest\",\n                command: error.command,\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.reference,\n                ),\n                detail: error.detail,\n                cause: error,\n              }),\n          ),\n        ),\n  });\n});\n\nexport const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make);\n","import * as DateTime from \"effect/DateTime\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport { PositiveInt, TrimmedNonEmptyString } from \"@t3tools/contracts\";\n\nexport interface NormalizedBitbucketPullRequestRecord {\n  readonly number: number;\n  readonly title: string;\n  readonly url: string;\n  readonly baseRefName: string;\n  readonly headRefName: string;\n  readonly state: \"open\" | \"closed\" | \"merged\";\n  readonly updatedAt: Option.Option<DateTime.Utc>;\n  readonly isCrossRepository?: boolean;\n  readonly headRepositoryNameWithOwner?: string | null;\n  readonly headRepositoryOwnerLogin?: string | null;\n}\n\nexport const BitbucketRepositoryRefSchema = Schema.Struct({\n  full_name: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n  workspace: Schema.optional(\n    Schema.NullOr(\n      Schema.Struct({\n        slug: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n      }),\n    ),\n  ),\n});\n\nexport const BitbucketPullRequestBranchSchema = Schema.Struct({\n  repository: Schema.optional(Schema.NullOr(BitbucketRepositoryRefSchema)),\n  branch: Schema.Struct({\n    name: TrimmedNonEmptyString,\n  }),\n});\n\nexport const BitbucketPullRequestSchema = Schema.Struct({\n  id: PositiveInt,\n  title: TrimmedNonEmptyString,\n  state: Schema.optional(Schema.NullOr(Schema.String)),\n  updated_on: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),\n  links: Schema.Struct({\n    html: Schema.Struct({\n      href: TrimmedNonEmptyString,\n    }),\n  }),\n  source: BitbucketPullRequestBranchSchema,\n  destination: BitbucketPullRequestBranchSchema,\n});\n\nexport const BitbucketPullRequestListSchema = Schema.Struct({\n  values: Schema.Array(BitbucketPullRequestSchema),\n  next: Schema.optional(TrimmedNonEmptyString),\n});\n\nfunction trimOptionalString(value: string | null | undefined): string | null {\n  const trimmed = value?.trim() ?? \"\";\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction repositoryOwner(repository: Schema.Schema.Type<typeof BitbucketRepositoryRefSchema>) {\n  return (\n    trimOptionalString(repository.workspace?.slug) ??\n    (repository.full_name?.includes(\"/\") ? (repository.full_name.split(\"/\")[0] ?? null) : null)\n  );\n}\n\nfunction normalizeBitbucketPullRequestState(state: string | null | undefined) {\n  switch (state?.trim().toUpperCase()) {\n    case \"MERGED\":\n      return \"merged\" as const;\n    case \"DECLINED\":\n    case \"SUPERSEDED\":\n      return \"closed\" as const;\n    case \"OPEN\":\n    default:\n      return \"open\" as const;\n  }\n}\n\nexport function normalizeBitbucketPullRequestRecord(\n  raw: Schema.Schema.Type<typeof BitbucketPullRequestSchema>,\n): NormalizedBitbucketPullRequestRecord {\n  const headRepositoryNameWithOwner = trimOptionalString(raw.source.repository?.full_name);\n  const baseRepositoryNameWithOwner = trimOptionalString(raw.destination.repository?.full_name);\n  const headRepositoryOwnerLogin = raw.source.repository\n    ? repositoryOwner(raw.source.repository)\n    : null;\n  const isCrossRepository =\n    headRepositoryNameWithOwner !== null &&\n    baseRepositoryNameWithOwner !== null &&\n    headRepositoryNameWithOwner !== baseRepositoryNameWithOwner;\n\n  return {\n    number: raw.id,\n    title: raw.title,\n    url: raw.links.html.href,\n    baseRefName: raw.destination.branch.name,\n    headRefName: raw.source.branch.name,\n    state: normalizeBitbucketPullRequestState(raw.state),\n    updatedAt: raw.updated_on ?? Option.none(),\n    ...(isCrossRepository ? { isCrossRepository: true } : {}),\n    ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),\n    ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),\n  };\n}\n","import * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport {\n  NonNegativeInt,\n  TrimmedNonEmptyString,\n  type SourceControlProviderAuth,\n  type SourceControlRepositoryCloneUrls,\n  type SourceControlRepositoryVisibility,\n} from \"@t3tools/contracts\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/unstable/http\";\nimport { sanitizeBranchFragment } from \"@t3tools/shared/git\";\nimport { detectSourceControlProviderFromRemoteUrl } from \"@t3tools/shared/sourceControl\";\n\nimport {\n  BitbucketPullRequestListSchema,\n  BitbucketPullRequestSchema,\n  normalizeBitbucketPullRequestRecord,\n  type NormalizedBitbucketPullRequestRecord,\n} from \"./bitbucketPullRequests.ts\";\nimport * as SourceControlProvider from \"./SourceControlProvider.ts\";\nimport * as GitVcsDriver from \"../vcs/GitVcsDriver.ts\";\nimport * as VcsDriverRegistry from \"../vcs/VcsDriverRegistry.ts\";\n\nconst DEFAULT_API_BASE_URL = \"https://api.bitbucket.org/2.0\";\n\nconst BitbucketApiEnvConfig = Config.all({\n  baseUrl: Config.string(\"SYNAPTIC_BITBUCKET_API_BASE_URL\").pipe(\n    Config.withDefault(DEFAULT_API_BASE_URL),\n  ),\n  accessToken: Config.string(\"SYNAPTIC_BITBUCKET_ACCESS_TOKEN\").pipe(Config.option),\n  email: Config.string(\"SYNAPTIC_BITBUCKET_EMAIL\").pipe(Config.option),\n  apiToken: Config.string(\"SYNAPTIC_BITBUCKET_API_TOKEN\").pipe(Config.option),\n});\n\nconst BitbucketApiOperation = Schema.Literals([\n  \"resolveRepository\",\n  \"getRepository\",\n  \"getBranchingModel\",\n  \"getPullRequest\",\n  \"listPullRequests\",\n  \"createRepository\",\n  \"createPullRequest\",\n  \"probeAuth\",\n  \"checkoutPullRequest\",\n]);\ntype BitbucketApiOperation = typeof BitbucketApiOperation.Type;\n\nexport class BitbucketRepositoryLocatorError extends Schema.TaggedErrorClass<BitbucketRepositoryLocatorError>()(\n  \"BitbucketRepositoryLocatorError\",\n  {\n    repository: Schema.String,\n  },\n) {\n  override get message(): string {\n    return \"Bitbucket API failed in createRepository: Bitbucket repositories must be specified as workspace/repository.\";\n  }\n}\n\nexport class BitbucketRequestError extends Schema.TaggedErrorClass<BitbucketRequestError>()(\n  \"BitbucketRequestError\",\n  {\n    operation: BitbucketApiOperation,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Bitbucket API failed in ${this.operation}: Failed to send the Bitbucket request.`;\n  }\n}\n\nexport class BitbucketResponseError extends Schema.TaggedErrorClass<BitbucketResponseError>()(\n  \"BitbucketResponseError\",\n  {\n    operation: BitbucketApiOperation,\n    status: Schema.Int,\n    responseBodyLength: NonNegativeInt,\n  },\n) {\n  override get message(): string {\n    return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;\n  }\n}\n\nexport class BitbucketResponseBodyReadError extends Schema.TaggedErrorClass<BitbucketResponseBodyReadError>()(\n  \"BitbucketResponseBodyReadError\",\n  {\n    operation: BitbucketApiOperation,\n    status: Schema.Int,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Bitbucket API failed in ${this.operation}: Bitbucket returned HTTP ${this.status}.`;\n  }\n}\n\nexport class BitbucketResponseDecodeError extends Schema.TaggedErrorClass<BitbucketResponseDecodeError>()(\n  \"BitbucketResponseDecodeError\",\n  {\n    operation: BitbucketApiOperation,\n    status: Schema.Int,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Bitbucket API failed in ${this.operation}: Bitbucket returned invalid JSON for the requested resource.`;\n  }\n}\n\nexport class BitbucketRepositoryVcsResolveError extends Schema.TaggedErrorClass<BitbucketRepositoryVcsResolveError>()(\n  \"BitbucketRepositoryVcsResolveError\",\n  {\n    cwd: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Bitbucket API failed in resolveRepository: Failed to resolve VCS repository for ${this.cwd}.`;\n  }\n}\n\nexport class BitbucketRepositoryRemotesListError extends Schema.TaggedErrorClass<BitbucketRepositoryRemotesListError>()(\n  \"BitbucketRepositoryRemotesListError\",\n  {\n    cwd: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Bitbucket API failed in resolveRepository: Failed to list remotes for ${this.cwd}.`;\n  }\n}\n\nexport class BitbucketRepositoryRemoteNotFoundError extends Schema.TaggedErrorClass<BitbucketRepositoryRemoteNotFoundError>()(\n  \"BitbucketRepositoryRemoteNotFoundError\",\n  {\n    cwd: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Bitbucket API failed in resolveRepository: No Bitbucket repository remote was detected for ${this.cwd}.`;\n  }\n}\n\nexport class BitbucketPullRequestBodyReadError extends Schema.TaggedErrorClass<BitbucketPullRequestBodyReadError>()(\n  \"BitbucketPullRequestBodyReadError\",\n  {\n    cwd: Schema.String,\n    bodyFile: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Bitbucket API failed in createPullRequest: Failed to read pull request body file ${this.bodyFile}.`;\n  }\n}\n\nexport class BitbucketCheckoutError extends Schema.TaggedErrorClass<BitbucketCheckoutError>()(\n  \"BitbucketCheckoutError\",\n  {\n    cwd: Schema.String,\n    reference: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.\";\n  }\n}\n\nexport const BitbucketApiError = Schema.Union([\n  BitbucketRepositoryLocatorError,\n  BitbucketRequestError,\n  BitbucketResponseError,\n  BitbucketResponseBodyReadError,\n  BitbucketResponseDecodeError,\n  BitbucketRepositoryVcsResolveError,\n  BitbucketRepositoryRemotesListError,\n  BitbucketRepositoryRemoteNotFoundError,\n  BitbucketPullRequestBodyReadError,\n  BitbucketCheckoutError,\n]);\nexport type BitbucketApiError = typeof BitbucketApiError.Type;\nexport const isBitbucketApiError = Schema.is(BitbucketApiError);\n\nconst RawBitbucketRepositorySchema = Schema.Struct({\n  full_name: TrimmedNonEmptyString,\n  links: Schema.Struct({\n    html: Schema.optional(\n      Schema.Struct({\n        href: TrimmedNonEmptyString,\n      }),\n    ),\n    clone: Schema.optional(\n      Schema.Array(\n        Schema.Struct({\n          name: TrimmedNonEmptyString,\n          href: TrimmedNonEmptyString,\n        }),\n      ),\n    ),\n  }),\n  mainbranch: Schema.optional(\n    Schema.NullOr(\n      Schema.Struct({\n        name: TrimmedNonEmptyString,\n      }),\n    ),\n  ),\n});\n\nconst RawBitbucketBranchingModelSchema = Schema.Struct({\n  development: Schema.optional(\n    Schema.Struct({\n      branch: Schema.optional(\n        Schema.NullOr(\n          Schema.Struct({\n            name: Schema.optional(TrimmedNonEmptyString),\n          }),\n        ),\n      ),\n      is_valid: Schema.optional(Schema.Boolean),\n      name: Schema.optional(Schema.NullOr(Schema.String)),\n      use_mainbranch: Schema.optional(Schema.Boolean),\n    }),\n  ),\n});\n\nconst BitbucketUserSchema = Schema.Struct({\n  username: Schema.optional(TrimmedNonEmptyString),\n  display_name: Schema.optional(TrimmedNonEmptyString),\n  account_id: Schema.optional(TrimmedNonEmptyString),\n});\n\nexport interface BitbucketRepositoryLocator {\n  readonly workspace: string;\n  readonly repoSlug: string;\n}\n\nexport class BitbucketApi extends Context.Service<\n  BitbucketApi,\n  {\n    readonly probeAuth: Effect.Effect<SourceControlProviderAuth, never>;\n    readonly listPullRequests: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProvider.SourceControlProviderContext;\n      readonly headSelector: string;\n      readonly source?: SourceControlProvider.SourceControlRefSelector;\n      readonly state: \"open\" | \"closed\" | \"merged\" | \"all\";\n      readonly limit?: number;\n    }) => Effect.Effect<ReadonlyArray<NormalizedBitbucketPullRequestRecord>, BitbucketApiError>;\n    readonly getPullRequest: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProvider.SourceControlProviderContext;\n      readonly reference: string;\n    }) => Effect.Effect<NormalizedBitbucketPullRequestRecord, BitbucketApiError>;\n    readonly getRepositoryCloneUrls: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProvider.SourceControlProviderContext;\n      readonly repository: string;\n    }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;\n    readonly createRepository: (input: {\n      readonly cwd: string;\n      readonly repository: string;\n      readonly visibility: SourceControlRepositoryVisibility;\n    }) => Effect.Effect<SourceControlRepositoryCloneUrls, BitbucketApiError>;\n    readonly createPullRequest: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProvider.SourceControlProviderContext;\n      readonly baseBranch: string;\n      readonly headSelector: string;\n      readonly source?: SourceControlProvider.SourceControlRefSelector;\n      readonly target?: SourceControlProvider.SourceControlRefSelector;\n      readonly title: string;\n      readonly bodyFile: string;\n    }) => Effect.Effect<void, BitbucketApiError>;\n    readonly getDefaultBranch: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProvider.SourceControlProviderContext;\n    }) => Effect.Effect<string | null, BitbucketApiError>;\n    readonly checkoutPullRequest: (input: {\n      readonly cwd: string;\n      readonly context?: SourceControlProvider.SourceControlProviderContext;\n      readonly reference: string;\n      readonly force?: boolean;\n    }) => Effect.Effect<void, BitbucketApiError>;\n  }\n>()(\"t3/sourceControl/BitbucketApi\") {}\n\nfunction nonEmpty(value: string | undefined): Option.Option<string> {\n  const trimmed = value?.trim();\n  return trimmed === undefined || trimmed.length === 0 ? Option.none() : Option.some(trimmed);\n}\n\nfunction normalizeChangeRequestId(reference: string): string {\n  const trimmed = reference.trim().replace(/^#/, \"\");\n  const urlMatch = /(?:pull-requests|pullrequests|pull-request|pull|pr)\\/(\\d+)(?:\\D.*)?$/i.exec(\n    trimmed,\n  );\n  return urlMatch?.[1] ?? trimmed;\n}\n\nfunction sourceWorkspace(input: {\n  readonly headSelector: string;\n  readonly source?: SourceControlProvider.SourceControlRefSelector;\n}): string | undefined {\n  if (input.source?.owner) return input.source.owner;\n  return SourceControlProvider.parseSourceControlOwnerRef(input.headSelector)?.owner;\n}\n\nfunction toBitbucketStates(state: \"open\" | \"closed\" | \"merged\" | \"all\"): ReadonlyArray<string> {\n  switch (state) {\n    case \"open\":\n      return [\"OPEN\"];\n    case \"closed\":\n      return [\"DECLINED\", \"SUPERSEDED\"];\n    case \"merged\":\n      return [\"MERGED\"];\n    case \"all\":\n      return [\"OPEN\", \"MERGED\", \"DECLINED\", \"SUPERSEDED\"];\n  }\n}\n\nfunction bitbucketQueryString(filters: ReadonlyArray<string>): string {\n  return filters.join(\" AND \");\n}\n\nfunction bitbucketStateFilter(states: ReadonlyArray<string>): string {\n  return states.length === 1\n    ? `state = \"${states[0]}\"`\n    : `(${states.map((state) => `state = \"${state}\"`).join(\" OR \")})`;\n}\n\nfunction parseBitbucketRepositorySlug(value: string): BitbucketRepositoryLocator | null {\n  const normalized = value.trim().replace(/\\.git$/u, \"\");\n  const parts = normalized.split(\"/\").filter((part) => part.length > 0);\n  if (parts.length < 2) return null;\n  const workspace = parts.at(-2);\n  const repoSlug = parts.at(-1);\n  return workspace && repoSlug ? { workspace, repoSlug } : null;\n}\n\nfunction requireRepositoryLocator(\n  repository: string,\n): Effect.Effect<BitbucketRepositoryLocator, BitbucketApiError> {\n  const locator = parseBitbucketRepositorySlug(repository);\n  return locator\n    ? Effect.succeed(locator)\n    : Effect.fail(\n        new BitbucketRepositoryLocatorError({\n          repository,\n        }),\n      );\n}\n\nfunction parseBitbucketRemoteUrl(remoteUrl: string): BitbucketRepositoryLocator | null {\n  const trimmed = remoteUrl.trim();\n  if (trimmed.startsWith(\"git@\")) {\n    const pathStart = trimmed.indexOf(\":\");\n    return pathStart < 0 ? null : parseBitbucketRepositorySlug(trimmed.slice(pathStart + 1));\n  }\n\n  try {\n    return parseBitbucketRepositorySlug(new URL(trimmed).pathname);\n  } catch {\n    return null;\n  }\n}\n\nfunction normalizeRepositoryCloneUrls(\n  raw: typeof RawBitbucketRepositorySchema.Type,\n): SourceControlRepositoryCloneUrls {\n  const httpClone =\n    raw.links.clone?.find((entry) => entry.name.toLowerCase() === \"https\")?.href ??\n    raw.links.html?.href;\n  const sshClone = raw.links.clone?.find((entry) => entry.name.toLowerCase() === \"ssh\")?.href;\n\n  return {\n    nameWithOwner: raw.full_name,\n    url: httpClone ?? raw.links.html?.href ?? raw.full_name,\n    sshUrl: sshClone ?? httpClone ?? raw.full_name,\n  };\n}\n\nfunction defaultChangeRequestTargetBranch(input: {\n  readonly repository: typeof RawBitbucketRepositorySchema.Type;\n  readonly branchingModel: typeof RawBitbucketBranchingModelSchema.Type | null;\n}): string | null {\n  const repositoryMainBranch = input.repository.mainbranch?.name ?? null;\n  const development = input.branchingModel?.development;\n  if (!development || development.use_mainbranch === true || development.is_valid === false) {\n    return repositoryMainBranch;\n  }\n\n  const developmentBranch = development.branch?.name?.trim() ?? development.name?.trim() ?? \"\";\n  if (developmentBranch.length === 0 || developmentBranch === \"null\") {\n    return repositoryMainBranch;\n  }\n\n  return developmentBranch;\n}\n\nfunction shouldPreferSshRemote(originRemoteUrl: string | null): boolean {\n  const trimmed = originRemoteUrl?.trim() ?? \"\";\n  return trimmed.startsWith(\"git@\") || trimmed.startsWith(\"ssh://\");\n}\n\nfunction selectCloneUrl(input: {\n  readonly cloneUrls: SourceControlRepositoryCloneUrls;\n  readonly originRemoteUrl: string | null;\n}): string {\n  return shouldPreferSshRemote(input.originRemoteUrl)\n    ? input.cloneUrls.sshUrl\n    : input.cloneUrls.url;\n}\n\nfunction checkoutBranchName(input: {\n  readonly pullRequestId: number;\n  readonly headBranch: string;\n  readonly isCrossRepository: boolean;\n}): string {\n  if (!input.isCrossRepository) {\n    return input.headBranch;\n  }\n\n  return `synaptic/pr-${input.pullRequestId}/${sanitizeBranchFragment(input.headBranch)}`;\n}\n\nfunction repositoryNameWithOwner(\n  repository: Schema.Schema.Type<typeof BitbucketPullRequestSchema>[\"source\"][\"repository\"],\n): string | null {\n  const fullName = repository?.full_name?.trim() ?? \"\";\n  return fullName.length > 0 ? fullName : null;\n}\n\nfunction repositoryOwnerName(repositoryName: string): string {\n  return repositoryName.split(\"/\")[0]?.trim() || \"bitbucket\";\n}\n\nfunction authFromConfig(\n  config: Config.Success<typeof BitbucketApiEnvConfig>,\n): SourceControlProviderAuth {\n  if (Option.isSome(config.accessToken)) {\n    return {\n      status: \"unknown\",\n      account: Option.none(),\n      host: Option.some(\"bitbucket.org\"),\n      detail: Option.some(\"Bitbucket access token is configured.\"),\n    };\n  }\n\n  if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {\n    return {\n      status: \"unknown\",\n      account: config.email,\n      host: Option.some(\"bitbucket.org\"),\n      detail: Option.some(\"Bitbucket API token is configured.\"),\n    };\n  }\n\n  return {\n    status: \"unauthenticated\",\n    account: Option.none(),\n    host: Option.some(\"bitbucket.org\"),\n    detail: Option.some(\n      \"Set SYNAPTIC_BITBUCKET_EMAIL and SYNAPTIC_BITBUCKET_API_TOKEN, or SYNAPTIC_BITBUCKET_ACCESS_TOKEN.\",\n    ),\n  };\n}\n\nfunction responseError(\n  operation: BitbucketApiOperation,\n  response: HttpClientResponse.HttpClientResponse,\n): Effect.Effect<never, BitbucketApiError> {\n  return response.text.pipe(\n    Effect.mapError(\n      (cause) =>\n        new BitbucketResponseBodyReadError({\n          operation,\n          status: response.status,\n          cause,\n        }),\n    ),\n    Effect.flatMap((body) =>\n      Effect.fail(\n        new BitbucketResponseError({\n          operation,\n          status: response.status,\n          responseBodyLength: body.length,\n        }),\n      ),\n    ),\n  );\n}\n\nexport const make = Effect.gen(function* () {\n  const config = yield* BitbucketApiEnvConfig;\n  const httpClient = yield* HttpClient.HttpClient;\n  const fileSystem = yield* FileSystem.FileSystem;\n  const git = yield* GitVcsDriver.GitVcsDriver;\n  const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;\n\n  const apiUrl = (path: string) => `${config.baseUrl.replace(/\\/+$/u, \"\")}${path}`;\n\n  const withAuth = (request: HttpClientRequest.HttpClientRequest) => {\n    if (Option.isSome(config.accessToken)) {\n      return request.pipe(HttpClientRequest.bearerToken(config.accessToken.value));\n    }\n    if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {\n      return request.pipe(HttpClientRequest.basicAuth(config.email.value, config.apiToken.value));\n    }\n    return request;\n  };\n\n  const decodeResponse = <S extends Schema.Top>(\n    operation: BitbucketApiOperation,\n    schema: S,\n    response: HttpClientResponse.HttpClientResponse,\n  ): Effect.Effect<S[\"Type\"], BitbucketApiError, S[\"DecodingServices\"]> =>\n    HttpClientResponse.matchStatus({\n      \"2xx\": (success) =>\n        HttpClientResponse.schemaBodyJson(schema)(success).pipe(\n          Effect.mapError(\n            (cause) =>\n              new BitbucketResponseDecodeError({\n                operation,\n                status: success.status,\n                cause,\n              }),\n          ),\n        ),\n      orElse: (failed) => responseError(operation, failed),\n    })(response);\n\n  const executeJson = <S extends Schema.Top>(\n    operation: BitbucketApiOperation,\n    request: HttpClientRequest.HttpClientRequest,\n    schema: S,\n  ): Effect.Effect<S[\"Type\"], BitbucketApiError, S[\"DecodingServices\"]> =>\n    httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(\n      Effect.mapError(\n        (cause) =>\n          new BitbucketRequestError({\n            operation,\n            cause,\n          }),\n      ),\n      Effect.flatMap((response) => decodeResponse(operation, schema, response)),\n    );\n\n  const resolveRepository = Effect.fn(\"BitbucketApi.resolveRepository\")(function* (input: {\n    readonly cwd: string;\n    readonly context?: SourceControlProvider.SourceControlProviderContext;\n    readonly repository?: string;\n  }) {\n    const fromRepository =\n      input.repository !== undefined ? parseBitbucketRepositorySlug(input.repository) : null;\n    if (fromRepository) return fromRepository;\n\n    const fromContext =\n      input.context?.provider.kind === \"bitbucket\"\n        ? parseBitbucketRemoteUrl(input.context.remoteUrl)\n        : null;\n    if (fromContext) return fromContext;\n\n    const handle = yield* vcsRegistry.resolve({ cwd: input.cwd }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new BitbucketRepositoryVcsResolveError({\n            cwd: input.cwd,\n            cause,\n          }),\n      ),\n    );\n    const remotes = yield* handle.driver.listRemotes(input.cwd).pipe(\n      Effect.mapError(\n        (cause) =>\n          new BitbucketRepositoryRemotesListError({\n            cwd: input.cwd,\n            cause,\n          }),\n      ),\n    );\n\n    for (const remote of remotes.remotes) {\n      if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== \"bitbucket\") continue;\n      const parsed = parseBitbucketRemoteUrl(remote.url);\n      if (parsed) return parsed;\n    }\n\n    return yield* new BitbucketRepositoryRemoteNotFoundError({\n      cwd: input.cwd,\n    });\n  });\n\n  const getRepositoryFromLocator = (repository: BitbucketRepositoryLocator) =>\n    executeJson(\n      \"getRepository\",\n      HttpClientRequest.get(\n        apiUrl(\n          `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,\n        ),\n      ),\n      RawBitbucketRepositorySchema,\n    );\n\n  const getRepository = (input: {\n    readonly cwd: string;\n    readonly context?: SourceControlProvider.SourceControlProviderContext;\n    readonly repository?: string;\n  }) => resolveRepository(input).pipe(Effect.flatMap(getRepositoryFromLocator));\n\n  const getBranchingModelFromLocator = (repository: BitbucketRepositoryLocator) =>\n    executeJson(\n      \"getBranchingModel\",\n      HttpClientRequest.get(\n        apiUrl(\n          `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/branching-model`,\n        ),\n      ),\n      RawBitbucketBranchingModelSchema,\n    );\n\n  const getRawPullRequestFromRepository = (\n    repository: BitbucketRepositoryLocator,\n    reference: string,\n  ) =>\n    executeJson(\n      \"getPullRequest\",\n      HttpClientRequest.get(\n        apiUrl(\n          `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests/${encodeURIComponent(normalizeChangeRequestId(reference))}`,\n        ),\n      ),\n      BitbucketPullRequestSchema,\n    );\n\n  const getRawPullRequest = (input: {\n    readonly cwd: string;\n    readonly context?: SourceControlProvider.SourceControlProviderContext;\n    readonly reference: string;\n  }) =>\n    resolveRepository(input).pipe(\n      Effect.flatMap((repository) => getRawPullRequestFromRepository(repository, input.reference)),\n    );\n\n  const readConfigValueNullable = (cwd: string, key: string) =>\n    git.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));\n\n  const resolveCheckoutRemote = Effect.fn(\"BitbucketApi.resolveCheckoutRemote\")(function* (input: {\n    readonly cwd: string;\n    readonly context?: SourceControlProvider.SourceControlProviderContext;\n    readonly destinationRepository: BitbucketRepositoryLocator;\n    readonly sourceRepositoryName: string;\n    readonly isCrossRepository: boolean;\n  }) {\n    if (\n      input.context?.provider.kind === \"bitbucket\" &&\n      !input.isCrossRepository &&\n      parseBitbucketRemoteUrl(input.context.remoteUrl) !== null\n    ) {\n      return input.context.remoteName;\n    }\n\n    if (!input.isCrossRepository) {\n      const remoteName = yield* git\n        .resolvePrimaryRemoteName(input.cwd)\n        .pipe(Effect.orElseSucceed(() => null));\n      if (remoteName) return remoteName;\n    }\n\n    const cloneUrls = yield* getRepository({\n      cwd: input.cwd,\n      repository: input.sourceRepositoryName,\n      ...(input.context ? { context: input.context } : {}),\n    }).pipe(Effect.map(normalizeRepositoryCloneUrls));\n    const originRemoteUrl = yield* readConfigValueNullable(input.cwd, \"remote.origin.url\");\n    return yield* git.ensureRemote({\n      cwd: input.cwd,\n      preferredName: input.isCrossRepository\n        ? repositoryOwnerName(input.sourceRepositoryName)\n        : input.destinationRepository.workspace,\n      url: selectCloneUrl({ cloneUrls, originRemoteUrl }),\n    });\n  });\n\n  return BitbucketApi.of({\n    probeAuth: executeJson(\n      \"probeAuth\",\n      HttpClientRequest.get(apiUrl(\"/user\")),\n      BitbucketUserSchema,\n    ).pipe(\n      Effect.map((user) => ({\n        status: \"authenticated\" as const,\n        account: nonEmpty(user.username ?? user.display_name ?? user.account_id),\n        host: Option.some(\"bitbucket.org\"),\n        detail: Option.none<string>(),\n      })),\n      Effect.orElseSucceed(() => authFromConfig(config)),\n    ),\n    listPullRequests: (input) =>\n      resolveRepository(input).pipe(\n        Effect.flatMap((repository) => {\n          const states = toBitbucketStates(input.state);\n          const query: Record<string, string | ReadonlyArray<string>> = {\n            pagelen: String(Math.max(1, Math.min(input.limit ?? 20, 50))),\n            sort: \"-updated_on\",\n            q: bitbucketQueryString([\n              `source.branch.name = \"${SourceControlProvider.sourceBranch(input).replaceAll('\"', '\\\\\"')}\"`,\n              bitbucketStateFilter(states),\n            ]),\n            state: states,\n          };\n\n          return executeJson(\n            \"listPullRequests\",\n            HttpClientRequest.get(\n              apiUrl(\n                `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,\n              ),\n              { urlParams: query },\n            ),\n            BitbucketPullRequestListSchema,\n          );\n        }),\n        Effect.map((list) => list.values.map(normalizeBitbucketPullRequestRecord)),\n      ),\n    getPullRequest: (input) =>\n      getRawPullRequest(input).pipe(Effect.map(normalizeBitbucketPullRequestRecord)),\n    getRepositoryCloneUrls: (input) =>\n      getRepository(input).pipe(Effect.map(normalizeRepositoryCloneUrls)),\n    createRepository: (input) =>\n      requireRepositoryLocator(input.repository).pipe(\n        Effect.flatMap((repository) =>\n          executeJson(\n            \"createRepository\",\n            HttpClientRequest.post(\n              apiUrl(\n                `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}`,\n              ),\n            ).pipe(\n              HttpClientRequest.bodyJsonUnsafe({\n                scm: \"git\",\n                is_private: input.visibility === \"private\",\n              }),\n            ),\n            RawBitbucketRepositorySchema,\n          ),\n        ),\n        Effect.map(normalizeRepositoryCloneUrls),\n      ),\n    createPullRequest: (input) =>\n      Effect.gen(function* () {\n        const repository = yield* resolveRepository(input);\n        const description = yield* fileSystem.readFileString(input.bodyFile).pipe(\n          Effect.mapError(\n            (cause) =>\n              new BitbucketPullRequestBodyReadError({\n                cwd: input.cwd,\n                bodyFile: input.bodyFile,\n                cause,\n              }),\n          ),\n        );\n        const sourceOwner = sourceWorkspace(input);\n        const body = {\n          title: input.title,\n          description,\n          source: {\n            branch: {\n              name: SourceControlProvider.sourceBranch(input),\n            },\n            ...(sourceOwner\n              ? {\n                  repository: {\n                    full_name: `${sourceOwner}/${input.source?.repository ?? repository.repoSlug}`,\n                  },\n                }\n              : {}),\n          },\n          destination: {\n            branch: {\n              name: input.target?.refName ?? input.baseBranch,\n            },\n          },\n        };\n\n        yield* executeJson(\n          \"createPullRequest\",\n          HttpClientRequest.post(\n            apiUrl(\n              `/repositories/${encodeURIComponent(repository.workspace)}/${encodeURIComponent(repository.repoSlug)}/pullrequests`,\n            ),\n          ).pipe(HttpClientRequest.bodyJsonUnsafe(body)),\n          BitbucketPullRequestSchema,\n        );\n      }),\n    getDefaultBranch: (input) =>\n      resolveRepository(input).pipe(\n        Effect.flatMap((locator) =>\n          Effect.all(\n            {\n              repository: getRepositoryFromLocator(locator),\n              branchingModel: getBranchingModelFromLocator(locator).pipe(\n                Effect.orElseSucceed(\n                  (): typeof RawBitbucketBranchingModelSchema.Type | null => null,\n                ),\n              ),\n            },\n            { concurrency: \"unbounded\" },\n          ),\n        ),\n        Effect.map(defaultChangeRequestTargetBranch),\n      ),\n    // Bitbucket Cloud pull requests are Git-backed and Bitbucket does not provide\n    // an official checkout CLI. This provider-local path uses GitVcsDriver as a\n    // narrow escape hatch to materialize Bitbucket PR refs. Do not generalize this\n    // as the source-control provider model: if we support non-Git-compatible\n    // hosting providers or native JJ/Sapling checkout flows, move this into a\n    // VCS-specific change-request checkout capability.\n    checkoutPullRequest: (input) =>\n      Effect.gen(function* () {\n        const destinationRepository = yield* resolveRepository(input);\n        const pullRequest = yield* getRawPullRequestFromRepository(\n          destinationRepository,\n          input.reference,\n        );\n        const destinationRepositoryName =\n          repositoryNameWithOwner(pullRequest.destination.repository) ??\n          `${destinationRepository.workspace}/${destinationRepository.repoSlug}`;\n        const sourceRepositoryName =\n          repositoryNameWithOwner(pullRequest.source.repository) ?? destinationRepositoryName;\n        const isCrossRepository = sourceRepositoryName !== destinationRepositoryName;\n        const remoteName = yield* resolveCheckoutRemote({\n          cwd: input.cwd,\n          destinationRepository,\n          sourceRepositoryName,\n          isCrossRepository,\n          ...(input.context ? { context: input.context } : {}),\n        });\n        const remoteBranch = pullRequest.source.branch.name;\n        const localBranch = checkoutBranchName({\n          pullRequestId: pullRequest.id,\n          headBranch: remoteBranch,\n          isCrossRepository,\n        });\n        const localBranchNames = yield* git.listLocalBranchNames(input.cwd);\n        const localBranchExists = localBranchNames.includes(localBranch);\n\n        if (input.force === true || !localBranchExists) {\n          yield* git.fetchRemoteBranch({\n            cwd: input.cwd,\n            remoteName,\n            remoteBranch,\n            localBranch,\n          });\n        } else {\n          yield* git.fetchRemoteTrackingBranch({\n            cwd: input.cwd,\n            remoteName,\n            remoteBranch,\n          });\n        }\n\n        yield* git.setBranchUpstream({\n          cwd: input.cwd,\n          branch: localBranch,\n          remoteName,\n          remoteBranch,\n        });\n        yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));\n      }).pipe(\n        Effect.mapError((cause) =>\n          isBitbucketApiError(cause)\n            ? cause\n            : new BitbucketCheckoutError({\n                cwd: input.cwd,\n                reference: input.reference,\n                cause,\n              }),\n        ),\n      ),\n  });\n});\n\nexport const layer = Layer.effect(BitbucketApi, make);\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport { SourceControlProviderError, type ChangeRequest } from \"@t3tools/contracts\";\n\nimport * as BitbucketApi from \"./BitbucketApi.ts\";\nimport type { NormalizedBitbucketPullRequestRecord } from \"./bitbucketPullRequests.ts\";\nimport * as SourceControlProvider from \"./SourceControlProvider.ts\";\nimport type { SourceControlApiDiscoverySpec } from \"./SourceControlProviderDiscovery.ts\";\n\nfunction toChangeRequest(summary: NormalizedBitbucketPullRequestRecord): ChangeRequest {\n  return {\n    provider: \"bitbucket\",\n    number: summary.number,\n    title: summary.title,\n    url: summary.url,\n    baseRefName: summary.baseRefName,\n    headRefName: summary.headRefName,\n    state: summary.state,\n    updatedAt: summary.updatedAt ?? Option.none(),\n    ...(summary.isCrossRepository !== undefined\n      ? { isCrossRepository: summary.isCrossRepository }\n      : {}),\n    ...(summary.headRepositoryNameWithOwner !== undefined\n      ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }\n      : {}),\n    ...(summary.headRepositoryOwnerLogin !== undefined\n      ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }\n      : {}),\n  };\n}\n\nexport const make = Effect.gen(function* () {\n  const bitbucket = yield* BitbucketApi.BitbucketApi;\n\n  return SourceControlProvider.SourceControlProvider.of({\n    kind: \"bitbucket\",\n    listChangeRequests: (input) => {\n      const source = SourceControlProvider.sourceControlRefFromInput(input);\n      return bitbucket\n        .listPullRequests({\n          cwd: input.cwd,\n          ...(input.context ? { context: input.context } : {}),\n          headSelector: input.headSelector,\n          ...(source ? { source } : {}),\n          state: input.state,\n          ...(input.limit !== undefined ? { limit: input.limit } : {}),\n        })\n        .pipe(\n          Effect.map((items) => items.map(toChangeRequest)),\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"bitbucket\",\n                operation: \"listChangeRequests\",\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.headSelector,\n                ),\n                detail: \"Failed to list change requests.\",\n                cause: error,\n              }),\n          ),\n        );\n    },\n    getChangeRequest: (input) =>\n      bitbucket.getPullRequest(input).pipe(\n        Effect.map(toChangeRequest),\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"bitbucket\",\n              operation: \"getChangeRequest\",\n              cwd: input.cwd,\n              reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.reference,\n              ),\n              detail: \"Failed to get change request.\",\n              cause: error,\n            }),\n        ),\n      ),\n    createChangeRequest: (input) => {\n      const source = SourceControlProvider.sourceControlRefFromInput(input);\n      return bitbucket\n        .createPullRequest({\n          cwd: input.cwd,\n          ...(input.context ? { context: input.context } : {}),\n          baseBranch: input.baseRefName,\n          headSelector: input.headSelector,\n          ...(source ? { source } : {}),\n          ...(input.target ? { target: input.target } : {}),\n          title: input.title,\n          bodyFile: input.bodyFile,\n        })\n        .pipe(\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"bitbucket\",\n                operation: \"createChangeRequest\",\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.headSelector,\n                ),\n                detail: \"Failed to create change request.\",\n                cause: error,\n              }),\n          ),\n        );\n    },\n    getRepositoryCloneUrls: (input) =>\n      bitbucket.getRepositoryCloneUrls(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"bitbucket\",\n              operation: \"getRepositoryCloneUrls\",\n              cwd: input.cwd,\n              repository: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.repository,\n              ),\n              detail: \"Failed to get repository clone URLs.\",\n              cause: error,\n            }),\n        ),\n      ),\n    createRepository: (input) =>\n      bitbucket.createRepository(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"bitbucket\",\n              operation: \"createRepository\",\n              cwd: input.cwd,\n              repository: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.repository,\n              ),\n              detail: \"Failed to create repository.\",\n              cause: error,\n            }),\n        ),\n      ),\n    getDefaultBranch: (input) =>\n      bitbucket\n        .getDefaultBranch({\n          cwd: input.cwd,\n          ...(input.context ? { context: input.context } : {}),\n        })\n        .pipe(\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"bitbucket\",\n                operation: \"getDefaultBranch\",\n                cwd: input.cwd,\n                detail: \"Failed to get default branch.\",\n                cause: error,\n              }),\n          ),\n        ),\n    checkoutChangeRequest: (input) =>\n      bitbucket\n        .checkoutPullRequest({\n          cwd: input.cwd,\n          ...(input.context ? { context: input.context } : {}),\n          reference: input.reference,\n          ...(input.force !== undefined ? { force: input.force } : {}),\n        })\n        .pipe(\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"bitbucket\",\n                operation: \"checkoutChangeRequest\",\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.reference,\n                ),\n                detail: \"Failed to check out change request.\",\n                cause: error,\n              }),\n          ),\n        ),\n  });\n});\n\nexport const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make);\n\nexport const makeDiscovery = Effect.gen(function* () {\n  const bitbucket = yield* BitbucketApi.BitbucketApi;\n\n  return {\n    type: \"api\",\n    kind: \"bitbucket\",\n    label: \"Bitbucket\",\n    installHint:\n      \"Set SYNAPTIC_BITBUCKET_EMAIL and SYNAPTIC_BITBUCKET_API_TOKEN on the server (use a Bitbucket API token with pull request and repository scopes).\",\n    probeAuth: bitbucket.probeAuth,\n  } satisfies SourceControlApiDiscoverySpec;\n});\n","import * as Cause from \"effect/Cause\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { PositiveInt, TrimmedNonEmptyString } from \"@t3tools/contracts\";\nimport { decodeJsonResult, formatSchemaError } from \"@t3tools/shared/schemaJson\";\n\nexport interface NormalizedGitHubPullRequestRecord {\n  readonly number: number;\n  readonly title: string;\n  readonly url: string;\n  readonly baseRefName: string;\n  readonly headRefName: string;\n  readonly state: \"open\" | \"closed\" | \"merged\";\n  readonly updatedAt: Option.Option<DateTime.Utc>;\n  readonly isCrossRepository?: boolean;\n  readonly headRepositoryNameWithOwner?: string | null;\n  readonly headRepositoryOwnerLogin?: string | null;\n}\n\nconst GitHubPullRequestSchema = Schema.Struct({\n  number: PositiveInt,\n  title: TrimmedNonEmptyString,\n  url: TrimmedNonEmptyString,\n  baseRefName: TrimmedNonEmptyString,\n  headRefName: TrimmedNonEmptyString,\n  state: Schema.optional(Schema.NullOr(Schema.String)),\n  mergedAt: Schema.optional(Schema.NullOr(Schema.String)),\n  updatedAt: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),\n  isCrossRepository: Schema.optional(Schema.Boolean),\n  // gh < 2.47 exports headRepository as {id, name} only; nameWithOwner was\n  // added later. Both fields stay optional so a version-drifted gh CLI can\n  // never fail the decode and silently drop the PR from the list.\n  headRepository: Schema.optional(\n    Schema.NullOr(\n      Schema.Struct({\n        nameWithOwner: Schema.optional(Schema.NullOr(Schema.String)),\n        name: Schema.optional(Schema.NullOr(Schema.String)),\n      }),\n    ),\n  ),\n  headRepositoryOwner: Schema.optional(\n    Schema.NullOr(\n      Schema.Struct({\n        login: Schema.optional(Schema.NullOr(Schema.String)),\n      }),\n    ),\n  ),\n});\n\nfunction trimOptionalString(value: string | null | undefined): string | null {\n  const trimmed = value?.trim() ?? \"\";\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeGitHubPullRequestState(input: {\n  state?: string | null | undefined;\n  mergedAt?: string | null | undefined;\n}): \"open\" | \"closed\" | \"merged\" {\n  const normalizedState = input.state?.trim().toUpperCase();\n  if (\n    (typeof input.mergedAt === \"string\" && input.mergedAt.trim().length > 0) ||\n    normalizedState === \"MERGED\"\n  ) {\n    return \"merged\";\n  }\n  if (normalizedState === \"CLOSED\") {\n    return \"closed\";\n  }\n  return \"open\";\n}\n\nfunction normalizeGitHubPullRequestRecord(\n  raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,\n): NormalizedGitHubPullRequestRecord {\n  const explicitNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);\n  const headRepositoryName = trimOptionalString(raw.headRepository?.name);\n  const headRepositoryOwnerLogin =\n    trimOptionalString(raw.headRepositoryOwner?.login) ??\n    (explicitNameWithOwner?.includes(\"/\") ? (explicitNameWithOwner.split(\"/\")[0] ?? null) : null);\n  const headRepositoryNameWithOwner =\n    explicitNameWithOwner ??\n    (headRepositoryOwnerLogin && headRepositoryName\n      ? `${headRepositoryOwnerLogin}/${headRepositoryName}`\n      : null);\n\n  return {\n    number: raw.number,\n    title: raw.title,\n    url: raw.url,\n    baseRefName: raw.baseRefName,\n    headRefName: raw.headRefName,\n    state: normalizeGitHubPullRequestState(raw),\n    updatedAt: raw.updatedAt ?? Option.none(),\n    ...(typeof raw.isCrossRepository === \"boolean\"\n      ? { isCrossRepository: raw.isCrossRepository }\n      : {}),\n    ...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),\n    ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),\n  };\n}\n\nconst decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));\nconst decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);\nconst decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);\n\nexport const formatGitHubJsonDecodeError = formatSchemaError;\n\nexport function decodeGitHubPullRequestListJson(\n  raw: string,\n): Result.Result<\n  ReadonlyArray<NormalizedGitHubPullRequestRecord>,\n  Cause.Cause<Schema.SchemaError>\n> {\n  const result = decodeGitHubPullRequestList(raw);\n  if (Result.isSuccess(result)) {\n    const pullRequests: NormalizedGitHubPullRequestRecord[] = [];\n    for (const entry of result.success) {\n      const decodedEntry = decodeGitHubPullRequestEntry(entry);\n      if (Exit.isFailure(decodedEntry)) {\n        continue;\n      }\n      pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value));\n    }\n    return Result.succeed(pullRequests);\n  }\n  return Result.fail(result.failure);\n}\n\nexport function decodeGitHubPullRequestJson(\n  raw: string,\n): Result.Result<NormalizedGitHubPullRequestRecord, Cause.Cause<Schema.SchemaError>> {\n  const result = decodeGitHubPullRequest(raw);\n  if (Result.isSuccess(result)) {\n    return Result.succeed(normalizeGitHubPullRequestRecord(result.success));\n  }\n  return Result.fail(result.failure);\n}\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\nimport {\n  TrimmedNonEmptyString,\n  type SourceControlRepositoryVisibility,\n  type VcsError,\n} from \"@t3tools/contracts\";\n\nimport * as VcsProcess from \"../vcs/VcsProcess.ts\";\nimport {\n  decodeGitHubPullRequestJson,\n  decodeGitHubPullRequestListJson,\n} from \"./gitHubPullRequests.ts\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\nconst gitHubCliFailureFields = {\n  command: Schema.Literal(\"gh\"),\n  cwd: Schema.String,\n  cause: Schema.Defect(),\n} as const;\n\nexport class GitHubCliUnavailableError extends Schema.TaggedErrorClass<GitHubCliUnavailableError>()(\n  \"GitHubCliUnavailableError\",\n  gitHubCliFailureFields,\n) {\n  get detail(): string {\n    return \"GitHub CLI (`gh`) is required but not available on PATH.\";\n  }\n\n  override get message(): string {\n    return `GitHub CLI failed in execute: ${this.detail}`;\n  }\n}\n\nexport class GitHubCliAuthenticationError extends Schema.TaggedErrorClass<GitHubCliAuthenticationError>()(\n  \"GitHubCliAuthenticationError\",\n  gitHubCliFailureFields,\n) {\n  get detail(): string {\n    return \"GitHub CLI is not authenticated. Run `gh auth login` and retry.\";\n  }\n\n  override get message(): string {\n    return `GitHub CLI failed in execute: ${this.detail}`;\n  }\n}\n\nexport class GitHubPullRequestNotFoundError extends Schema.TaggedErrorClass<GitHubPullRequestNotFoundError>()(\n  \"GitHubPullRequestNotFoundError\",\n  gitHubCliFailureFields,\n) {\n  get detail(): string {\n    return \"Pull request not found. Check the PR number or URL and try again.\";\n  }\n\n  override get message(): string {\n    return `GitHub CLI failed in execute: ${this.detail}`;\n  }\n}\n\nexport class GitHubCliCommandError extends Schema.TaggedErrorClass<GitHubCliCommandError>()(\n  \"GitHubCliCommandError\",\n  gitHubCliFailureFields,\n) {\n  get detail(): string {\n    return \"GitHub CLI command failed.\";\n  }\n\n  override get message(): string {\n    return `GitHub CLI failed in execute: ${this.detail}`;\n  }\n}\n\nconst gitHubCliDecodeFields = {\n  command: Schema.Literal(\"gh\"),\n  cwd: Schema.String,\n  cause: Schema.Defect(),\n} as const;\n\nexport class GitHubPullRequestListDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestListDecodeError>()(\n  \"GitHubPullRequestListDecodeError\",\n  gitHubCliDecodeFields,\n) {\n  get detail(): string {\n    return \"GitHub CLI returned invalid PR list JSON.\";\n  }\n\n  override get message(): string {\n    return `GitHub CLI failed in listOpenPullRequests: ${this.detail}`;\n  }\n}\n\nexport class GitHubChangeRequestListDecodeError extends Schema.TaggedErrorClass<GitHubChangeRequestListDecodeError>()(\n  \"GitHubChangeRequestListDecodeError\",\n  gitHubCliDecodeFields,\n) {\n  get detail(): string {\n    return \"GitHub CLI returned invalid change request JSON.\";\n  }\n\n  override get message(): string {\n    return `GitHub CLI failed in listChangeRequests: ${this.detail}`;\n  }\n}\n\nexport class GitHubPullRequestDecodeError extends Schema.TaggedErrorClass<GitHubPullRequestDecodeError>()(\n  \"GitHubPullRequestDecodeError\",\n  gitHubCliDecodeFields,\n) {\n  get detail(): string {\n    return \"GitHub CLI returned invalid pull request JSON.\";\n  }\n\n  override get message(): string {\n    return `GitHub CLI failed in getPullRequest: ${this.detail}`;\n  }\n}\n\nexport class GitHubRepositoryDecodeError extends Schema.TaggedErrorClass<GitHubRepositoryDecodeError>()(\n  \"GitHubRepositoryDecodeError\",\n  gitHubCliDecodeFields,\n) {\n  get detail(): string {\n    return \"GitHub CLI returned invalid repository JSON.\";\n  }\n\n  override get message(): string {\n    return `GitHub CLI failed in getRepositoryCloneUrls: ${this.detail}`;\n  }\n}\n\nexport const GitHubCliError = Schema.Union([\n  GitHubCliUnavailableError,\n  GitHubCliAuthenticationError,\n  GitHubPullRequestNotFoundError,\n  GitHubCliCommandError,\n  GitHubPullRequestListDecodeError,\n  GitHubChangeRequestListDecodeError,\n  GitHubPullRequestDecodeError,\n  GitHubRepositoryDecodeError,\n]);\nexport type GitHubCliError = typeof GitHubCliError.Type;\n\nexport const isGitHubCliError = Schema.is(GitHubCliError);\n\nexport function fromVcsError(\n  context: {\n    readonly command: \"gh\";\n    readonly cwd: string;\n  },\n  error: VcsError,\n): GitHubCliError {\n  if (\n    error._tag === \"VcsProcessSpawnError\" &&\n    error.cause instanceof PlatformError.PlatformError &&\n    error.cause.reason._tag === \"NotFound\" &&\n    error.cause.reason.module === \"ChildProcess\" &&\n    error.cause.reason.method === \"spawn\"\n  ) {\n    return new GitHubCliUnavailableError({ ...context, cause: error });\n  }\n\n  if (error._tag === \"VcsProcessExitError\") {\n    if (error.failureKind === \"authentication\") {\n      return new GitHubCliAuthenticationError({ ...context, cause: error });\n    }\n    if (error.failureKind === \"not-found\") {\n      return new GitHubPullRequestNotFoundError({ ...context, cause: error });\n    }\n  }\n\n  return new GitHubCliCommandError({ ...context, cause: error });\n}\n\nexport interface GitHubPullRequestSummary {\n  readonly number: number;\n  readonly title: string;\n  readonly url: string;\n  readonly baseRefName: string;\n  readonly headRefName: string;\n  readonly state?: \"open\" | \"closed\" | \"merged\";\n  readonly isCrossRepository?: boolean;\n  readonly headRepositoryNameWithOwner?: string | null;\n  readonly headRepositoryOwnerLogin?: string | null;\n}\n\nexport interface GitHubRepositoryCloneUrls {\n  readonly nameWithOwner: string;\n  readonly url: string;\n  readonly sshUrl: string;\n}\n\nexport class GitHubCli extends Context.Service<\n  GitHubCli,\n  {\n    readonly execute: (input: {\n      readonly cwd: string;\n      readonly args: ReadonlyArray<string>;\n      readonly timeoutMs?: number;\n    }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitHubCliError>;\n\n    readonly listOpenPullRequests: (input: {\n      readonly cwd: string;\n      readonly headSelector: string;\n      readonly limit?: number;\n    }) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;\n\n    readonly getPullRequest: (input: {\n      readonly cwd: string;\n      readonly reference: string;\n    }) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;\n\n    readonly getRepositoryCloneUrls: (input: {\n      readonly cwd: string;\n      readonly repository: string;\n    }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;\n\n    readonly createRepository: (input: {\n      readonly cwd: string;\n      readonly repository: string;\n      readonly visibility: SourceControlRepositoryVisibility;\n    }) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;\n\n    readonly createPullRequest: (input: {\n      readonly cwd: string;\n      readonly baseBranch: string;\n      readonly headSelector: string;\n      readonly title: string;\n      readonly bodyFile: string;\n    }) => Effect.Effect<void, GitHubCliError>;\n\n    readonly getDefaultBranch: (input: {\n      readonly cwd: string;\n    }) => Effect.Effect<string | null, GitHubCliError>;\n\n    readonly checkoutPullRequest: (input: {\n      readonly cwd: string;\n      readonly reference: string;\n      readonly force?: boolean;\n    }) => Effect.Effect<void, GitHubCliError>;\n  }\n>()(\"t3/sourceControl/GitHubCli\") {}\n\nconst RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({\n  nameWithOwner: TrimmedNonEmptyString,\n  url: TrimmedNonEmptyString,\n  sshUrl: TrimmedNonEmptyString,\n});\nconst decodeRawGitHubRepositoryCloneUrls = Schema.decodeEffect(\n  Schema.fromJsonString(RawGitHubRepositoryCloneUrlsSchema),\n);\n\nfunction normalizeRepositoryCloneUrls(\n  raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,\n): GitHubRepositoryCloneUrls {\n  return {\n    nameWithOwner: raw.nameWithOwner,\n    url: raw.url,\n    sshUrl: raw.sshUrl,\n  };\n}\n\n/**\n * `gh repo create` prints the canonical URL of the new repository on stdout\n * (e.g. `https://github.com/owner/repo`). Reading it back here avoids a\n * follow-up `gh repo view`, which can race GitHub's GraphQL eventual\n * consistency window and falsely report the just-created repo as missing.\n */\nfunction deriveRepositoryCloneUrlsFromCreateOutput(\n  stdout: string,\n  repository: string,\n): GitHubRepositoryCloneUrls {\n  const fallbackHost = \"github.com\";\n  const match = stdout.match(/https?:\\/\\/[^\\s]+/);\n  if (match) {\n    const cleaned = match[0].replace(/\\.git$/, \"\");\n    try {\n      const parsed = new URL(cleaned);\n      const pathname = parsed.pathname.replace(/^\\/+|\\/+$/g, \"\");\n      const segments = pathname.split(\"/\").filter(Boolean);\n      if (segments.length === 2) {\n        const nameWithOwner = `${segments[0]}/${segments[1]}`;\n        return {\n          nameWithOwner,\n          url: `${parsed.origin}/${nameWithOwner}`,\n          sshUrl: `git@${parsed.host}:${nameWithOwner}.git`,\n        };\n      }\n    } catch {\n      // Fall through to the input-derived defaults below.\n    }\n  }\n  return {\n    nameWithOwner: repository,\n    url: `https://${fallbackHost}/${repository}`,\n    sshUrl: `git@${fallbackHost}:${repository}.git`,\n  };\n}\n\nexport const make = Effect.gen(function* () {\n  const process = yield* VcsProcess.VcsProcess;\n\n  const execute: GitHubCli[\"Service\"][\"execute\"] = (input) =>\n    process\n      .run({\n        operation: \"GitHubCli.execute\",\n        command: \"gh\",\n        args: input.args,\n        cwd: input.cwd,\n        timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n      })\n      .pipe(Effect.mapError((error) => fromVcsError({ command: \"gh\", cwd: input.cwd }, error)));\n\n  return GitHubCli.of({\n    execute,\n    listOpenPullRequests: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\n          \"pr\",\n          \"list\",\n          \"--head\",\n          input.headSelector,\n          \"--state\",\n          \"open\",\n          \"--limit\",\n          String(input.limit ?? 1),\n          \"--json\",\n          \"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner\",\n        ],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          raw.length === 0\n            ? Effect.succeed([])\n            : Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(\n                Effect.flatMap((decoded) => {\n                  if (!Result.isSuccess(decoded)) {\n                    return Effect.fail(\n                      new GitHubPullRequestListDecodeError({\n                        command: \"gh\",\n                        cwd: input.cwd,\n                        cause: decoded.failure,\n                      }),\n                    );\n                  }\n\n                  return Effect.succeed(\n                    decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),\n                  );\n                }),\n              ),\n        ),\n      ),\n    getPullRequest: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\n          \"pr\",\n          \"view\",\n          input.reference,\n          \"--json\",\n          \"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner\",\n        ],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(\n            Effect.flatMap((decoded) => {\n              if (!Result.isSuccess(decoded)) {\n                return Effect.fail(\n                  new GitHubPullRequestDecodeError({\n                    command: \"gh\",\n                    cwd: input.cwd,\n                    cause: decoded.failure,\n                  }),\n                );\n              }\n\n              return Effect.succeed(\n                (({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),\n              );\n            }),\n          ),\n        ),\n      ),\n    getRepositoryCloneUrls: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\"repo\", \"view\", input.repository, \"--json\", \"nameWithOwner,url,sshUrl\"],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          decodeRawGitHubRepositoryCloneUrls(raw).pipe(\n            Effect.mapError(\n              (cause) =>\n                new GitHubRepositoryDecodeError({\n                  command: \"gh\",\n                  cwd: input.cwd,\n                  cause,\n                }),\n            ),\n          ),\n        ),\n        Effect.map(normalizeRepositoryCloneUrls),\n      ),\n    createRepository: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\"repo\", \"create\", input.repository, `--${input.visibility}`],\n      }).pipe(\n        Effect.map((result) =>\n          deriveRepositoryCloneUrlsFromCreateOutput(result.stdout, input.repository),\n        ),\n      ),\n    createPullRequest: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\n          \"pr\",\n          \"create\",\n          \"--base\",\n          input.baseBranch,\n          \"--head\",\n          input.headSelector,\n          \"--title\",\n          input.title,\n          \"--body-file\",\n          input.bodyFile,\n        ],\n      }).pipe(Effect.asVoid),\n    getDefaultBranch: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\"repo\", \"view\", \"--json\", \"defaultBranchRef\", \"--jq\", \".defaultBranchRef.name\"],\n      }).pipe(\n        Effect.map((value) => {\n          const trimmed = value.stdout.trim();\n          return trimmed.length > 0 ? trimmed : null;\n        }),\n      ),\n    checkoutPullRequest: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\"pr\", \"checkout\", input.reference, ...(input.force ? [\"--force\"] : [])],\n      }).pipe(Effect.asVoid),\n  });\n});\n\nexport const layer = Layer.effect(GitHubCli, make);\n","import * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nconst GitHubAuthStatusAccountSchema = Schema.Struct({\n  state: Schema.String,\n  error: Schema.optional(Schema.String),\n  active: Schema.Boolean,\n  host: Schema.String,\n  login: Schema.String,\n});\n\nconst GitHubAuthStatusSchema = Schema.Struct({\n  hosts: Schema.Record(Schema.String, Schema.Array(GitHubAuthStatusAccountSchema)),\n});\n\nconst decodeGitHubAuthStatusJson = Schema.decodeUnknownOption(\n  Schema.fromJsonString(GitHubAuthStatusSchema),\n);\n\nexport interface GitHubAuthStatusAccount {\n  readonly host: string;\n  readonly account: string;\n  readonly authenticated: boolean;\n  readonly active: boolean;\n  readonly error: string | null;\n}\n\nexport interface GitHubAuthStatus {\n  readonly parsed: boolean;\n  readonly accounts: ReadonlyArray<GitHubAuthStatusAccount>;\n}\n\nfunction nonEmptyString(value: string): string | null {\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nexport function parseGitHubAuthStatus(text: string): GitHubAuthStatus {\n  return Option.match(decodeGitHubAuthStatusJson(text), {\n    onNone: () => ({ parsed: false, accounts: [] }),\n    onSome: (status) =>\n      ({\n        parsed: true,\n        accounts: Object.values(status.hosts).flatMap((accounts) =>\n          accounts.flatMap((account) => {\n            const host = nonEmptyString(account.host);\n            const login = nonEmptyString(account.login);\n            if (host === null || login === null) return [];\n\n            return [\n              {\n                host: host.toLowerCase(),\n                account: login,\n                authenticated: account.state === \"success\",\n                active: account.active,\n                error: account.error?.trim() || null,\n              },\n            ];\n          }),\n        ),\n      }) satisfies GitHubAuthStatus,\n  });\n}\n\nexport function findAuthenticatedGitHubAccount(\n  accounts: ReadonlyArray<GitHubAuthStatusAccount>,\n): GitHubAuthStatusAccount | undefined {\n  return (\n    accounts.find((account) => account.authenticated && account.active) ??\n    accounts.find((account) => account.authenticated)\n  );\n}\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport {\n  SourceControlProviderError,\n  type ChangeRequest,\n  type ChangeRequestState,\n} from \"@t3tools/contracts\";\n\nimport * as GitHubCli from \"./GitHubCli.ts\";\nimport { findAuthenticatedGitHubAccount, parseGitHubAuthStatus } from \"./gitHubAuthStatus.ts\";\nimport { decodeGitHubPullRequestListJson } from \"./gitHubPullRequests.ts\";\nimport * as SourceControlProvider from \"./SourceControlProvider.ts\";\nimport {\n  combinedAuthOutput,\n  firstSafeAuthLine,\n  providerAuth,\n  type SourceControlAuthProbeInput,\n  type SourceControlCliDiscoverySpec,\n} from \"./SourceControlProviderDiscovery.ts\";\n\nfunction toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeRequest {\n  return {\n    provider: \"github\",\n    number: summary.number,\n    title: summary.title,\n    url: summary.url,\n    baseRefName: summary.baseRefName,\n    headRefName: summary.headRefName,\n    state: summary.state ?? \"open\",\n    updatedAt: Option.none(),\n    ...(summary.isCrossRepository !== undefined\n      ? { isCrossRepository: summary.isCrossRepository }\n      : {}),\n    ...(summary.headRepositoryNameWithOwner !== undefined\n      ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }\n      : {}),\n    ...(summary.headRepositoryOwnerLogin !== undefined\n      ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }\n      : {}),\n  };\n}\n\nfunction parseGitHubAuth(input: SourceControlAuthProbeInput) {\n  const output = combinedAuthOutput(input);\n  const authStatus = parseGitHubAuthStatus(input.stdout);\n  const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts);\n  const host = authenticatedAccount?.host;\n\n  if (authenticatedAccount) {\n    return providerAuth({\n      status: \"authenticated\",\n      account: authenticatedAccount.account,\n      host,\n    });\n  }\n\n  const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];\n  if (authStatus.parsed) {\n    return providerAuth({\n      status: \"unauthenticated\",\n      host: failedAccount?.host,\n      detail:\n        failedAccount?.error ??\n        \"Run `gh auth login` to authenticate GitHub CLI with an active account.\",\n    });\n  }\n\n  if (input.exitCode !== 0) {\n    return providerAuth({\n      status: \"unauthenticated\",\n      host,\n      detail: firstSafeAuthLine(output) ?? \"Run `gh auth login` to authenticate GitHub CLI.\",\n    });\n  }\n\n  return providerAuth({\n    status: \"unknown\",\n    host,\n    detail: firstSafeAuthLine(output) ?? \"GitHub CLI auth status could not be parsed.\",\n  });\n}\n\nexport const discovery = {\n  type: \"cli\",\n  kind: \"github\",\n  label: \"GitHub\",\n  executable: \"gh\",\n  versionArgs: [\"--version\"],\n  authArgs: [\"auth\", \"status\", \"--json\", \"hosts\"],\n  parseAuth: parseGitHubAuth,\n  installHint:\n    \"Install the GitHub command-line tool (`gh`) via https://cli.github.com/ or your package manager (for example `brew install gh`).\",\n} satisfies SourceControlCliDiscoverySpec;\n\nexport const make = Effect.gen(function* () {\n  const github = yield* GitHubCli.GitHubCli;\n\n  const listChangeRequests: SourceControlProvider.SourceControlProvider[\"Service\"][\"listChangeRequests\"] =\n    (input) => {\n      if (input.state === \"open\") {\n        return github\n          .listOpenPullRequests({\n            cwd: input.cwd,\n            headSelector: input.headSelector,\n            ...(input.limit !== undefined ? { limit: input.limit } : {}),\n          })\n          .pipe(\n            Effect.map((items) => items.map(toChangeRequest)),\n            Effect.mapError(\n              (error) =>\n                new SourceControlProviderError({\n                  provider: \"github\",\n                  operation: \"listChangeRequests\",\n                  command: error.command,\n                  cwd: input.cwd,\n                  reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                    input.headSelector,\n                  ),\n                  detail: error.detail,\n                  cause: error,\n                }),\n            ),\n          );\n      }\n\n      const stateArg: ChangeRequestState | \"all\" = input.state;\n      return github\n        .execute({\n          cwd: input.cwd,\n          args: [\n            \"pr\",\n            \"list\",\n            \"--head\",\n            input.headSelector,\n            \"--state\",\n            stateArg,\n            \"--limit\",\n            String(input.limit ?? 20),\n            \"--json\",\n            \"number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner\",\n          ],\n        })\n        .pipe(\n          Effect.flatMap((result) => {\n            const raw = result.stdout.trim();\n            if (raw.length === 0) {\n              return Effect.succeed([]);\n            }\n            return Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(\n              Effect.flatMap((decoded) =>\n                Result.isSuccess(decoded)\n                  ? Effect.succeed(\n                      decoded.success.map((item) => ({\n                        ...toChangeRequest(item),\n                        updatedAt: item.updatedAt,\n                      })),\n                    )\n                  : Effect.fail(\n                      new GitHubCli.GitHubChangeRequestListDecodeError({\n                        command: \"gh\",\n                        cwd: input.cwd,\n                        cause: decoded.failure,\n                      }),\n                    ),\n              ),\n            );\n          }),\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"github\",\n                operation: \"listChangeRequests\",\n                command: error.command,\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.headSelector,\n                ),\n                detail: error.detail,\n                cause: error,\n              }),\n          ),\n        );\n    };\n\n  return SourceControlProvider.SourceControlProvider.of({\n    kind: \"github\",\n    listChangeRequests,\n    getChangeRequest: (input) =>\n      github.getPullRequest(input).pipe(\n        Effect.map(toChangeRequest),\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"github\",\n              operation: \"getChangeRequest\",\n              command: error.command,\n              cwd: input.cwd,\n              reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.reference,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    createChangeRequest: (input) =>\n      github\n        .createPullRequest({\n          cwd: input.cwd,\n          baseBranch: input.baseRefName,\n          headSelector: input.headSelector,\n          title: input.title,\n          bodyFile: input.bodyFile,\n        })\n        .pipe(\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"github\",\n                operation: \"createChangeRequest\",\n                command: error.command,\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.headSelector,\n                ),\n                detail: error.detail,\n                cause: error,\n              }),\n          ),\n        ),\n    getRepositoryCloneUrls: (input) =>\n      github.getRepositoryCloneUrls(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"github\",\n              operation: \"getRepositoryCloneUrls\",\n              command: error.command,\n              cwd: input.cwd,\n              repository: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.repository,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    createRepository: (input) =>\n      github.createRepository(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"github\",\n              operation: \"createRepository\",\n              command: error.command,\n              cwd: input.cwd,\n              repository: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.repository,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    getDefaultBranch: (input) =>\n      github.getDefaultBranch(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"github\",\n              operation: \"getDefaultBranch\",\n              command: error.command,\n              cwd: input.cwd,\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    checkoutChangeRequest: (input) =>\n      github.checkoutPullRequest(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"github\",\n              operation: \"checkoutChangeRequest\",\n              command: error.command,\n              cwd: input.cwd,\n              reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.reference,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n  });\n});\n\nexport const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make);\n","import * as Cause from \"effect/Cause\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { PositiveInt, TrimmedNonEmptyString } from \"@t3tools/contracts\";\nimport { decodeJsonResult, formatSchemaError } from \"@t3tools/shared/schemaJson\";\n\nexport interface NormalizedGitLabMergeRequestRecord {\n  readonly number: number;\n  readonly title: string;\n  readonly url: string;\n  readonly baseRefName: string;\n  readonly headRefName: string;\n  readonly state: \"open\" | \"closed\" | \"merged\";\n  readonly updatedAt: Option.Option<DateTime.Utc>;\n  readonly isCrossRepository?: boolean;\n  readonly headRepositoryNameWithOwner?: string | null;\n  readonly headRepositoryOwnerLogin?: string | null;\n}\n\nconst GitLabProjectReferenceSchema = Schema.Struct({\n  path_with_namespace: Schema.optional(Schema.String),\n  pathWithNamespace: Schema.optional(Schema.String),\n  namespace: Schema.optional(\n    Schema.NullOr(\n      Schema.Struct({\n        path: Schema.optional(Schema.String),\n        full_path: Schema.optional(Schema.String),\n        fullPath: Schema.optional(Schema.String),\n      }),\n    ),\n  ),\n});\n\nconst GitLabMergeRequestSchema = Schema.Struct({\n  iid: PositiveInt,\n  title: TrimmedNonEmptyString,\n  web_url: TrimmedNonEmptyString,\n  source_branch: TrimmedNonEmptyString,\n  target_branch: TrimmedNonEmptyString,\n  state: Schema.optional(Schema.NullOr(Schema.String)),\n  updated_at: Schema.optional(Schema.OptionFromNullOr(Schema.DateTimeUtcFromString)),\n  source_project_id: Schema.optional(Schema.NullOr(Schema.Number)),\n  target_project_id: Schema.optional(Schema.NullOr(Schema.Number)),\n  source_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),\n  target_project: Schema.optional(Schema.NullOr(GitLabProjectReferenceSchema)),\n});\n\nfunction trimOptionalString(value: string | null | undefined): string | null {\n  const trimmed = value?.trim() ?? \"\";\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeGitLabMergeRequestState(\n  state: string | null | undefined,\n): \"open\" | \"closed\" | \"merged\" {\n  const normalized = state?.trim().toLowerCase();\n  if (normalized === \"merged\") {\n    return \"merged\";\n  }\n  if (normalized === \"closed\") {\n    return \"closed\";\n  }\n  return \"open\";\n}\n\nfunction projectPathWithNamespace(\n  project: Schema.Schema.Type<typeof GitLabProjectReferenceSchema> | null | undefined,\n): string | null {\n  const explicit =\n    trimOptionalString(project?.path_with_namespace) ??\n    trimOptionalString(project?.pathWithNamespace);\n  if (explicit) {\n    return explicit;\n  }\n\n  const namespacePath =\n    trimOptionalString(project?.namespace?.full_path) ??\n    trimOptionalString(project?.namespace?.fullPath) ??\n    trimOptionalString(project?.namespace?.path);\n  return namespacePath;\n}\n\nfunction ownerLoginFromPathWithNamespace(pathWithNamespace: string | null): string | null {\n  const [owner] = pathWithNamespace?.split(\"/\") ?? [];\n  return trimOptionalString(owner);\n}\n\nfunction normalizeGitLabMergeRequestRecord(\n  raw: Schema.Schema.Type<typeof GitLabMergeRequestSchema>,\n): NormalizedGitLabMergeRequestRecord {\n  const sourceProjectPath = projectPathWithNamespace(raw.source_project);\n  const targetProjectPath = projectPathWithNamespace(raw.target_project);\n  const isCrossRepository =\n    typeof raw.source_project_id === \"number\" && typeof raw.target_project_id === \"number\"\n      ? raw.source_project_id !== raw.target_project_id\n      : sourceProjectPath !== null && targetProjectPath !== null\n        ? sourceProjectPath.toLowerCase() !== targetProjectPath.toLowerCase()\n        : undefined;\n  const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath);\n\n  return {\n    number: raw.iid,\n    title: raw.title,\n    url: raw.web_url,\n    baseRefName: raw.target_branch,\n    headRefName: raw.source_branch,\n    state: normalizeGitLabMergeRequestState(raw.state),\n    updatedAt: raw.updated_at ?? Option.none(),\n    ...(typeof isCrossRepository === \"boolean\" ? { isCrossRepository } : {}),\n    ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}),\n    ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),\n  };\n}\n\nconst decodeGitLabMergeRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));\nconst decodeGitLabMergeRequest = decodeJsonResult(GitLabMergeRequestSchema);\nconst decodeGitLabMergeRequestEntry = Schema.decodeUnknownExit(GitLabMergeRequestSchema);\n\nexport const formatGitLabJsonDecodeError = formatSchemaError;\n\nexport function decodeGitLabMergeRequestListJson(\n  raw: string,\n): Result.Result<\n  ReadonlyArray<NormalizedGitLabMergeRequestRecord>,\n  Cause.Cause<Schema.SchemaError>\n> {\n  const result = decodeGitLabMergeRequestList(raw);\n  if (Result.isSuccess(result)) {\n    const mergeRequests: NormalizedGitLabMergeRequestRecord[] = [];\n    for (const entry of result.success) {\n      const decodedEntry = decodeGitLabMergeRequestEntry(entry);\n      if (Exit.isFailure(decodedEntry)) {\n        continue;\n      }\n      mergeRequests.push(normalizeGitLabMergeRequestRecord(decodedEntry.value));\n    }\n    return Result.succeed(mergeRequests);\n  }\n  return Result.fail(result.failure);\n}\n\nexport function decodeGitLabMergeRequestJson(\n  raw: string,\n): Result.Result<NormalizedGitLabMergeRequestRecord, Cause.Cause<Schema.SchemaError>> {\n  const result = decodeGitLabMergeRequest(raw);\n  if (Result.isSuccess(result)) {\n    return Result.succeed(normalizeGitLabMergeRequestRecord(result.success));\n  }\n  return Result.fail(result.failure);\n}\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport type * as DateTime from \"effect/DateTime\";\n\nimport {\n  TrimmedNonEmptyString,\n  type SourceControlRepositoryVisibility,\n  type VcsError,\n} from \"@t3tools/contracts\";\n\nimport * as VcsProcess from \"../vcs/VcsProcess.ts\";\nimport {\n  decodeGitLabMergeRequestJson,\n  decodeGitLabMergeRequestListJson,\n} from \"./gitLabMergeRequests.ts\";\nimport type * as SourceControlProvider from \"./SourceControlProvider.ts\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\nconst gitLabCliExecutionErrorContext = {\n  operation: Schema.Literal(\"execute\"),\n  command: Schema.Literal(\"glab\"),\n  cwd: Schema.String,\n  cause: Schema.Defect(),\n};\n\nconst gitLabCliDecodeErrorContext = {\n  command: Schema.Literal(\"glab\"),\n  cwd: Schema.String,\n  cause: Schema.Defect(),\n};\n\nexport class GitLabCliUnavailableError extends Schema.TaggedErrorClass<GitLabCliUnavailableError>()(\n  \"GitLabCliUnavailableError\",\n  gitLabCliExecutionErrorContext,\n) {\n  get detail(): string {\n    return \"GitLab CLI (`glab`) is required but not available on PATH.\";\n  }\n\n  override get message(): string {\n    return `GitLab CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class GitLabCliAuthenticationError extends Schema.TaggedErrorClass<GitLabCliAuthenticationError>()(\n  \"GitLabCliAuthenticationError\",\n  gitLabCliExecutionErrorContext,\n) {\n  get detail(): string {\n    return \"GitLab CLI is not authenticated. Run `glab auth login` and retry.\";\n  }\n\n  override get message(): string {\n    return `GitLab CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class GitLabMergeRequestNotFoundError extends Schema.TaggedErrorClass<GitLabMergeRequestNotFoundError>()(\n  \"GitLabMergeRequestNotFoundError\",\n  {\n    ...gitLabCliExecutionErrorContext,\n    reference: Schema.String,\n  },\n) {\n  get detail(): string {\n    return `Merge request ${this.reference} was not found. Check the MR number or URL and try again.`;\n  }\n\n  override get message(): string {\n    return `GitLab CLI failed in ${this.operation}: ${this.detail}`;\n  }\n\n  static fromVcsError(\n    context: {\n      readonly operation: \"execute\";\n      readonly command: \"glab\";\n      readonly cwd: string;\n      readonly reference: string;\n    },\n    error: VcsError,\n  ): GitLabCliError {\n    if (error._tag === \"VcsProcessExitError\" && error.failureKind === \"not-found\") {\n      return new GitLabMergeRequestNotFoundError({ ...context, cause: error });\n    }\n\n    return GitLabCliCommandError.fromVcsError(\n      {\n        operation: context.operation,\n        command: context.command,\n        cwd: context.cwd,\n      },\n      error,\n    );\n  }\n}\n\nexport class GitLabCliCommandError extends Schema.TaggedErrorClass<GitLabCliCommandError>()(\n  \"GitLabCliCommandError\",\n  gitLabCliExecutionErrorContext,\n) {\n  get detail(): string {\n    return \"GitLab CLI command failed.\";\n  }\n\n  override get message(): string {\n    return `GitLab CLI failed in ${this.operation}: ${this.detail}`;\n  }\n\n  static fromVcsError(\n    context: {\n      readonly operation: \"execute\";\n      readonly command: \"glab\";\n      readonly cwd: string;\n    },\n    error: VcsError,\n  ): GitLabCliError {\n    return Match.valueTags(error, {\n      VcsProcessSpawnError: (cause) => new GitLabCliUnavailableError({ ...context, cause }),\n      VcsProcessExitError: (cause) => {\n        switch (cause.failureKind) {\n          case \"authentication\":\n            return new GitLabCliAuthenticationError({ ...context, cause });\n          case \"not-found\":\n          case \"command-failed\":\n          case undefined:\n            return new GitLabCliCommandError({ ...context, cause });\n        }\n      },\n      VcsProcessTimeoutError: (cause) => new GitLabCliCommandError({ ...context, cause }),\n      VcsProcessStdinWriteError: (cause) => new GitLabCliCommandError({ ...context, cause }),\n      VcsProcessOutputReadError: (cause) => new GitLabCliCommandError({ ...context, cause }),\n      VcsProcessOutputLimitError: (cause) => new GitLabCliCommandError({ ...context, cause }),\n      VcsProcessMissingExitCodeError: (cause) => new GitLabCliCommandError({ ...context, cause }),\n      VcsRepositoryDetectionError: (cause) => new GitLabCliCommandError({ ...context, cause }),\n      VcsUnsupportedOperationError: (cause) => new GitLabCliCommandError({ ...context, cause }),\n    });\n  }\n}\n\nexport class GitLabMergeRequestListDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestListDecodeError>()(\n  \"GitLabMergeRequestListDecodeError\",\n  {\n    ...gitLabCliDecodeErrorContext,\n    operation: Schema.Literal(\"listMergeRequests\"),\n  },\n) {\n  get detail(): string {\n    return \"GitLab CLI returned invalid MR list JSON.\";\n  }\n\n  override get message(): string {\n    return `GitLab CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class GitLabMergeRequestDecodeError extends Schema.TaggedErrorClass<GitLabMergeRequestDecodeError>()(\n  \"GitLabMergeRequestDecodeError\",\n  {\n    ...gitLabCliDecodeErrorContext,\n    operation: Schema.Literal(\"getMergeRequest\"),\n    reference: Schema.String,\n  },\n) {\n  get detail(): string {\n    return \"GitLab CLI returned invalid merge request JSON.\";\n  }\n\n  override get message(): string {\n    return `GitLab CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class GitLabRepositoryDecodeError extends Schema.TaggedErrorClass<GitLabRepositoryDecodeError>()(\n  \"GitLabRepositoryDecodeError\",\n  {\n    ...gitLabCliDecodeErrorContext,\n    operation: Schema.Literals([\"getRepositoryCloneUrls\", \"createRepository\", \"getDefaultBranch\"]),\n    repository: Schema.optional(Schema.String),\n  },\n) {\n  get detail(): string {\n    return \"GitLab CLI returned invalid repository JSON.\";\n  }\n\n  override get message(): string {\n    return `GitLab CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport class GitLabNamespaceDecodeError extends Schema.TaggedErrorClass<GitLabNamespaceDecodeError>()(\n  \"GitLabNamespaceDecodeError\",\n  {\n    ...gitLabCliDecodeErrorContext,\n    operation: Schema.Literal(\"createRepository\"),\n    namespacePath: Schema.String,\n  },\n) {\n  get detail(): string {\n    return \"GitLab CLI returned invalid namespace JSON.\";\n  }\n\n  override get message(): string {\n    return `GitLab CLI failed in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport const GitLabCliError = Schema.Union([\n  GitLabCliUnavailableError,\n  GitLabCliAuthenticationError,\n  GitLabMergeRequestNotFoundError,\n  GitLabCliCommandError,\n  GitLabMergeRequestListDecodeError,\n  GitLabMergeRequestDecodeError,\n  GitLabRepositoryDecodeError,\n  GitLabNamespaceDecodeError,\n]);\nexport type GitLabCliError = typeof GitLabCliError.Type;\nexport const isGitLabCliError = Schema.is(GitLabCliError);\n\nexport interface GitLabMergeRequestSummary {\n  readonly number: number;\n  readonly title: string;\n  readonly url: string;\n  readonly baseRefName: string;\n  readonly headRefName: string;\n  readonly state?: \"open\" | \"closed\" | \"merged\";\n  readonly updatedAt?: Option.Option<DateTime.Utc>;\n  readonly isCrossRepository?: boolean;\n  readonly headRepositoryNameWithOwner?: string | null;\n  readonly headRepositoryOwnerLogin?: string | null;\n}\n\nexport interface GitLabRepositoryCloneUrls {\n  readonly nameWithOwner: string;\n  readonly url: string;\n  readonly sshUrl: string;\n}\n\nexport class GitLabCli extends Context.Service<\n  GitLabCli,\n  {\n    readonly execute: (input: {\n      readonly cwd: string;\n      readonly args: ReadonlyArray<string>;\n      readonly timeoutMs?: number;\n    }) => Effect.Effect<VcsProcess.VcsProcessOutput, GitLabCliError>;\n\n    readonly listMergeRequests: (input: {\n      readonly cwd: string;\n      readonly headSelector: string;\n      readonly source?: SourceControlProvider.SourceControlRefSelector;\n      readonly state: \"open\" | \"closed\" | \"merged\" | \"all\";\n      readonly limit?: number;\n    }) => Effect.Effect<ReadonlyArray<GitLabMergeRequestSummary>, GitLabCliError>;\n\n    readonly getMergeRequest: (input: {\n      readonly cwd: string;\n      readonly reference: string;\n    }) => Effect.Effect<GitLabMergeRequestSummary, GitLabCliError>;\n\n    readonly getRepositoryCloneUrls: (input: {\n      readonly cwd: string;\n      readonly repository: string;\n    }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;\n\n    readonly createRepository: (input: {\n      readonly cwd: string;\n      readonly repository: string;\n      readonly visibility: SourceControlRepositoryVisibility;\n    }) => Effect.Effect<GitLabRepositoryCloneUrls, GitLabCliError>;\n\n    readonly createMergeRequest: (input: {\n      readonly cwd: string;\n      readonly baseBranch: string;\n      readonly headSelector: string;\n      readonly source?: SourceControlProvider.SourceControlRefSelector;\n      readonly target?: SourceControlProvider.SourceControlRefSelector;\n      readonly title: string;\n      readonly bodyFile: string;\n    }) => Effect.Effect<void, GitLabCliError>;\n\n    readonly getDefaultBranch: (input: {\n      readonly cwd: string;\n    }) => Effect.Effect<string | null, GitLabCliError>;\n\n    readonly checkoutMergeRequest: (input: {\n      readonly cwd: string;\n      readonly reference: string;\n      readonly force?: boolean;\n    }) => Effect.Effect<void, GitLabCliError>;\n  }\n>()(\"t3/sourceControl/GitLabCli\") {}\n\nconst RawGitLabRepositoryCloneUrlsSchema = Schema.Struct({\n  path_with_namespace: TrimmedNonEmptyString,\n  web_url: TrimmedNonEmptyString,\n  http_url_to_repo: TrimmedNonEmptyString,\n  ssh_url_to_repo: TrimmedNonEmptyString,\n});\n\nconst RawGitLabDefaultBranchSchema = Schema.Struct({\n  default_branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),\n});\n\nconst RawGitLabNamespaceSchema = Schema.Struct({\n  id: Schema.Number,\n});\n\nconst decodeGitLabRepositoryCloneUrls = Schema.decodeEffect(\n  Schema.fromJsonString(RawGitLabRepositoryCloneUrlsSchema),\n);\nconst decodeGitLabDefaultBranch = Schema.decodeEffect(\n  Schema.fromJsonString(RawGitLabDefaultBranchSchema),\n);\nconst decodeGitLabNamespace = Schema.decodeEffect(Schema.fromJsonString(RawGitLabNamespaceSchema));\n\nfunction normalizeRepositoryCloneUrls(\n  raw: Schema.Schema.Type<typeof RawGitLabRepositoryCloneUrlsSchema>,\n): GitLabRepositoryCloneUrls {\n  return {\n    nameWithOwner: raw.path_with_namespace,\n    url: raw.web_url,\n    sshUrl: raw.ssh_url_to_repo,\n  };\n}\n\nfunction stateArgs(state: \"open\" | \"closed\" | \"merged\" | \"all\"): ReadonlyArray<string> {\n  switch (state) {\n    case \"open\":\n      return [];\n    case \"closed\":\n      return [\"--closed\"];\n    case \"merged\":\n      return [\"--merged\"];\n    case \"all\":\n      return [\"--all\"];\n  }\n}\n\nfunction normalizeHeadSelector(headSelector: string): string {\n  const trimmed = headSelector.trim();\n  const ownerBranch = /^[^:]+:(.+)$/.exec(trimmed);\n  return ownerBranch?.[1]?.trim() || trimmed;\n}\n\nfunction sourceRefName(input: {\n  readonly headSelector: string;\n  readonly source?: SourceControlProvider.SourceControlRefSelector;\n}): string {\n  return input.source?.refName ?? normalizeHeadSelector(input.headSelector);\n}\n\nfunction sourceProjectIdentifier(\n  source: SourceControlProvider.SourceControlRefSelector | undefined,\n): string | null {\n  return source?.repository ?? source?.owner ?? null;\n}\n\nfunction toSummaryWithOptionalUpdatedAt(\n  record: GitLabMergeRequestSummary & {\n    readonly updatedAt: Option.Option<DateTime.Utc>;\n  },\n): GitLabMergeRequestSummary {\n  const { updatedAt, ...summary } = record;\n  return Option.isSome(updatedAt) ? { ...summary, updatedAt } : summary;\n}\n\nfunction parseRepositoryPath(repository: string): {\n  readonly namespacePath: string | null;\n  readonly projectPath: string;\n} {\n  const parts: Array<string> = [];\n  for (const part of repository.split(\"/\")) {\n    const trimmed = part.trim();\n    if (trimmed.length > 0) {\n      parts.push(trimmed);\n    }\n  }\n  const projectPath = parts.at(-1) ?? repository.trim();\n  const namespacePath = parts.length > 1 ? parts.slice(0, -1).join(\"/\") : null;\n  return { namespacePath, projectPath };\n}\n\nexport const make = Effect.gen(function* () {\n  const process = yield* VcsProcess.VcsProcess;\n\n  const run = (\n    input: Parameters<GitLabCli[\"Service\"][\"execute\"]>[0],\n    mapError: (error: VcsError) => GitLabCliError,\n  ) =>\n    process\n      .run({\n        operation: \"GitLabCli.execute\",\n        command: \"glab\",\n        args: input.args,\n        cwd: input.cwd,\n        timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n      })\n      .pipe(Effect.mapError(mapError));\n\n  const execute: GitLabCli[\"Service\"][\"execute\"] = (input) =>\n    run(input, (error) =>\n      GitLabCliCommandError.fromVcsError(\n        { operation: \"execute\", command: \"glab\", cwd: input.cwd },\n        error,\n      ),\n    );\n\n  const executeMergeRequest = (input: {\n    readonly cwd: string;\n    readonly reference: string;\n    readonly args: ReadonlyArray<string>;\n  }) =>\n    run(input, (error) =>\n      GitLabMergeRequestNotFoundError.fromVcsError(\n        {\n          operation: \"execute\",\n          command: \"glab\",\n          cwd: input.cwd,\n          reference: input.reference,\n        },\n        error,\n      ),\n    );\n\n  return GitLabCli.of({\n    execute,\n    listMergeRequests: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\n          \"mr\",\n          \"list\",\n          \"--source-branch\",\n          sourceRefName(input),\n          ...stateArgs(input.state),\n          \"--per-page\",\n          String(input.limit ?? 20),\n          \"--output\",\n          \"json\",\n        ],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          raw.length === 0\n            ? Effect.succeed([])\n            : Effect.sync(() => decodeGitLabMergeRequestListJson(raw)).pipe(\n                Effect.flatMap((decoded) => {\n                  if (!Result.isSuccess(decoded)) {\n                    return Effect.fail(\n                      new GitLabMergeRequestListDecodeError({\n                        operation: \"listMergeRequests\",\n                        command: \"glab\",\n                        cwd: input.cwd,\n                        cause: decoded.failure,\n                      }),\n                    );\n                  }\n\n                  return Effect.succeed(decoded.success.map(toSummaryWithOptionalUpdatedAt));\n                }),\n              ),\n        ),\n      ),\n    getMergeRequest: (input) =>\n      executeMergeRequest({\n        cwd: input.cwd,\n        reference: input.reference,\n        args: [\"mr\", \"view\", input.reference, \"--output\", \"json\"],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          Effect.sync(() => decodeGitLabMergeRequestJson(raw)).pipe(\n            Effect.flatMap((decoded) => {\n              if (!Result.isSuccess(decoded)) {\n                return Effect.fail(\n                  new GitLabMergeRequestDecodeError({\n                    operation: \"getMergeRequest\",\n                    command: \"glab\",\n                    cwd: input.cwd,\n                    reference: input.reference,\n                    cause: decoded.failure,\n                  }),\n                );\n              }\n\n              return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success));\n            }),\n          ),\n        ),\n      ),\n    getRepositoryCloneUrls: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\"api\", `projects/${encodeURIComponent(input.repository)}`],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          decodeGitLabRepositoryCloneUrls(raw).pipe(\n            Effect.mapError(\n              (cause) =>\n                new GitLabRepositoryDecodeError({\n                  operation: \"getRepositoryCloneUrls\",\n                  command: \"glab\",\n                  cwd: input.cwd,\n                  repository: input.repository,\n                  cause,\n                }),\n            ),\n          ),\n        ),\n        Effect.map(normalizeRepositoryCloneUrls),\n      ),\n    createRepository: (input) => {\n      const { namespacePath, projectPath } = parseRepositoryPath(input.repository);\n      const namespaceId: Effect.Effect<number | null, GitLabCliError> = namespacePath\n        ? execute({\n            cwd: input.cwd,\n            args: [\"api\", `namespaces/${encodeURIComponent(namespacePath)}`],\n          }).pipe(\n            Effect.map((result) => result.stdout.trim()),\n            Effect.flatMap((raw) =>\n              decodeGitLabNamespace(raw).pipe(\n                Effect.mapError(\n                  (cause) =>\n                    new GitLabNamespaceDecodeError({\n                      operation: \"createRepository\",\n                      command: \"glab\",\n                      cwd: input.cwd,\n                      namespacePath,\n                      cause,\n                    }),\n                ),\n              ),\n            ),\n            Effect.map((namespace) => namespace.id),\n          )\n        : Effect.succeed(null);\n\n      return namespaceId.pipe(\n        Effect.flatMap((resolvedNamespaceId) =>\n          execute({\n            cwd: input.cwd,\n            args: [\n              \"api\",\n              \"--method\",\n              \"POST\",\n              \"projects\",\n              \"--raw-field\",\n              `path=${projectPath}`,\n              \"--raw-field\",\n              `name=${projectPath}`,\n              \"--raw-field\",\n              `visibility=${input.visibility}`,\n              ...(resolvedNamespaceId === null\n                ? []\n                : [\"--raw-field\", `namespace_id=${resolvedNamespaceId}`]),\n            ],\n          }),\n        ),\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          decodeGitLabRepositoryCloneUrls(raw).pipe(\n            Effect.mapError(\n              (cause) =>\n                new GitLabRepositoryDecodeError({\n                  operation: \"createRepository\",\n                  command: \"glab\",\n                  cwd: input.cwd,\n                  repository: input.repository,\n                  cause,\n                }),\n            ),\n          ),\n        ),\n        Effect.map(normalizeRepositoryCloneUrls),\n      );\n    },\n    createMergeRequest: (input) => {\n      const sourceProject = sourceProjectIdentifier(input.source);\n      return execute({\n        cwd: input.cwd,\n        args: [\n          \"api\",\n          \"--method\",\n          \"POST\",\n          \"projects/:fullpath/merge_requests\",\n          \"--raw-field\",\n          `source_branch=${sourceRefName(input)}`,\n          \"--raw-field\",\n          `target_branch=${input.target?.refName ?? input.baseBranch}`,\n          ...(sourceProject ? [\"--raw-field\", `source_project_id=${sourceProject}`] : []),\n          \"--raw-field\",\n          `title=${input.title}`,\n          \"--field\",\n          `description=@${input.bodyFile}`,\n        ],\n      }).pipe(Effect.asVoid);\n    },\n    getDefaultBranch: (input) =>\n      execute({\n        cwd: input.cwd,\n        args: [\"api\", \"projects/:fullpath\"],\n      }).pipe(\n        Effect.map((result) => result.stdout.trim()),\n        Effect.flatMap((raw) =>\n          decodeGitLabDefaultBranch(raw).pipe(\n            Effect.mapError(\n              (cause) =>\n                new GitLabRepositoryDecodeError({\n                  operation: \"getDefaultBranch\",\n                  command: \"glab\",\n                  cwd: input.cwd,\n                  cause,\n                }),\n            ),\n          ),\n        ),\n        Effect.map((value) => value.default_branch ?? null),\n      ),\n    checkoutMergeRequest: (input) =>\n      executeMergeRequest({\n        cwd: input.cwd,\n        reference: input.reference,\n        args: [\"mr\", \"checkout\", input.reference],\n      }).pipe(Effect.asVoid),\n  });\n});\n\nexport const layer = Layer.effect(GitLabCli, make);\n","const HOST_LINE_PATTERN = /^(?:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?|\\[[a-f0-9:.]+\\])(?::\\d+)?$/iu;\nconst LOGGED_IN_PATTERN = /Logged in to .+? as\\s+([^\\s(]+)/iu;\n\nexport interface GitLabAuthStatusHost {\n  readonly host: string;\n  readonly account: string | null;\n}\n\nexport function parseGitLabAuthStatusHosts(text: string): ReadonlyArray<GitLabAuthStatusHost> {\n  const hosts: GitLabAuthStatusHost[] = [];\n  let currentHost: string | null = null;\n  let currentLines: string[] = [];\n\n  const flush = () => {\n    if (currentHost === null) return;\n\n    const account = LOGGED_IN_PATTERN.exec(currentLines.join(\"\\n\"))?.[1]?.trim() || null;\n    hosts.push({ host: currentHost, account });\n    currentHost = null;\n    currentLines = [];\n  };\n\n  for (const rawLine of text.split(/\\r?\\n/)) {\n    const line = rawLine.trim();\n    if (line.length === 0) continue;\n\n    const isHostLine =\n      rawLine.length === rawLine.trimStart().length && HOST_LINE_PATTERN.test(line);\n    if (isHostLine) {\n      flush();\n      currentHost = line.toLowerCase();\n      continue;\n    }\n\n    if (currentHost !== null) {\n      currentLines.push(line);\n    }\n  }\n\n  flush();\n  return hosts;\n}\n\nexport function findAuthenticatedGitLabHost(\n  hosts: ReadonlyArray<GitLabAuthStatusHost>,\n): GitLabAuthStatusHost | undefined {\n  return hosts.find((host) => host.account !== null);\n}\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport { SourceControlProviderError, type ChangeRequest } from \"@t3tools/contracts\";\n\nimport * as GitLabCli from \"./GitLabCli.ts\";\nimport * as SourceControlProvider from \"./SourceControlProvider.ts\";\nimport {\n  combinedAuthOutput,\n  firstSafeAuthLine,\n  matchFirst,\n  parseCliHost,\n  providerAuth,\n  type SourceControlAuthProbeInput,\n  type SourceControlCliDiscoverySpec,\n  type SourceControlUnknownRemoteRefinementInput,\n} from \"./SourceControlProviderDiscovery.ts\";\nimport { findAuthenticatedGitLabHost, parseGitLabAuthStatusHosts } from \"./gitLabAuthStatus.ts\";\n\nfunction toChangeRequest(summary: GitLabCli.GitLabMergeRequestSummary): ChangeRequest {\n  return {\n    provider: \"gitlab\",\n    number: summary.number,\n    title: summary.title,\n    url: summary.url,\n    baseRefName: summary.baseRefName,\n    headRefName: summary.headRefName,\n    state: summary.state ?? \"open\",\n    updatedAt: summary.updatedAt ?? Option.none(),\n    ...(summary.isCrossRepository !== undefined\n      ? { isCrossRepository: summary.isCrossRepository }\n      : {}),\n    ...(summary.headRepositoryNameWithOwner !== undefined\n      ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }\n      : {}),\n    ...(summary.headRepositoryOwnerLogin !== undefined\n      ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }\n      : {}),\n  };\n}\n\nfunction parseGitLabAuth(input: SourceControlAuthProbeInput) {\n  const output = combinedAuthOutput(input);\n  const authenticatedHost = findAuthenticatedGitLabHost(parseGitLabAuthStatusHosts(output));\n  const account =\n    authenticatedHost?.account ??\n    matchFirst(output, [\n      /Logged in to .* as\\s+([^\\s(]+)/iu,\n      /Logged in to .* account\\s+([^\\s(]+)/iu,\n      /account:\\s*([^\\s(]+)/iu,\n    ]);\n  const host = authenticatedHost?.host ?? parseCliHost(output);\n\n  if (account) {\n    return providerAuth({ status: \"authenticated\", account, host });\n  }\n\n  if (input.exitCode !== 0) {\n    return providerAuth({\n      status: \"unauthenticated\",\n      host,\n      detail: firstSafeAuthLine(output) ?? \"Run `glab auth login` to authenticate GitLab CLI.\",\n    });\n  }\n\n  return providerAuth({\n    status: \"unknown\",\n    host,\n    detail: firstSafeAuthLine(output) ?? \"GitLab CLI auth status could not be parsed.\",\n  });\n}\n\nfunction refineUnknownGitLabRemote(input: SourceControlUnknownRemoteRefinementInput) {\n  const host = input.context.provider.name.toLowerCase();\n  const authenticated = parseGitLabAuthStatusHosts(combinedAuthOutput(input.auth)).some(\n    (entry) => entry.account !== null && entry.host === host,\n  );\n\n  if (!authenticated) {\n    return null;\n  }\n\n  return {\n    kind: \"gitlab\",\n    name: \"GitLab Self-Hosted\",\n    baseUrl: input.context.provider.baseUrl,\n  } as const;\n}\n\nexport const discovery = {\n  type: \"cli\",\n  kind: \"gitlab\",\n  label: \"GitLab\",\n  executable: \"glab\",\n  versionArgs: [\"--version\"],\n  authArgs: [\"auth\", \"status\"],\n  parseAuth: parseGitLabAuth,\n  refineUnknownRemote: refineUnknownGitLabRemote,\n  installHint:\n    \"Install the GitLab command-line tool (`glab`) from https://gitlab.com/gitlab-org/cli or your package manager (for example `brew install glab`).\",\n} satisfies SourceControlCliDiscoverySpec;\n\nexport const make = Effect.gen(function* () {\n  const gitlab = yield* GitLabCli.GitLabCli;\n\n  return SourceControlProvider.SourceControlProvider.of({\n    kind: \"gitlab\",\n    listChangeRequests: (input) => {\n      const source = SourceControlProvider.sourceControlRefFromInput(input);\n      return gitlab\n        .listMergeRequests({\n          cwd: input.cwd,\n          headSelector: input.headSelector,\n          ...(source ? { source } : {}),\n          state: input.state,\n          ...(input.limit !== undefined ? { limit: input.limit } : {}),\n        })\n        .pipe(\n          Effect.map((items) => items.map(toChangeRequest)),\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"gitlab\",\n                operation: \"listChangeRequests\",\n                command: error.command,\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.headSelector,\n                ),\n                detail: error.detail,\n                cause: error,\n              }),\n          ),\n        );\n    },\n    getChangeRequest: (input) =>\n      gitlab.getMergeRequest(input).pipe(\n        Effect.map(toChangeRequest),\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"gitlab\",\n              operation: \"getChangeRequest\",\n              command: error.command,\n              cwd: input.cwd,\n              reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.reference,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    createChangeRequest: (input) => {\n      const source = SourceControlProvider.sourceControlRefFromInput(input);\n      return gitlab\n        .createMergeRequest({\n          cwd: input.cwd,\n          baseBranch: input.baseRefName,\n          headSelector: input.headSelector,\n          ...(source ? { source } : {}),\n          ...(input.target ? { target: input.target } : {}),\n          title: input.title,\n          bodyFile: input.bodyFile,\n        })\n        .pipe(\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"gitlab\",\n                operation: \"createChangeRequest\",\n                command: error.command,\n                cwd: input.cwd,\n                reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                  input.headSelector,\n                ),\n                detail: error.detail,\n                cause: error,\n              }),\n          ),\n        );\n    },\n    getRepositoryCloneUrls: (input) =>\n      gitlab.getRepositoryCloneUrls(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"gitlab\",\n              operation: \"getRepositoryCloneUrls\",\n              command: error.command,\n              cwd: input.cwd,\n              repository: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.repository,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    createRepository: (input) =>\n      gitlab.createRepository(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"gitlab\",\n              operation: \"createRepository\",\n              command: error.command,\n              cwd: input.cwd,\n              repository: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.repository,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    getDefaultBranch: (input) =>\n      gitlab.getDefaultBranch(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"gitlab\",\n              operation: \"getDefaultBranch\",\n              command: error.command,\n              cwd: input.cwd,\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n    checkoutChangeRequest: (input) =>\n      gitlab.checkoutMergeRequest(input).pipe(\n        Effect.mapError(\n          (error) =>\n            new SourceControlProviderError({\n              provider: \"gitlab\",\n              operation: \"checkoutChangeRequest\",\n              command: error.command,\n              cwd: input.cwd,\n              reference: SourceControlProvider.transportSafeSourceControlErrorValue(\n                input.reference,\n              ),\n              detail: error.detail,\n              cause: error,\n            }),\n        ),\n      ),\n  });\n});\n\nexport const layer = Layer.effect(SourceControlProvider.SourceControlProvider, make);\n","import * as Cache from \"effect/Cache\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport {\n  SourceControlProviderError,\n  type SourceControlProviderDiscoveryItem,\n} from \"@t3tools/contracts\";\nimport type { SourceControlProviderKind } from \"@t3tools/contracts\";\nimport { detectSourceControlProviderFromRemoteUrl } from \"@t3tools/shared/sourceControl\";\n\nimport * as AzureDevOpsSourceControlProvider from \"./AzureDevOpsSourceControlProvider.ts\";\nimport * as BitbucketSourceControlProvider from \"./BitbucketSourceControlProvider.ts\";\nimport * as GitHubSourceControlProvider from \"./GitHubSourceControlProvider.ts\";\nimport * as GitLabSourceControlProvider from \"./GitLabSourceControlProvider.ts\";\nimport * as SourceControlProvider from \"./SourceControlProvider.ts\";\nimport {\n  probeSourceControlProvider,\n  refineUnknownRemoteProvider,\n  type SourceControlProviderDiscoverySpec,\n} from \"./SourceControlProviderDiscovery.ts\";\nimport { ServerConfig } from \"../config.ts\";\nimport * as VcsDriverRegistry from \"../vcs/VcsDriverRegistry.ts\";\nimport * as VcsProcess from \"../vcs/VcsProcess.ts\";\n\nconst PROVIDER_DETECTION_CACHE_CAPACITY = 2_048;\nconst PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5);\n\nexport interface SourceControlProviderRegistration {\n  readonly kind: SourceControlProviderKind;\n  readonly provider: SourceControlProvider.SourceControlProvider[\"Service\"];\n  readonly discovery: SourceControlProviderDiscoverySpec;\n}\n\nexport interface SourceControlProviderHandle {\n  readonly provider: SourceControlProvider.SourceControlProvider[\"Service\"];\n  readonly context: SourceControlProvider.SourceControlProviderContext | null;\n}\n\nexport class SourceControlProviderRegistry extends Context.Service<\n  SourceControlProviderRegistry,\n  {\n    readonly get: (\n      kind: SourceControlProviderKind,\n    ) => Effect.Effect<\n      SourceControlProvider.SourceControlProvider[\"Service\"],\n      SourceControlProviderError\n    >;\n    readonly resolveHandle: (input: {\n      readonly cwd: string;\n    }) => Effect.Effect<SourceControlProviderHandle, SourceControlProviderError>;\n    readonly resolve: (input: {\n      readonly cwd: string;\n    }) => Effect.Effect<\n      SourceControlProvider.SourceControlProvider[\"Service\"],\n      SourceControlProviderError\n    >;\n    readonly discover: Effect.Effect<ReadonlyArray<SourceControlProviderDiscoveryItem>>;\n  }\n>()(\"t3/sourceControl/SourceControlProviderRegistry\") {}\n\nfunction unsupportedProvider(\n  kind: SourceControlProviderKind,\n): SourceControlProvider.SourceControlProvider[\"Service\"] {\n  return SourceControlProvider.SourceControlProvider.of({\n    kind,\n    listChangeRequests: (input) =>\n      new SourceControlProviderError({\n        provider: kind,\n        operation: \"listChangeRequests\",\n        cwd: input.cwd,\n        detail: `No ${kind} source control provider is registered.`,\n      }),\n    getChangeRequest: (input) =>\n      new SourceControlProviderError({\n        provider: kind,\n        operation: \"getChangeRequest\",\n        cwd: input.cwd,\n        reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),\n        detail: `No ${kind} source control provider is registered.`,\n      }),\n    createChangeRequest: (input) =>\n      new SourceControlProviderError({\n        provider: kind,\n        operation: \"createChangeRequest\",\n        cwd: input.cwd,\n        reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.headSelector),\n        detail: `No ${kind} source control provider is registered.`,\n      }),\n    getRepositoryCloneUrls: (input) =>\n      new SourceControlProviderError({\n        provider: kind,\n        operation: \"getRepositoryCloneUrls\",\n        cwd: input.cwd,\n        repository: SourceControlProvider.transportSafeSourceControlErrorValue(input.repository),\n        detail: `No ${kind} source control provider is registered.`,\n      }),\n    createRepository: (input) =>\n      new SourceControlProviderError({\n        provider: kind,\n        operation: \"createRepository\",\n        cwd: input.cwd,\n        repository: SourceControlProvider.transportSafeSourceControlErrorValue(input.repository),\n        detail: `No ${kind} source control provider is registered.`,\n      }),\n    getDefaultBranch: (input) =>\n      new SourceControlProviderError({\n        provider: kind,\n        operation: \"getDefaultBranch\",\n        cwd: input.cwd,\n        detail: `No ${kind} source control provider is registered.`,\n      }),\n    checkoutChangeRequest: (input) =>\n      new SourceControlProviderError({\n        provider: kind,\n        operation: \"checkoutChangeRequest\",\n        cwd: input.cwd,\n        reference: SourceControlProvider.transportSafeSourceControlErrorValue(input.reference),\n        detail: `No ${kind} source control provider is registered.`,\n      }),\n  });\n}\n\nfunction selectProviderContext(\n  remotes: ReadonlyArray<{\n    readonly name: string;\n    readonly url: string;\n  }>,\n): SourceControlProvider.SourceControlProviderContext | null {\n  const candidates: Array<SourceControlProvider.SourceControlProviderContext> = [];\n  for (const remote of remotes) {\n    const provider = detectSourceControlProviderFromRemoteUrl(remote.url);\n    if (provider) {\n      candidates.push({\n        provider,\n        remoteName: remote.name,\n        remoteUrl: remote.url,\n      });\n    }\n  }\n\n  return (\n    candidates.find((candidate) => candidate.remoteName === \"origin\") ??\n    candidates.find((candidate) => candidate.provider.kind !== \"unknown\") ??\n    candidates[0] ??\n    null\n  );\n}\n\nfunction bindProviderContext(\n  provider: SourceControlProvider.SourceControlProvider[\"Service\"],\n  context: SourceControlProvider.SourceControlProviderContext | null,\n): SourceControlProvider.SourceControlProvider[\"Service\"] {\n  if (context === null) {\n    return provider;\n  }\n\n  return SourceControlProvider.SourceControlProvider.of({\n    kind: provider.kind,\n    listChangeRequests: (input) =>\n      provider.listChangeRequests({\n        ...input,\n        context: input.context ?? context,\n      }),\n    getChangeRequest: (input) =>\n      provider.getChangeRequest({\n        ...input,\n        context: input.context ?? context,\n      }),\n    createChangeRequest: (input) =>\n      provider.createChangeRequest({\n        ...input,\n        context: input.context ?? context,\n      }),\n    getRepositoryCloneUrls: (input) =>\n      provider.getRepositoryCloneUrls({\n        ...input,\n        context: input.context ?? context,\n      }),\n    createRepository: (input) => provider.createRepository(input),\n    getDefaultBranch: (input) =>\n      provider.getDefaultBranch({\n        ...input,\n        context: input.context ?? context,\n      }),\n    checkoutChangeRequest: (input) =>\n      provider.checkoutChangeRequest({\n        ...input,\n        context: input.context ?? context,\n      }),\n  });\n}\n\nexport const makeWithProviders = Effect.fn(\"makeSourceControlProviderRegistryWithProviders\")(\n  function* (registrations: ReadonlyArray<SourceControlProviderRegistration>) {\n    const config = yield* ServerConfig;\n    const process = yield* VcsProcess.VcsProcess;\n    const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;\n    const providers = new Map<\n      SourceControlProviderKind,\n      SourceControlProvider.SourceControlProvider[\"Service\"]\n    >(registrations.map((registration) => [registration.kind, registration.provider]));\n    const discoverySpecs = registrations.map((registration) => registration.discovery);\n\n    const get: SourceControlProviderRegistry[\"Service\"][\"get\"] = (kind) =>\n      Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind));\n\n    const detectProviderContext = Effect.fn(\"SourceControlProviderRegistry.detectProviderContext\")(\n      function* (cwd: string) {\n        const handle = yield* vcsRegistry.resolve({ cwd }).pipe(\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"unknown\",\n                operation: \"detectProvider\",\n                cwd,\n                detail: \"Failed to detect source control provider.\",\n                cause: error,\n              }),\n          ),\n        );\n        const remotes = yield* handle.driver.listRemotes(cwd).pipe(\n          Effect.mapError(\n            (error) =>\n              new SourceControlProviderError({\n                provider: \"unknown\",\n                operation: \"detectProvider\",\n                cwd,\n                detail: \"Failed to detect source control provider.\",\n                cause: error,\n              }),\n          ),\n        );\n        const context = selectProviderContext(remotes.remotes);\n\n        return yield* refineUnknownRemoteProvider({\n          specs: discoverySpecs,\n          process,\n          cwd,\n          context,\n        });\n      },\n    );\n\n    const providerContextCache = yield* Cache.makeWith<\n      string,\n      SourceControlProvider.SourceControlProviderContext | null,\n      SourceControlProviderError\n    >(detectProviderContext, {\n      capacity: PROVIDER_DETECTION_CACHE_CAPACITY,\n      timeToLive: (exit) => (Exit.isSuccess(exit) ? PROVIDER_DETECTION_CACHE_TTL : Duration.zero),\n    });\n\n    const resolveHandle: SourceControlProviderRegistry[\"Service\"][\"resolveHandle\"] = (input) =>\n      Cache.get(providerContextCache, input.cwd).pipe(\n        Effect.map((context) => {\n          const kind = context?.provider.kind ?? \"unknown\";\n          const provider = providers.get(kind) ?? unsupportedProvider(kind);\n          return {\n            provider: bindProviderContext(provider, context),\n            context,\n          } satisfies SourceControlProviderHandle;\n        }),\n      );\n\n    return SourceControlProviderRegistry.of({\n      get,\n      resolveHandle,\n      resolve: (input) => resolveHandle(input).pipe(Effect.map((handle) => handle.provider)),\n      discover: Effect.all(\n        discoverySpecs.map((spec) =>\n          probeSourceControlProvider({\n            spec,\n            process,\n            cwd: config.cwd,\n          }),\n        ),\n        { concurrency: \"unbounded\" },\n      ),\n    });\n  },\n);\n\nexport const make = Effect.gen(function* () {\n  const github = yield* GitHubSourceControlProvider.make;\n  const gitlab = yield* GitLabSourceControlProvider.make;\n  const bitbucket = yield* BitbucketSourceControlProvider.make;\n  const bitbucketDiscovery = yield* BitbucketSourceControlProvider.makeDiscovery;\n  const azureDevOps = yield* AzureDevOpsSourceControlProvider.make;\n  return yield* makeWithProviders([\n    {\n      kind: \"github\",\n      provider: github,\n      discovery: GitHubSourceControlProvider.discovery,\n    },\n    {\n      kind: \"gitlab\",\n      provider: gitlab,\n      discovery: GitLabSourceControlProvider.discovery,\n    },\n    {\n      kind: \"azure-devops\",\n      provider: azureDevOps,\n      discovery: AzureDevOpsSourceControlProvider.discovery,\n    },\n    {\n      kind: \"bitbucket\",\n      provider: bitbucket,\n      discovery: bitbucketDiscovery,\n    },\n  ]);\n});\n\nexport const layer = Layer.effect(SourceControlProviderRegistry, make);\n","import type { GitCommandError } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\n\nimport type * as GitVcsDriver from \"../vcs/GitVcsDriver.ts\";\n\nconst TEMPLATE_MAX_BYTES = 8_000;\nconst TREE_LIST_MAX_BYTES = 100_000;\nconst TRUNCATION_MARKER = \"[truncated]\";\n\nconst TEMPLATE_PATHS = [\n  \".github/pull_request_template.md\",\n  \".github/PULL_REQUEST_TEMPLATE.md\",\n  \"pull_request_template.md\",\n  \"PULL_REQUEST_TEMPLATE.md\",\n  \"docs/pull_request_template.md\",\n  \"docs/PULL_REQUEST_TEMPLATE.md\",\n] as const;\n\nconst TEMPLATE_DIRECTORIES = [\n  \".github/PULL_REQUEST_TEMPLATE\",\n  \"PULL_REQUEST_TEMPLATE\",\n  \"docs/PULL_REQUEST_TEMPLATE\",\n] as const;\n\nconst TREE_PATHS = [...TEMPLATE_PATHS, ...TEMPLATE_DIRECTORIES] as const;\n\ntype ExecuteGit = GitVcsDriver.GitVcsDriver[\"Service\"][\"execute\"];\n\ninterface TemplateTreeEntry {\n  readonly objectId: string;\n  readonly path: string;\n}\n\nfunction parseTemplateTreeEntries(output: string): ReadonlyArray<TemplateTreeEntry> {\n  const entries: TemplateTreeEntry[] = [];\n  for (const record of output.split(\"\\0\")) {\n    if (record.length === 0) {\n      continue;\n    }\n\n    const separator = record.indexOf(\"\\t\");\n    if (separator < 0) {\n      continue;\n    }\n\n    const [mode, type, objectId] = record.slice(0, separator).split(\" \");\n    if (\n      type !== \"blob\" ||\n      (mode !== \"100644\" && mode !== \"100755\") ||\n      !objectId ||\n      !/^[0-9a-f]{40,64}$/.test(objectId)\n    ) {\n      continue;\n    }\n\n    entries.push({ objectId, path: record.slice(separator + 1) });\n  }\n  return entries;\n}\n\nfunction readTemplateBlob(input: {\n  readonly cwd: string;\n  readonly executeGit: ExecuteGit;\n  readonly entry: TemplateTreeEntry;\n}): Effect.Effect<Option.Option<string>, GitCommandError> {\n  return input\n    .executeGit({\n      operation: \"PrTemplateDetection.readTemplateBlob\",\n      cwd: input.cwd,\n      args: [\"cat-file\", \"blob\", input.entry.objectId],\n      maxOutputBytes: TEMPLATE_MAX_BYTES,\n      appendTruncationMarker: true,\n    })\n    .pipe(\n      Effect.map((result) => {\n        const template = result.stdout.trim();\n        if (template.length === 0) {\n          return Option.none();\n        }\n        return Option.some(\n          result.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER)\n            ? `${template}\\n\\n${TRUNCATION_MARKER}`\n            : template,\n        );\n      }),\n    );\n}\n\ntype DirectoryTemplateResult =\n  | { readonly _tag: \"None\" }\n  | { readonly _tag: \"Ambiguous\" }\n  | { readonly _tag: \"Template\"; readonly template: string };\n\nfunction readTemplateDirectory(input: {\n  readonly cwd: string;\n  readonly executeGit: ExecuteGit;\n  readonly entries: ReadonlyArray<TemplateTreeEntry>;\n  readonly directory: string;\n}): Effect.Effect<DirectoryTemplateResult, GitCommandError> {\n  return Effect.gen(function* () {\n    const prefix = `${input.directory}/`;\n    const candidates = input.entries.filter((entry) => {\n      if (!entry.path.startsWith(prefix)) {\n        return false;\n      }\n      const relativePath = entry.path.slice(prefix.length);\n      return !relativePath.includes(\"/\") && relativePath.toLowerCase().endsWith(\".md\");\n    });\n\n    const templates: string[] = [];\n    for (const entry of candidates) {\n      const template = yield* readTemplateBlob({ ...input, entry });\n      if (Option.isSome(template)) {\n        templates.push(template.value);\n        if (templates.length > 1) {\n          return { _tag: \"Ambiguous\" } as const;\n        }\n      }\n    }\n\n    return templates[0]\n      ? ({ _tag: \"Template\", template: templates[0] } as const)\n      : ({ _tag: \"None\" } as const);\n  });\n}\n\nexport const detectPrTemplate = Effect.fn(\"detectPrTemplate\")(function* (\n  cwd: string,\n  treeish: string,\n  executeGit: ExecuteGit,\n) {\n  return yield* Effect.gen(function* () {\n    // Worktree paths can be replaced between validation and open. Read regular blobs from the\n    // committed base tree so repository-controlled symlinks and path races never reach the host filesystem.\n    const result = yield* executeGit({\n      operation: \"PrTemplateDetection.listTemplates\",\n      cwd,\n      args: [\"ls-tree\", \"-r\", \"-z\", \"--full-tree\", treeish, \"--\", ...TREE_PATHS],\n      maxOutputBytes: TREE_LIST_MAX_BYTES,\n      appendTruncationMarker: true,\n    });\n    if (result.stdoutTruncated) {\n      return Option.none();\n    }\n\n    const entries = parseTemplateTreeEntries(result.stdout);\n    const entriesByPath = new Map(entries.map((entry) => [entry.path, entry]));\n    for (const templatePath of TEMPLATE_PATHS) {\n      const entry = entriesByPath.get(templatePath);\n      if (!entry) {\n        continue;\n      }\n      const template = yield* readTemplateBlob({ cwd, executeGit, entry });\n      if (Option.isSome(template)) {\n        return template;\n      }\n    }\n\n    for (const directory of TEMPLATE_DIRECTORIES) {\n      const directoryTemplate = yield* readTemplateDirectory({\n        cwd,\n        executeGit,\n        entries,\n        directory,\n      });\n      if (directoryTemplate._tag === \"Template\") {\n        return Option.some(directoryTemplate.template);\n      }\n      if (directoryTemplate._tag === \"Ambiguous\") {\n        return Option.none();\n      }\n    }\n\n    return Option.none();\n  }).pipe(Effect.orElseSucceed(() => Option.none()));\n});\n","import * as Arr from \"effect/Array\";\nimport * as Cache from \"effect/Cache\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Path from \"effect/Path\";\nimport * as Ref from \"effect/Ref\";\nimport {\n  GitActionProgressEvent,\n  GitActionProgressPhase,\n  GitCommandError,\n  GitPreparePullRequestThreadInput,\n  GitPreparePullRequestThreadResult,\n  GitPullRequestRefInput,\n  GitResolvePullRequestResult,\n  GitRunStackedActionInput,\n  GitRunStackedActionResult,\n  GitStackedAction,\n  VcsStatusInput,\n  type VcsStatusLocalResult,\n  type VcsStatusRemoteResult,\n  VcsStatusResult,\n  ModelSelection,\n  type SourceControlWritingStyleSettings,\n} from \"@t3tools/contracts\";\nimport {\n  detectSourceControlProviderFromGitRemoteUrl,\n  mergeGitStatusParts,\n  normalizeGitRemoteUrl,\n  resolveAutoFeatureBranchName,\n  sanitizeBranchFragment,\n  sanitizeFeatureBranchName,\n} from \"@t3tools/shared/git\";\nimport {\n  getChangeRequestTerminologyForKind,\n  type ChangeRequestTerminology,\n} from \"@t3tools/shared/sourceControl\";\n\nimport { GitManagerError, GitPullRequestMaterializationError } from \"@t3tools/contracts\";\nimport * as TextGeneration from \"../textGeneration/TextGeneration.ts\";\nimport {\n  conventionalCommitsTextGenerationPolicy,\n  customTextGenerationPolicy,\n  repositoryConventionsTextGenerationPolicy,\n} from \"../textGeneration/TextGenerationPresets.ts\";\nimport * as ProjectSetupScriptRunner from \"../project/ProjectSetupScriptRunner.ts\";\nimport * as ProviderRegistry from \"../provider/Services/ProviderRegistry.ts\";\nimport { extractBranchNameFromRemoteRef } from \"./remoteRefs.ts\";\nimport * as ServerSettings from \"../serverSettings.ts\";\nimport type { GitManagerServiceError } from \"@t3tools/contracts\";\nimport * as GitVcsDriver from \"../vcs/GitVcsDriver.ts\";\nimport * as SourceControlProviderRegistry from \"../sourceControl/SourceControlProviderRegistry.ts\";\nimport { detectPrTemplate } from \"../sourceControl/PrTemplateDetection.ts\";\nimport type { ChangeRequest } from \"@t3tools/contracts\";\n\nexport interface GitActionProgressReporter {\n  readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;\n}\n\nexport interface GitRunStackedActionOptions {\n  readonly actionId?: string;\n  readonly progressReporter?: GitActionProgressReporter;\n}\n\ninterface SourceControlTextGenerationSettings {\n  readonly modelSelection: ModelSelection;\n  readonly style: SourceControlWritingStyleSettings;\n}\n\nexport class GitManager extends Context.Service<\n  GitManager,\n  {\n    readonly status: (\n      input: VcsStatusInput,\n    ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;\n    readonly localStatus: (\n      input: VcsStatusInput,\n    ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;\n    readonly remoteStatus: (\n      input: VcsStatusInput,\n      options?: GitVcsDriver.GitRemoteStatusOptions,\n    ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;\n    readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;\n    readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;\n    readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;\n    readonly resolvePullRequest: (\n      input: GitPullRequestRefInput,\n    ) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;\n    readonly preparePullRequestThread: (\n      input: GitPreparePullRequestThreadInput,\n    ) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;\n    readonly runStackedAction: (\n      input: GitRunStackedActionInput,\n      options?: GitRunStackedActionOptions,\n    ) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;\n  }\n>()(\"t3/git/GitManager\") {}\n\nconst COMMIT_TIMEOUT_MS = 10 * 60_000;\nconst MAX_PROGRESS_TEXT_LENGTH = 500;\nconst SHORT_SHA_LENGTH = 7;\nconst TOAST_DESCRIPTION_MAX = 72;\nconst STATUS_RESULT_CACHE_TTL = Duration.seconds(1);\nconst STATUS_RESULT_CACHE_CAPACITY = 2_048;\nconst PR_LOOKUP_CACHE_TTL = Duration.minutes(2);\nconst PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20);\nconst PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15);\nconst PR_LOOKUP_CACHE_CAPACITY = 2_048;\n\n/**\n * How long a failed PR lookup is cached, given the number of consecutive\n * failures for that branch.\n *\n * A hosting provider rejects a throttled request immediately, so caching every\n * failure for a flat 20s made a rate-limited poller re-ask *faster* than a\n * healthy one does (which waits PR_LOOKUP_CACHE_TTL), turning a transient 429\n * into sustained pressure. Backing off per branch keeps the retry rate below\n * the healthy rate once a branch has failed more than a couple of times.\n */\nexport function prLookupFailureTtl(consecutiveFailures: number): Duration.Duration {\n  const exponent = Math.max(0, consecutiveFailures - 1);\n  const backoffMs = Duration.toMillis(PR_LOOKUP_FAILURE_BASE_TTL) * Math.pow(2, exponent);\n  return Duration.min(Duration.millis(backoffMs), PR_LOOKUP_FAILURE_MAX_TTL);\n}\ntype StripProgressContext<T> = T extends any ? Omit<T, \"actionId\" | \"cwd\" | \"action\"> : never;\ntype GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;\ntype GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;\n\nfunction isNotGitRepositoryError(error: GitCommandError): boolean {\n  return error.message.toLowerCase().includes(\"not a git repository\");\n}\n\ninterface OpenPrInfo {\n  number: number;\n  title: string;\n  url: string;\n  baseRefName: string;\n  headRefName: string;\n}\n\ninterface PullRequestInfo extends OpenPrInfo, PullRequestHeadRemoteInfo {\n  state: \"open\" | \"closed\" | \"merged\";\n  updatedAt: Option.Option<DateTime.Utc>;\n}\n\nconst pullRequestUpdatedAtDescOrder: Order.Order<PullRequestInfo> = Order.mapInput(\n  Order.flip(Option.makeOrder(DateTime.Order)),\n  (pullRequest) => pullRequest.updatedAt,\n);\n\ninterface ResolvedPullRequest {\n  number: number;\n  title: string;\n  url: string;\n  baseBranch: string;\n  headBranch: string;\n  state: \"open\" | \"closed\" | \"merged\";\n}\n\ninterface PullRequestHeadRemoteInfo {\n  isCrossRepository?: boolean | undefined;\n  headRepositoryNameWithOwner?: string | null | undefined;\n  headRepositoryOwnerLogin?: string | null | undefined;\n}\n\ninterface BranchHeadContext {\n  localBranch: string;\n  headBranch: string;\n  headSelectors: ReadonlyArray<string>;\n  preferredHeadSelector: string;\n  remoteName: string | null;\n  headRemoteUrlKey: string | null;\n  headRepositoryNameWithOwner: string | null;\n  headRepositoryOwnerLogin: string | null;\n  isCrossRepository: boolean;\n}\n\nfunction parseRepositoryNameFromPullRequestUrl(url: string): string | null {\n  const trimmed = url.trim();\n  const match = /^https:\\/\\/github\\.com\\/[^/]+\\/([^/]+)\\/pull\\/\\d+(?:\\/.*)?$/i.exec(trimmed);\n  const repositoryName = match?.[1]?.trim() ?? \"\";\n  return repositoryName.length > 0 ? repositoryName : null;\n}\n\nfunction resolveHeadRepositoryNameWithOwner(\n  pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,\n): string | null {\n  const explicitRepository = pullRequest.headRepositoryNameWithOwner?.trim() ?? \"\";\n  if (explicitRepository.length > 0) {\n    return explicitRepository;\n  }\n\n  if (!pullRequest.isCrossRepository) {\n    return null;\n  }\n\n  const ownerLogin = pullRequest.headRepositoryOwnerLogin?.trim() ?? \"\";\n  const repositoryName = parseRepositoryNameFromPullRequestUrl(pullRequest.url);\n  if (ownerLogin.length === 0 || !repositoryName) {\n    return null;\n  }\n\n  return `${ownerLogin}/${repositoryName}`;\n}\n\nfunction resolvePullRequestWorktreeLocalBranchName(\n  pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,\n): string {\n  if (!pullRequest.isCrossRepository) {\n    return pullRequest.headBranch;\n  }\n\n  const sanitizedHeadBranch = sanitizeBranchFragment(pullRequest.headBranch).trim();\n  const suffix = sanitizedHeadBranch.length > 0 ? sanitizedHeadBranch : \"head\";\n  return `synaptic/pr-${pullRequest.number}/${suffix}`;\n}\n\nfunction parseGitHubRepositoryNameWithOwnerFromRemoteUrl(url: string | null): string | null {\n  const trimmed = url?.trim() ?? \"\";\n  if (trimmed.length === 0) {\n    return null;\n  }\n\n  const match =\n    /^(?:git@github\\.com:|ssh:\\/\\/git@github\\.com\\/|https:\\/\\/github\\.com\\/|git:\\/\\/github\\.com\\/)([^/\\s]+\\/[^/\\s]+?)(?:\\.git)?\\/?$/i.exec(\n      trimmed,\n    );\n  const repositoryNameWithOwner = match?.[1]?.trim() ?? \"\";\n  return repositoryNameWithOwner.length > 0 ? repositoryNameWithOwner : null;\n}\n\nfunction parseRepositoryOwnerLogin(nameWithOwner: string | null): string | null {\n  const trimmed = nameWithOwner?.trim() ?? \"\";\n  if (trimmed.length === 0) {\n    return null;\n  }\n  const [ownerLogin] = trimmed.split(\"/\");\n  const normalizedOwnerLogin = ownerLogin?.trim() ?? \"\";\n  return normalizedOwnerLogin.length > 0 ? normalizedOwnerLogin : null;\n}\n\nfunction normalizeOptionalString(value: string | null | undefined): string | null {\n  const trimmed = value?.trim() ?? \"\";\n  return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeOptionalRepositoryNameWithOwner(value: string | null | undefined): string | null {\n  const normalized = normalizeOptionalString(value);\n  return normalized ? normalized.toLowerCase() : null;\n}\n\nfunction normalizeOptionalOwnerLogin(value: string | null | undefined): string | null {\n  const normalized = normalizeOptionalString(value);\n  return normalized ? normalized.toLowerCase() : null;\n}\n\nfunction resolvePullRequestHeadRepositoryNameWithOwner(\n  pr: PullRequestHeadRemoteInfo & { url: string },\n) {\n  const explicitRepository = normalizeOptionalString(pr.headRepositoryNameWithOwner);\n  if (explicitRepository) {\n    return explicitRepository;\n  }\n\n  if (!pr.isCrossRepository) {\n    return null;\n  }\n\n  const ownerLogin = normalizeOptionalString(pr.headRepositoryOwnerLogin);\n  const repositoryName = parseRepositoryNameFromPullRequestUrl(pr.url);\n  if (!ownerLogin || !repositoryName) {\n    return null;\n  }\n\n  return `${ownerLogin}/${repositoryName}`;\n}\n\ninterface PullRequestHeadIdentity {\n  readonly repositoryNameWithOwner: string | null;\n  readonly ownerLogin: string | null;\n}\n\nfunction resolveExpectedHeadIdentity(\n  headContext: Pick<BranchHeadContext, \"headRepositoryNameWithOwner\" | \"headRepositoryOwnerLogin\">,\n): PullRequestHeadIdentity {\n  const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(\n    headContext.headRepositoryNameWithOwner,\n  );\n  return {\n    repositoryNameWithOwner,\n    ownerLogin:\n      normalizeOptionalOwnerLogin(headContext.headRepositoryOwnerLogin) ??\n      parseRepositoryOwnerLogin(repositoryNameWithOwner),\n  };\n}\n\nfunction resolvePullRequestHeadIdentity(pr: PullRequestInfo): PullRequestHeadIdentity {\n  const repositoryNameWithOwner = normalizeOptionalRepositoryNameWithOwner(\n    resolvePullRequestHeadRepositoryNameWithOwner(pr),\n  );\n  return {\n    repositoryNameWithOwner,\n    ownerLogin:\n      normalizeOptionalOwnerLogin(pr.headRepositoryOwnerLogin) ??\n      parseRepositoryOwnerLogin(repositoryNameWithOwner),\n  };\n}\n\nexport function matchesBranchHeadContext(\n  pr: PullRequestInfo,\n  headContext: Pick<\n    BranchHeadContext,\n    \"headBranch\" | \"headRepositoryNameWithOwner\" | \"headRepositoryOwnerLogin\" | \"isCrossRepository\"\n  >,\n): boolean {\n  if (pr.headRefName !== headContext.headBranch) {\n    return false;\n  }\n\n  const expectedHead = resolveExpectedHeadIdentity(headContext);\n  const pullRequestHead = resolvePullRequestHeadIdentity(pr);\n\n  if (expectedHead.repositoryNameWithOwner) {\n    if (pullRequestHead.repositoryNameWithOwner) {\n      if (expectedHead.repositoryNameWithOwner !== pullRequestHead.repositoryNameWithOwner) {\n        return false;\n      }\n    }\n    if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {\n      if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {\n        return false;\n      }\n    }\n  }\n\n  if (expectedHead.ownerLogin && pullRequestHead.ownerLogin) {\n    if (expectedHead.ownerLogin !== pullRequestHead.ownerLogin) {\n      return false;\n    }\n  }\n\n  if (headContext.isCrossRepository) {\n    if (pr.isCrossRepository === false) {\n      return false;\n    }\n    if (\n      (expectedHead.repositoryNameWithOwner || expectedHead.ownerLogin) &&\n      !pullRequestHead.repositoryNameWithOwner &&\n      !pullRequestHead.ownerLogin\n    ) {\n      return false;\n    }\n    return true;\n  }\n\n  if (pr.isCrossRepository === true) {\n    if (\n      (!expectedHead.repositoryNameWithOwner && !expectedHead.ownerLogin) ||\n      (!pullRequestHead.repositoryNameWithOwner && !pullRequestHead.ownerLogin)\n    ) {\n      return false;\n    }\n  }\n\n  return true;\n}\n\nfunction toPullRequestInfo(summary: ChangeRequest): PullRequestInfo {\n  return {\n    number: summary.number,\n    title: summary.title,\n    url: summary.url,\n    baseRefName: summary.baseRefName,\n    headRefName: summary.headRefName,\n    state: summary.state ?? \"open\",\n    updatedAt: summary.updatedAt,\n    ...(summary.isCrossRepository !== undefined\n      ? { isCrossRepository: summary.isCrossRepository }\n      : {}),\n    ...(summary.headRepositoryNameWithOwner !== undefined\n      ? { headRepositoryNameWithOwner: summary.headRepositoryNameWithOwner }\n      : {}),\n    ...(summary.headRepositoryOwnerLogin !== undefined\n      ? { headRepositoryOwnerLogin: summary.headRepositoryOwnerLogin }\n      : {}),\n  };\n}\n\nfunction limitContext(value: string, maxChars: number): string {\n  if (value.length <= maxChars) return value;\n  return `${value.slice(0, maxChars)}\\n\\n[truncated]`;\n}\n\nfunction shortenSha(sha: string | undefined): string | null {\n  if (!sha) return null;\n  return sha.slice(0, SHORT_SHA_LENGTH);\n}\n\nfunction truncateText(\n  value: string | undefined,\n  maxLength = TOAST_DESCRIPTION_MAX,\n): string | undefined {\n  if (!value) return undefined;\n  if (value.length <= maxLength) return value;\n  if (maxLength <= 3) return \"...\".slice(0, maxLength);\n  return `${value.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`;\n}\n\nfunction withDescription(title: string, description: string | undefined) {\n  return description ? { title, description } : { title };\n}\n\nfunction summarizeGitActionResult(\n  result: Pick<GitRunStackedActionResult, \"commit\" | \"push\" | \"pr\">,\n  terms: ChangeRequestTerminology,\n): {\n  title: string;\n  description?: string;\n} {\n  if (result.pr.status === \"created\" || result.pr.status === \"opened_existing\") {\n    const prNumber = result.pr.number ? ` #${result.pr.number}` : \"\";\n    const title = `${result.pr.status === \"created\" ? \"Created\" : \"Opened\"} ${terms.shortLabel}${prNumber}`;\n    return withDescription(title, truncateText(result.pr.title));\n  }\n\n  if (result.push.status === \"pushed\") {\n    const shortSha = shortenSha(result.commit.commitSha);\n    const branch = result.push.upstreamBranch ?? result.push.branch;\n    const pushedCommitPart = shortSha ? ` ${shortSha}` : \"\";\n    const branchPart = branch ? ` to ${branch}` : \"\";\n    return withDescription(\n      `Pushed${pushedCommitPart}${branchPart}`,\n      truncateText(result.commit.subject),\n    );\n  }\n\n  if (result.commit.status === \"created\") {\n    const shortSha = shortenSha(result.commit.commitSha);\n    const title = shortSha ? `Committed ${shortSha}` : \"Committed changes\";\n    return withDescription(title, truncateText(result.commit.subject));\n  }\n\n  return { title: \"Done\" };\n}\n\nfunction sanitizeCommitMessage(generated: {\n  subject: string;\n  body: string;\n  branch?: string | undefined;\n}): {\n  subject: string;\n  body: string;\n  branch?: string | undefined;\n} {\n  const rawSubject = generated.subject.trim().split(/\\r?\\n/g)[0]?.trim() ?? \"\";\n  const subject = rawSubject.replace(/[.]+$/g, \"\").trim();\n  const safeSubject = subject.length > 0 ? subject.slice(0, 72).trimEnd() : \"Update project files\";\n  return {\n    subject: safeSubject,\n    body: generated.body.trim(),\n    ...(generated.branch !== undefined ? { branch: generated.branch } : {}),\n  };\n}\n\nfunction sanitizeProgressText(value: string): string | null {\n  const trimmed = value.trim();\n  if (trimmed.length === 0) {\n    return null;\n  }\n  if (trimmed.length <= MAX_PROGRESS_TEXT_LENGTH) {\n    return trimmed;\n  }\n  return trimmed.slice(0, MAX_PROGRESS_TEXT_LENGTH).trimEnd();\n}\n\ninterface CommitAndBranchSuggestion {\n  subject: string;\n  body: string;\n  branch?: string | undefined;\n  commitMessage: string;\n}\n\nfunction isCommitAction(\n  action: GitStackedAction,\n): action is \"commit\" | \"commit_push\" | \"commit_push_pr\" {\n  return action === \"commit\" || action === \"commit_push\" || action === \"commit_push_pr\";\n}\n\nfunction formatCommitMessage(subject: string, body: string): string {\n  const trimmedBody = body.trim();\n  if (trimmedBody.length === 0) {\n    return subject;\n  }\n  return `${subject}\\n\\n${trimmedBody}`;\n}\n\nfunction parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {\n  const normalized = raw.replace(/\\r\\n/g, \"\\n\").trim();\n  if (normalized.length === 0) {\n    return null;\n  }\n\n  const [firstLine, ...rest] = normalized.split(\"\\n\");\n  const subject = firstLine?.trim() ?? \"\";\n  if (subject.length === 0) {\n    return null;\n  }\n\n  return {\n    subject,\n    body: rest.join(\"\\n\").trim(),\n  };\n}\n\nfunction appendUnique(values: string[], next: string | null | undefined): void {\n  const trimmed = next?.trim() ?? \"\";\n  if (trimmed.length === 0 || values.includes(trimmed)) {\n    return;\n  }\n  values.push(trimmed);\n}\n\nfunction toStatusPr(pr: PullRequestInfo): {\n  number: number;\n  title: string;\n  url: string;\n  baseRef: string;\n  headRef: string;\n  state: \"open\" | \"closed\" | \"merged\";\n} {\n  return {\n    number: pr.number,\n    title: pr.title,\n    url: pr.url,\n    baseRef: pr.baseRefName,\n    headRef: pr.headRefName,\n    state: pr.state,\n  };\n}\n\nfunction normalizePullRequestReference(reference: string): string {\n  const trimmed = reference.trim();\n  const hashNumber = /^#(\\d+)$/.exec(trimmed);\n  return hashNumber?.[1] ?? trimmed;\n}\n\nfunction toResolvedPullRequest(pr: {\n  number: number;\n  title: string;\n  url: string;\n  baseRefName: string;\n  headRefName: string;\n  state?: \"open\" | \"closed\" | \"merged\";\n}): ResolvedPullRequest {\n  return {\n    number: pr.number,\n    title: pr.title,\n    url: pr.url,\n    baseBranch: pr.baseRefName,\n    headBranch: pr.headRefName,\n    state: pr.state ?? \"open\",\n  };\n}\n\nfunction shouldPreferSshRemote(url: string | null): boolean {\n  if (!url) return false;\n  const trimmed = url.trim();\n  return trimmed.startsWith(\"git@\") || trimmed.startsWith(\"ssh://\");\n}\n\nfunction toPullRequestHeadRemoteInfo(pr: {\n  isCrossRepository?: boolean | undefined;\n  headRepositoryNameWithOwner?: string | null | undefined;\n  headRepositoryOwnerLogin?: string | null | undefined;\n}): PullRequestHeadRemoteInfo {\n  return {\n    ...(pr.isCrossRepository !== undefined ? { isCrossRepository: pr.isCrossRepository } : {}),\n    ...(pr.headRepositoryNameWithOwner !== undefined\n      ? { headRepositoryNameWithOwner: pr.headRepositoryNameWithOwner }\n      : {}),\n    ...(pr.headRepositoryOwnerLogin !== undefined\n      ? { headRepositoryOwnerLogin: pr.headRepositoryOwnerLogin }\n      : {}),\n  };\n}\n\nexport const make = Effect.gen(function* () {\n  const gitCore = yield* GitVcsDriver.GitVcsDriver;\n  const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;\n  const textGeneration = yield* TextGeneration.TextGeneration;\n  const providerRegistry = yield* ProviderRegistry.ProviderRegistry;\n  const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;\n  const crypto = yield* Crypto.Crypto;\n\n  const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });\n  const serverSettingsService = yield* ServerSettings.ServerSettingsService;\n\n  const readRecentCommitSubjects = (cwd: string) =>\n    gitCore\n      .execute({\n        operation: \"GitManager.readRecentCommitSubjects\",\n        cwd,\n        args: [\"log\", \"-n\", \"20\", \"--no-merges\", \"--pretty=format:%s\"],\n      })\n      .pipe(\n        Effect.map((result) =>\n          result.stdout\n            .split(\"\\n\")\n            .map((line) => line.trim())\n            .filter((line) => line.length > 0),\n        ),\n        Effect.orElseSucceed(() => []),\n      );\n\n  const resolveStylePolicy = (cwd: string, style: SourceControlWritingStyleSettings) =>\n    Effect.gen(function* () {\n      switch (style.mode) {\n        case \"conventional_commits\":\n          return conventionalCommitsTextGenerationPolicy;\n        case \"custom\":\n          return customTextGenerationPolicy(\n            style.customInstructions\n              ? {\n                  commitInstructions: style.customInstructions,\n                  changeRequestInstructions: style.customInstructions,\n                }\n              : {},\n          );\n        case \"repo_conventions\": {\n          const subjects = yield* readRecentCommitSubjects(cwd);\n          if (subjects.length === 0) {\n            return repositoryConventionsTextGenerationPolicy;\n          }\n          const examples = [\"Recent commit subjects from this repository:\", ...subjects].join(\"\\n\");\n          return {\n            ...repositoryConventionsTextGenerationPolicy,\n            commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\\n\\n${examples}`,\n            changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\\n\\n${examples}`,\n          };\n        }\n      }\n    });\n  const randomUUIDv4 = (cwd: string) =>\n    crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new GitManagerError({\n            operation: \"randomUUIDv4\",\n            cwd,\n            detail: \"Failed to generate Git operation identifier.\",\n            cause,\n          }),\n      ),\n    );\n\n  const createProgressEmitter = (\n    input: { cwd: string; action: GitStackedAction },\n    options?: GitRunStackedActionOptions,\n  ) =>\n    (options?.actionId === undefined\n      ? randomUUIDv4(input.cwd)\n      : Effect.succeed(options.actionId)\n    ).pipe(\n      Effect.map((actionId) => {\n        const reporter = options?.progressReporter;\n        const emit = (event: GitActionProgressPayload) =>\n          reporter\n            ? reporter.publish({\n                actionId,\n                cwd: input.cwd,\n                action: input.action,\n                ...event,\n              } as GitActionProgressEvent)\n            : Effect.void;\n\n        return {\n          actionId,\n          emit,\n        };\n      }),\n    );\n\n  const configurePullRequestHeadUpstreamBase = Effect.fn(\"configurePullRequestHeadUpstream\")(\n    function* (\n      cwd: string,\n      pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,\n      localBranch = pullRequest.headBranch,\n    ) {\n      const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? \"\";\n      if (repositoryNameWithOwner.length === 0 && pullRequest.isCrossRepository !== true) {\n        const remoteName = yield* gitCore.resolvePrimaryRemoteName(cwd);\n        yield* gitCore.fetchRemoteTrackingBranch({\n          cwd,\n          remoteName,\n          remoteBranch: pullRequest.headBranch,\n        });\n        yield* gitCore.setBranchUpstream({\n          cwd,\n          branch: localBranch,\n          remoteName,\n          remoteBranch: pullRequest.headBranch,\n        });\n        return;\n      }\n\n      if (repositoryNameWithOwner.length === 0) {\n        return;\n      }\n\n      const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({\n        cwd,\n        repository: repositoryNameWithOwner,\n      });\n      const originRemoteUrl = yield* gitCore.readConfigValue(cwd, \"remote.origin.url\");\n      const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;\n      const preferredRemoteName =\n        pullRequest.headRepositoryOwnerLogin?.trim() ||\n        repositoryNameWithOwner.split(\"/\")[0]?.trim() ||\n        \"fork\";\n      const remoteName = yield* gitCore.ensureRemote({\n        cwd,\n        preferredName: preferredRemoteName,\n        url: remoteUrl,\n      });\n\n      yield* gitCore.fetchRemoteTrackingBranch({\n        cwd,\n        remoteName,\n        remoteBranch: pullRequest.headBranch,\n      });\n      yield* gitCore.setBranchUpstream({\n        cwd,\n        branch: localBranch,\n        remoteName,\n        remoteBranch: pullRequest.headBranch,\n      });\n    },\n  );\n\n  const configurePullRequestHeadUpstream = (\n    cwd: string,\n    pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,\n    localBranch = pullRequest.headBranch,\n  ) =>\n    configurePullRequestHeadUpstreamBase(cwd, pullRequest, localBranch).pipe(\n      Effect.catch((error) =>\n        Effect.logWarning(\"GitManager.configurePullRequestHeadUpstream failed\", {\n          cwd,\n          localBranch,\n          headBranch: pullRequest.headBranch,\n          cause: error,\n        }).pipe(Effect.asVoid),\n      ),\n    );\n\n  const materializePullRequestHeadBranchBase = Effect.fn(\"materializePullRequestHeadBranch\")(\n    function* (\n      cwd: string,\n      pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,\n      localBranch = pullRequest.headBranch,\n    ) {\n      const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? \"\";\n\n      if (repositoryNameWithOwner.length === 0) {\n        yield* gitCore.fetchPullRequestBranch({\n          cwd,\n          prNumber: pullRequest.number,\n          branch: localBranch,\n        });\n        return;\n      }\n\n      const cloneUrls = yield* (yield* sourceControlProvider(cwd)).getRepositoryCloneUrls({\n        cwd,\n        repository: repositoryNameWithOwner,\n      });\n      const originRemoteUrl = yield* gitCore.readConfigValue(cwd, \"remote.origin.url\");\n      const remoteUrl = shouldPreferSshRemote(originRemoteUrl) ? cloneUrls.sshUrl : cloneUrls.url;\n      const preferredRemoteName =\n        pullRequest.headRepositoryOwnerLogin?.trim() ||\n        repositoryNameWithOwner.split(\"/\")[0]?.trim() ||\n        \"fork\";\n      const remoteName = yield* gitCore.ensureRemote({\n        cwd,\n        preferredName: preferredRemoteName,\n        url: remoteUrl,\n      });\n\n      yield* gitCore.fetchRemoteBranch({\n        cwd,\n        remoteName,\n        remoteBranch: pullRequest.headBranch,\n        localBranch,\n      });\n      yield* gitCore.setBranchUpstream({\n        cwd,\n        branch: localBranch,\n        remoteName,\n        remoteBranch: pullRequest.headBranch,\n      });\n    },\n  );\n\n  const materializePullRequestHeadBranch = (\n    cwd: string,\n    pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,\n    localBranch = pullRequest.headBranch,\n  ) =>\n    materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe(\n      Effect.catch((primaryCause) =>\n        gitCore\n          .fetchPullRequestBranch({\n            cwd,\n            prNumber: pullRequest.number,\n            branch: localBranch,\n          })\n          .pipe(\n            Effect.mapError(\n              (fallbackCause) =>\n                new GitPullRequestMaterializationError({\n                  cwd,\n                  pullRequestNumber: pullRequest.number,\n                  headRepository: resolveHeadRepositoryNameWithOwner(pullRequest),\n                  headBranch: pullRequest.headBranch,\n                  localBranch,\n                  cause: new AggregateError(\n                    [primaryCause, fallbackCause],\n                    `Repository-head and pull-request-ref fetches both failed for pull request #${pullRequest.number}.`,\n                    { cause: primaryCause },\n                  ),\n                }),\n            ),\n          ),\n      ),\n    );\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? \"/tmp\";\n  const canonicalizeExistingPath = (value: string) =>\n    fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));\n  const normalizeStatusCacheKey = canonicalizeExistingPath;\n  const nonRepositoryStatusDetails = {\n    isRepo: false,\n    hasOriginRemote: false,\n    isDefaultBranch: false,\n    branch: null,\n    upstreamRef: null,\n    hasWorkingTreeChanges: false,\n    workingTree: { files: [], insertions: 0, deletions: 0 },\n    hasUpstream: false,\n    aheadCount: 0,\n    behindCount: 0,\n    aheadOfDefaultCount: 0,\n  } satisfies GitVcsDriver.GitStatusDetails;\n  const readLocalStatus = Effect.fn(\"readLocalStatus\")(function* (cwd: string) {\n    const details = yield* gitCore\n      .statusDetailsLocal(cwd)\n      .pipe(\n        Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)),\n      );\n    const hostingProvider = details.isRepo\n      ? yield* resolveHostingProvider(cwd, details.branch)\n      : null;\n\n    return {\n      isRepo: details.isRepo,\n      ...(hostingProvider ? { sourceControlProvider: hostingProvider } : {}),\n      hasPrimaryRemote: details.hasOriginRemote,\n      isDefaultRef: details.isDefaultBranch,\n      refName: details.branch,\n      hasWorkingTreeChanges: details.hasWorkingTreeChanges,\n      workingTree: details.workingTree,\n    } satisfies VcsStatusLocalResult;\n  });\n  const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {\n    capacity: STATUS_RESULT_CACHE_CAPACITY,\n    timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),\n  });\n  const invalidateLocalStatusResultCache = (cwd: string) =>\n    normalizeStatusCacheKey(cwd).pipe(\n      Effect.flatMap((cacheKey) => Cache.invalidate(localStatusResultCache, cacheKey)),\n    );\n  // PR lookups hit the hosting provider's API (gh/glab/...), so they refresh\n  // on their own, slower cadence: ahead/behind counts stay fresh on every\n  // status poll while the PR association is re-fetched at most once per\n  // PR_LOOKUP_CACHE_TTL per branch. Git actions and user-driven refreshes bump\n  // the epoch (invalidateStatus) to bypass the cache immediately.\n  const prLookupEpochByCwd = new Map<string, number>();\n  const prLookupEpoch = (cwd: string) => prLookupEpochByCwd.get(cwd) ?? 0;\n  const bumpPrLookupEpoch = (cwd: string) =>\n    normalizeStatusCacheKey(cwd).pipe(\n      Effect.map((cacheKey) => {\n        prLookupEpochByCwd.set(cacheKey, prLookupEpoch(cacheKey) + 1);\n      }),\n    );\n  // Cache keys are NUL-joined [cwd, branch, upstreamRef, epoch] — none of the\n  // segments can contain a NUL byte, and refs are never empty, so \"\" decodes\n  // back to a null upstreamRef.\n  const prLookupCacheKey = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>\n    [cwd, details.branch, details.upstreamRef ?? \"\", String(prLookupEpoch(cwd))].join(\"\\u0000\");\n  // Consecutive failures per cache key, so a branch that keeps failing waits\n  // longer before the next attempt. Cleared as soon as a lookup succeeds.\n  const prLookupFailureStreakByKey = new Map<string, number>();\n  const nextPrLookupFailureTtl = (key: string) => {\n    if (\n      !prLookupFailureStreakByKey.has(key) &&\n      prLookupFailureStreakByKey.size >= PR_LOOKUP_CACHE_CAPACITY\n    ) {\n      const oldestKey = prLookupFailureStreakByKey.keys().next().value;\n      if (oldestKey !== undefined) {\n        prLookupFailureStreakByKey.delete(oldestKey);\n      }\n    }\n    const streak = (prLookupFailureStreakByKey.get(key) ?? 0) + 1;\n    prLookupFailureStreakByKey.set(key, streak);\n    return prLookupFailureTtl(streak);\n  };\n  const prLookupCache = yield* Cache.makeWith(\n    (key: string) => {\n      const [cwd = \"\", branch = \"\", upstreamRef = \"\"] = key.split(\"\\u0000\");\n      const details = {\n        branch,\n        upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,\n      };\n      return Effect.gen(function* () {\n        const headContext = yield* resolveBranchHeadContext(cwd, details);\n        // Only skip when the branch is untracked as well: anything carrying an\n        // upstream keeps the old behaviour.\n        if (details.upstreamRef === null && (yield* isUnpublishedBranch(cwd, headContext))) {\n          return { latest: null, headContext };\n        }\n        const latest = yield* findLatestPrForHeadContext(cwd, headContext);\n        return { latest, headContext };\n      });\n    },\n    {\n      capacity: PR_LOOKUP_CACHE_CAPACITY,\n      timeToLive: (exit, key) => {\n        if (Exit.isSuccess(exit)) {\n          prLookupFailureStreakByKey.delete(key);\n          return PR_LOOKUP_CACHE_TTL;\n        }\n        return nextPrLookupFailureTtl(key);\n      },\n    },\n  );\n  // A transient lookup failure (rate limit, network blip) must not clear an\n  // already-known PR badge, so the last successful answer per branch sticks\n  // around as the fallback. Keep the resolved head context with it so a\n  // branch retargeted to another remote/fork cannot inherit the old badge.\n  interface LastKnownPr {\n    readonly pr: ReturnType<typeof toStatusPr> | null;\n    readonly upstreamRef: string | null;\n    readonly headBranch: string;\n    readonly remoteName: string | null;\n    readonly headRemoteUrlKey: string | null;\n  }\n  const lastKnownPrByBranchKey = new Map<string, LastKnownPr>();\n  const rememberLastKnownPr = (branchKey: string, entry: LastKnownPr) => {\n    if (\n      !lastKnownPrByBranchKey.has(branchKey) &&\n      lastKnownPrByBranchKey.size >= PR_LOOKUP_CACHE_CAPACITY\n    ) {\n      const oldestKey = lastKnownPrByBranchKey.keys().next().value;\n      if (oldestKey !== undefined) {\n        lastKnownPrByBranchKey.delete(oldestKey);\n      }\n    }\n    lastKnownPrByBranchKey.set(branchKey, entry);\n  };\n  const resolveLastKnownPr = (\n    branchKey: string,\n    current: Pick<LastKnownPr, \"upstreamRef\" | \"headBranch\" | \"remoteName\" | \"headRemoteUrlKey\">,\n  ): ReturnType<typeof toStatusPr> | null => {\n    const lastKnown = lastKnownPrByBranchKey.get(branchKey);\n    if (!lastKnown) return null;\n    if (lastKnown.headBranch !== current.headBranch) {\n      return null;\n    }\n\n    // The normalized URL catches both remote-alias changes and an existing\n    // alias being repointed. Both sides must be resolved before treating a\n    // mismatch as real: `readConfigValueNullable` swallows any git-config\n    // read failure into `null`, so a transient failure to resolve the\n    // *current* remote URL must read as \"unknown\", not as \"no remote\" — the\n    // latter would otherwise drop an already-known PR badge on every hiccup.\n    if (lastKnown.headRemoteUrlKey !== null && current.headRemoteUrlKey !== null) {\n      return lastKnown.headRemoteUrlKey === current.headRemoteUrlKey ? lastKnown.pr : null;\n    }\n\n    // If the remote URL can't be compared, fall back to the remote identity\n    // encoded by tracked branches — same \"both sides known\" requirement, for\n    // the same reason. A null-to-non-null transition (upstream/remoteName)\n    // is allowed because that is the expected first-push case.\n    if (\n      lastKnown.upstreamRef !== null &&\n      current.upstreamRef !== null &&\n      lastKnown.remoteName !== null &&\n      current.remoteName !== null\n    ) {\n      return lastKnown.remoteName === current.remoteName ? lastKnown.pr : null;\n    }\n    return lastKnown.pr;\n  };\n  const lookupStatusPr = Effect.fn(\"lookupStatusPr\")(function* (\n    cwd: string,\n    details: { branch: string; upstreamRef: string | null; isDefaultBranch: boolean },\n  ) {\n    // Keyed by (cwd, branch) only: the upstream ref changing (e.g. a first\n    // `push -u`) must not orphan the fallback value for the same branch.\n    const branchKey = `${cwd}\\u0000${details.branch}`;\n    return yield* Cache.get(prLookupCache, prLookupCacheKey(cwd, details)).pipe(\n      Effect.map(({ latest, headContext }) => {\n        if (!latest) return { pr: null, headContext };\n        // On the default branch, only surface open PRs.\n        // Merged/closed matches are usually reverse-merge history, not the thread's PR context.\n        if (details.isDefaultBranch && latest.state !== \"open\") {\n          return { pr: null, headContext };\n        }\n        return { pr: toStatusPr(latest), headContext };\n      }),\n      Effect.tap(({ pr, headContext }) =>\n        Effect.sync(() =>\n          rememberLastKnownPr(branchKey, {\n            pr,\n            upstreamRef: details.upstreamRef,\n            headBranch: headContext.headBranch,\n            remoteName: headContext.remoteName,\n            headRemoteUrlKey: headContext.headRemoteUrlKey,\n          }),\n        ),\n      ),\n      Effect.map(({ pr }) => pr),\n      Effect.catch((error) =>\n        Effect.logWarning(\"PR lookup failed; keeping last known PR state.\").pipe(\n          Effect.annotateLogs({\n            operation: \"lookupStatusPr\",\n            branch: details.branch,\n            errorTag:\n              typeof error === \"object\" && error !== null && \"_tag\" in error\n                ? String(error._tag)\n                : typeof error,\n          }),\n          Effect.andThen(resolveBranchHeadContext(cwd, details)),\n          Effect.map((headContext) =>\n            resolveLastKnownPr(branchKey, {\n              upstreamRef: details.upstreamRef,\n              headBranch: headContext.headBranch,\n              remoteName: headContext.remoteName,\n              headRemoteUrlKey: headContext.headRemoteUrlKey,\n            }),\n          ),\n        ),\n      ),\n    );\n  });\n  const readRemoteStatus = Effect.fn(\"readRemoteStatus\")(function* (\n    cwd: string,\n    options?: GitVcsDriver.GitRemoteStatusOptions,\n  ) {\n    const details = yield* gitCore\n      .statusDetailsRemote(cwd, options)\n      .pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));\n    if (details === null || !details.isRepo) {\n      return null;\n    }\n\n    const pr =\n      details.branch !== null\n        ? yield* lookupStatusPr(cwd, {\n            branch: details.branch,\n            upstreamRef: details.upstreamRef,\n            isDefaultBranch: details.isDefaultBranch,\n          })\n        : null;\n\n    return {\n      hasUpstream: details.hasUpstream,\n      aheadCount: details.aheadCount,\n      behindCount: details.behindCount,\n      aheadOfDefaultCount: details.aheadOfDefaultCount,\n      pr,\n    } satisfies VcsStatusRemoteResult;\n  });\n  const remoteStatusResultCache = yield* Cache.makeWith((cwd: string) => readRemoteStatus(cwd), {\n    capacity: STATUS_RESULT_CACHE_CAPACITY,\n    timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),\n  });\n  const invalidateRemoteStatusResultCache = (cwd: string) =>\n    normalizeStatusCacheKey(cwd).pipe(\n      Effect.flatMap((cacheKey) => Cache.invalidate(remoteStatusResultCache, cacheKey)),\n    );\n\n  const readConfigValueNullable = (cwd: string, key: string) =>\n    gitCore.readConfigValue(cwd, key).pipe(Effect.orElseSucceed(() => null));\n\n  const resolveHostingProvider = Effect.fn(\"resolveHostingProvider\")(function* (\n    cwd: string,\n    branch: string | null,\n  ) {\n    const preferredRemoteName =\n      branch === null\n        ? \"origin\"\n        : ((yield* readConfigValueNullable(cwd, `branch.${branch}.remote`)) ?? \"origin\");\n    const remoteUrl =\n      (yield* readConfigValueNullable(cwd, `remote.${preferredRemoteName}.url`)) ??\n      (yield* readConfigValueNullable(cwd, \"remote.origin.url\"));\n\n    return remoteUrl ? detectSourceControlProviderFromGitRemoteUrl(remoteUrl) : null;\n  });\n\n  const resolveRemoteRepositoryContext = Effect.fn(\"resolveRemoteRepositoryContext\")(function* (\n    cwd: string,\n    remoteName: string | null,\n  ) {\n    if (!remoteName) {\n      return {\n        remoteUrlKey: null,\n        repositoryNameWithOwner: null,\n        ownerLogin: null,\n      };\n    }\n\n    const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`);\n    const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl);\n    return {\n      remoteUrlKey: remoteUrl ? normalizeGitRemoteUrl(remoteUrl) : null,\n      repositoryNameWithOwner,\n      ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner),\n    };\n  });\n\n  const resolveBranchHeadContext = Effect.fn(\"resolveBranchHeadContext\")(function* (\n    cwd: string,\n    details: { branch: string; upstreamRef: string | null },\n  ) {\n    const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`);\n    const headBranchFromUpstream = details.upstreamRef\n      ? extractBranchNameFromRemoteRef(details.upstreamRef, { remoteName })\n      : \"\";\n    const headBranch = headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch;\n    const shouldProbeLocalBranchSelector =\n      headBranchFromUpstream.length === 0 || headBranch === details.branch;\n\n    const [remoteRepository, originRepository] = yield* Effect.all(\n      [\n        resolveRemoteRepositoryContext(cwd, remoteName),\n        resolveRemoteRepositoryContext(cwd, \"origin\"),\n      ],\n      { concurrency: \"unbounded\" },\n    );\n\n    const isCrossRepository =\n      remoteRepository.repositoryNameWithOwner !== null &&\n      originRepository.repositoryNameWithOwner !== null\n        ? remoteRepository.repositoryNameWithOwner.toLowerCase() !==\n          originRepository.repositoryNameWithOwner.toLowerCase()\n        : remoteName !== null &&\n          remoteName !== \"origin\" &&\n          remoteRepository.repositoryNameWithOwner !== null;\n\n    const ownerHeadSelector =\n      remoteRepository.ownerLogin && headBranch.length > 0\n        ? `${remoteRepository.ownerLogin}:${headBranch}`\n        : null;\n    const remoteAliasHeadSelector =\n      remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null;\n    const shouldProbeRemoteOwnedSelectors =\n      isCrossRepository || (remoteName !== null && remoteName !== \"origin\");\n\n    const headSelectors: string[] = [];\n    if (isCrossRepository && shouldProbeRemoteOwnedSelectors) {\n      appendUnique(headSelectors, ownerHeadSelector);\n      appendUnique(\n        headSelectors,\n        remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,\n      );\n    }\n    if (shouldProbeLocalBranchSelector) {\n      appendUnique(headSelectors, details.branch);\n    }\n    appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null);\n    if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) {\n      appendUnique(headSelectors, ownerHeadSelector);\n      appendUnique(\n        headSelectors,\n        remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null,\n      );\n    }\n\n    return {\n      localBranch: details.branch,\n      headBranch,\n      headSelectors,\n      preferredHeadSelector:\n        ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch,\n      remoteName,\n      headRemoteUrlKey:\n        remoteRepository.remoteUrlKey ??\n        (remoteName === null ? originRepository.remoteUrlKey : null),\n      headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner,\n      headRepositoryOwnerLogin: remoteRepository.ownerLogin,\n      isCrossRepository,\n    } satisfies BranchHeadContext;\n  });\n\n  /**\n   * Whether git has no record of this branch on any remote, so a change request\n   * cannot exist for it and asking the provider is a guaranteed-empty API call.\n   *\n   * `git push` writes the remote-tracking ref even without `-u` (how most\n   * terminal and agent pushes land), which makes this a safer \"did it ever\n   * reach the host\" test than looking for upstream config, and the glob spans\n   * every remote so a fork branch still counts. A repository that tracks no\n   * remotes at all cannot answer the question, because then every branch looks\n   * unpublished; it, and any failed probe, keeps the lookup.\n   */\n  const isUnpublishedBranch = Effect.fn(\"isUnpublishedBranch\")(function* (\n    cwd: string,\n    headContext: Pick<BranchHeadContext, \"headBranch\">,\n  ) {\n    if (headContext.headBranch.length === 0) {\n      return false;\n    }\n    const matchesRef = (pattern: string) =>\n      gitCore\n        .execute({\n          operation: \"GitManager.isUnpublishedBranch\",\n          cwd,\n          args: [\"for-each-ref\", \"--count=1\", \"--format=%(refname)\", pattern],\n          timeoutMs: 5_000,\n        })\n        .pipe(Effect.map((result) => result.stdout.trim().length > 0));\n\n    return yield* Effect.all(\n      [matchesRef(\"refs/remotes\"), matchesRef(`refs/remotes/*/${headContext.headBranch}`)],\n      { concurrency: \"unbounded\" },\n    ).pipe(\n      Effect.map(([tracksAnyRemote, tracksThisBranch]) => tracksAnyRemote && !tracksThisBranch),\n      Effect.orElseSucceed(() => false),\n    );\n  });\n\n  const findOpenPr = Effect.fn(\"findOpenPr\")(function* (\n    cwd: string,\n    headContext: Pick<\n      BranchHeadContext,\n      | \"headBranch\"\n      | \"headSelectors\"\n      | \"headRepositoryNameWithOwner\"\n      | \"headRepositoryOwnerLogin\"\n      | \"isCrossRepository\"\n    >,\n  ) {\n    for (const headSelector of headContext.headSelectors) {\n      const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({\n        cwd,\n        headSelector,\n        state: \"open\",\n        limit: 1,\n      });\n      const normalizedPullRequests = pullRequests.map(toPullRequestInfo);\n\n      const firstPullRequest = normalizedPullRequests.find((pullRequest) =>\n        matchesBranchHeadContext(pullRequest, headContext),\n      );\n      if (firstPullRequest) {\n        return {\n          number: firstPullRequest.number,\n          title: firstPullRequest.title,\n          url: firstPullRequest.url,\n          baseRefName: firstPullRequest.baseRefName,\n          headRefName: firstPullRequest.headRefName,\n          state: \"open\",\n          updatedAt: Option.none(),\n        } satisfies PullRequestInfo;\n      }\n    }\n\n    return null;\n  });\n\n  const findLatestPrForHeadContext = Effect.fn(\"findLatestPrForHeadContext\")(function* (\n    cwd: string,\n    headContext: BranchHeadContext,\n  ) {\n    const parsedByNumber = new Map<number, PullRequestInfo>();\n\n    for (const headSelector of headContext.headSelectors) {\n      const pullRequests = yield* (yield* sourceControlProvider(cwd)).listChangeRequests({\n        cwd,\n        headSelector,\n        state: \"all\",\n        limit: 20,\n      });\n\n      for (const pr of pullRequests.map(toPullRequestInfo)) {\n        if (!matchesBranchHeadContext(pr, headContext)) {\n          continue;\n        }\n        parsedByNumber.set(pr.number, pr);\n      }\n    }\n\n    const parsed = Arr.sort(parsedByNumber.values(), pullRequestUpdatedAtDescOrder);\n\n    const latestOpenPr = parsed.find((pr) => pr.state === \"open\");\n    if (latestOpenPr) {\n      return latestOpenPr;\n    }\n    return parsed[0] ?? null;\n  });\n  const buildCompletionToast = Effect.fn(\"buildCompletionToast\")(function* (\n    cwd: string,\n    result: Pick<GitRunStackedActionResult, \"action\" | \"branch\" | \"commit\" | \"push\" | \"pr\">,\n  ) {\n    const terms = yield* sourceControlProvider(cwd).pipe(\n      Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),\n      Effect.orElseSucceed(() => getChangeRequestTerminologyForKind(\"unknown\")),\n    );\n    const summary = summarizeGitActionResult(result, terms);\n    let latestOpenPr: PullRequestInfo | null = null;\n    let currentBranchIsDefault = false;\n    let finalBranchContext: {\n      branch: string;\n      upstreamRef: string | null;\n      hasUpstream: boolean;\n    } | null = null;\n\n    if (result.action !== \"commit\") {\n      const finalStatus = yield* gitCore.statusDetails(cwd);\n      if (finalStatus.branch) {\n        finalBranchContext = {\n          branch: finalStatus.branch,\n          upstreamRef: finalStatus.upstreamRef,\n          hasUpstream: finalStatus.hasUpstream,\n        };\n        currentBranchIsDefault = finalStatus.isDefaultBranch;\n      }\n    }\n\n    const explicitResultPr =\n      (result.pr.status === \"created\" || result.pr.status === \"opened_existing\") && result.pr.url\n        ? {\n            url: result.pr.url,\n            state: \"open\" as const,\n          }\n        : null;\n    const shouldLookupExistingOpenPr =\n      (result.action === \"commit_push\" || result.action === \"push\") &&\n      result.push.status === \"pushed\" &&\n      result.branch.status !== \"created\" &&\n      !currentBranchIsDefault &&\n      explicitResultPr === null &&\n      finalBranchContext?.hasUpstream === true;\n\n    if (shouldLookupExistingOpenPr && finalBranchContext) {\n      latestOpenPr = yield* resolveBranchHeadContext(cwd, {\n        branch: finalBranchContext.branch,\n        upstreamRef: finalBranchContext.upstreamRef,\n      }).pipe(\n        Effect.flatMap((headContext) => findOpenPr(cwd, headContext)),\n        Effect.orElseSucceed(() => null),\n      );\n    }\n\n    const openPr = latestOpenPr ?? explicitResultPr;\n\n    const cta =\n      result.action === \"commit\" && result.commit.status === \"created\"\n        ? {\n            kind: \"run_action\" as const,\n            label: \"Push\",\n            action: { kind: \"push\" as const },\n          }\n        : (result.action === \"push\" ||\n              result.action === \"create_pr\" ||\n              result.action === \"commit_push\" ||\n              result.action === \"commit_push_pr\") &&\n            openPr?.url &&\n            (!currentBranchIsDefault ||\n              result.pr.status === \"created\" ||\n              result.pr.status === \"opened_existing\")\n          ? {\n              kind: \"open_pr\" as const,\n              label: `View ${terms.shortLabel}`,\n              url: openPr.url,\n            }\n          : (result.action === \"push\" || result.action === \"commit_push\") &&\n              result.push.status === \"pushed\" &&\n              !currentBranchIsDefault\n            ? {\n                kind: \"run_action\" as const,\n                label: `Create ${terms.shortLabel}`,\n                action: { kind: \"create_pr\" as const },\n              }\n            : {\n                kind: \"none\" as const,\n              };\n\n    return {\n      ...summary,\n      cta,\n    };\n  });\n\n  const resolveBaseBranch = Effect.fn(\"resolveBaseBranch\")(function* (\n    cwd: string,\n    branch: string,\n    upstreamRef: string | null,\n    headContext: Pick<BranchHeadContext, \"isCrossRepository\" | \"remoteName\">,\n  ) {\n    const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`);\n    if (configured) return configured;\n\n    if (upstreamRef && !headContext.isCrossRepository) {\n      const upstreamBranch = extractBranchNameFromRemoteRef(upstreamRef, {\n        remoteName: headContext.remoteName,\n      });\n      if (upstreamBranch.length > 0 && upstreamBranch !== branch) {\n        return upstreamBranch;\n      }\n    }\n\n    const defaultFromProvider = yield* sourceControlProvider(cwd).pipe(\n      Effect.flatMap((provider) => provider.getDefaultBranch({ cwd })),\n      Effect.orElseSucceed(() => null),\n    );\n    if (defaultFromProvider) {\n      return defaultFromProvider;\n    }\n\n    return \"main\";\n  });\n\n  const resolveBaseRangeRef = Effect.fn(\"resolveBaseRangeRef\")(function* (\n    cwd: string,\n    baseBranch: string,\n  ) {\n    const remoteName = yield* gitCore\n      .resolvePrimaryRemoteName(cwd)\n      .pipe(Effect.orElseSucceed(() => null));\n    if (!remoteName) return baseBranch;\n\n    return yield* gitCore\n      .resolveRemoteTrackingCommit({\n        cwd,\n        refName: baseBranch,\n        fallbackRemoteName: remoteName,\n      })\n      .pipe(\n        Effect.map((resolved) => resolved.commitSha),\n        Effect.orElseSucceed(() => baseBranch),\n      );\n  });\n\n  const resolveCommitAndBranchSuggestion = Effect.fn(\"resolveCommitAndBranchSuggestion\")(\n    function* (input: {\n      cwd: string;\n      branch: string | null;\n      commitMessage?: string;\n      /** When true, also produce a semantic feature branch name. */\n      includeBranch?: boolean;\n      filePaths?: readonly string[];\n      settings: SourceControlTextGenerationSettings;\n    }) {\n      const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);\n      if (!context) {\n        return null;\n      }\n\n      const customCommit = parseCustomCommitMessage(input.commitMessage ?? \"\");\n      if (customCommit) {\n        return {\n          subject: customCommit.subject,\n          body: customCommit.body,\n          ...(input.includeBranch\n            ? { branch: sanitizeFeatureBranchName(customCommit.subject) }\n            : {}),\n          commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),\n        };\n      }\n\n      const policy = yield* resolveStylePolicy(input.cwd, input.settings.style);\n\n      const generated = yield* textGeneration\n        .generateCommitMessage({\n          cwd: input.cwd,\n          branch: input.branch,\n          stagedSummary: limitContext(context.stagedSummary, 8_000),\n          stagedPatch: limitContext(context.stagedPatch, 50_000),\n          ...(input.includeBranch ? { includeBranch: true } : {}),\n          ...(policy ? { policy } : {}),\n          modelSelection: input.settings.modelSelection,\n        })\n        .pipe(Effect.map((result) => sanitizeCommitMessage(result)));\n\n      return {\n        subject: generated.subject,\n        body: generated.body,\n        ...(generated.branch !== undefined ? { branch: generated.branch } : {}),\n        commitMessage: formatCommitMessage(generated.subject, generated.body),\n      };\n    },\n  );\n\n  const runCommitStep = Effect.fn(\"runCommitStep\")(function* (\n    settings: SourceControlTextGenerationSettings,\n    cwd: string,\n    action: \"commit\" | \"commit_push\" | \"commit_push_pr\",\n    branch: string | null,\n    commitMessage?: string,\n    preResolvedSuggestion?: CommitAndBranchSuggestion,\n    filePaths?: readonly string[],\n    progressReporter?: GitActionProgressReporter,\n    actionId?: string,\n  ) {\n    const emit = (event: GitActionProgressPayload) =>\n      progressReporter && actionId\n        ? progressReporter.publish({\n            actionId,\n            cwd,\n            action,\n            ...event,\n          } as GitActionProgressEvent)\n        : Effect.void;\n\n    let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion;\n    if (!suggestion) {\n      const needsGeneration = !commitMessage?.trim();\n      if (needsGeneration) {\n        yield* emit({\n          kind: \"phase_started\",\n          phase: \"commit\",\n          label: \"Generating commit message...\",\n        });\n      }\n      suggestion = yield* resolveCommitAndBranchSuggestion({\n        cwd,\n        branch,\n        ...(commitMessage ? { commitMessage } : {}),\n        ...(filePaths ? { filePaths } : {}),\n        settings,\n      });\n    }\n    if (!suggestion) {\n      return { status: \"skipped_no_changes\" as const };\n    }\n\n    yield* emit({\n      kind: \"phase_started\",\n      phase: \"commit\",\n      label: \"Committing...\",\n    });\n\n    let currentHookName: string | null = null;\n    const commitProgress =\n      progressReporter && actionId\n        ? {\n            onOutputLine: ({ stream, text }: { stream: \"stdout\" | \"stderr\"; text: string }) => {\n              const sanitized = sanitizeProgressText(text);\n              if (!sanitized) {\n                return Effect.void;\n              }\n              return emit({\n                kind: \"hook_output\",\n                hookName: currentHookName,\n                stream,\n                text: sanitized,\n              });\n            },\n            onHookStarted: (hookName: string) => {\n              currentHookName = hookName;\n              return emit({\n                kind: \"hook_started\",\n                hookName,\n              });\n            },\n            onHookFinished: ({\n              hookName,\n              exitCode,\n              durationMs,\n            }: {\n              hookName: string;\n              exitCode: number | null;\n              durationMs: number | null;\n            }) => {\n              if (currentHookName === hookName) {\n                currentHookName = null;\n              }\n              return emit({\n                kind: \"hook_finished\",\n                hookName,\n                exitCode,\n                durationMs,\n              });\n            },\n          }\n        : null;\n    const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, {\n      timeoutMs: COMMIT_TIMEOUT_MS,\n      ...(commitProgress ? { progress: commitProgress } : {}),\n    });\n    if (currentHookName !== null) {\n      yield* emit({\n        kind: \"hook_finished\",\n        hookName: currentHookName,\n        exitCode: 0,\n        durationMs: null,\n      });\n      currentHookName = null;\n    }\n    return {\n      status: \"created\" as const,\n      commitSha,\n      subject: suggestion.subject,\n    };\n  });\n\n  const runPrStep = Effect.fn(\"runPrStep\")(function* (\n    settings: SourceControlTextGenerationSettings,\n    cwd: string,\n    fallbackBranch: string | null,\n    emit: GitActionProgressEmitter,\n  ) {\n    const provider = yield* sourceControlProvider(cwd);\n    const terms = getChangeRequestTerminologyForKind(provider.kind);\n    const details = yield* gitCore.statusDetails(cwd);\n    const branch = details.branch ?? fallbackBranch;\n    if (!branch) {\n      return yield* new GitManagerError({\n        operation: \"runPrStep\",\n        cwd,\n        detail: \"Cannot create a pull request from detached HEAD.\",\n      });\n    }\n    if (!details.hasUpstream) {\n      return yield* new GitManagerError({\n        operation: \"runPrStep\",\n        cwd,\n        detail: \"Current branch has not been pushed. Push before creating a PR.\",\n      });\n    }\n\n    const headContext = yield* resolveBranchHeadContext(cwd, {\n      branch,\n      upstreamRef: details.upstreamRef,\n    });\n\n    const existing = yield* findOpenPr(cwd, headContext);\n    if (existing) {\n      return {\n        status: \"opened_existing\" as const,\n        url: existing.url,\n        number: existing.number,\n        baseBranch: existing.baseRefName,\n        headBranch: existing.headRefName,\n        title: existing.title,\n      };\n    }\n\n    const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext);\n    yield* emit({\n      kind: \"phase_started\",\n      phase: \"pr\",\n      label: `Generating ${terms.shortLabel} content...`,\n    });\n    const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseBranch);\n    const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);\n    const policy = yield* resolveStylePolicy(cwd, settings.style);\n    const changeRequestTemplate =\n      settings.style.followChangeRequestTemplates && provider.kind === \"github\"\n        ? Option.getOrUndefined(yield* detectPrTemplate(cwd, baseRangeRef, gitCore.execute))\n        : undefined;\n\n    const generated = yield* textGeneration.generatePrContent({\n      cwd,\n      baseBranch,\n      headBranch: headContext.headBranch,\n      commitSummary: limitContext(rangeContext.commitSummary, 20_000),\n      diffSummary: limitContext(rangeContext.diffSummary, 20_000),\n      diffPatch: limitContext(rangeContext.diffPatch, 60_000),\n      ...(changeRequestTemplate ? { changeRequestTemplate } : {}),\n      ...(policy ? { policy } : {}),\n      modelSelection: settings.modelSelection,\n    });\n\n    const bodyFile = path.join(\n      tempDir,\n      `t3code-pr-body-${process.pid}-${yield* randomUUIDv4(cwd)}.md`,\n    );\n    yield* fileSystem.writeFileString(bodyFile, generated.body).pipe(\n      Effect.mapError(\n        (cause) =>\n          new GitManagerError({\n            operation: \"runPrStep\",\n            cwd,\n            detail: \"Failed to write pull request body temp file.\",\n            cause,\n          }),\n      ),\n    );\n    yield* emit({\n      kind: \"phase_started\",\n      phase: \"pr\",\n      label: `Creating ${terms.singular}...`,\n    });\n    yield* provider\n      .createChangeRequest({\n        cwd,\n        baseRefName: baseBranch,\n        headSelector: headContext.preferredHeadSelector,\n        title: generated.title,\n        bodyFile,\n      })\n      .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void))));\n\n    const created = yield* findOpenPr(cwd, headContext);\n    if (!created) {\n      return {\n        status: \"created\" as const,\n        baseBranch,\n        headBranch: headContext.headBranch,\n        title: generated.title,\n      };\n    }\n\n    return {\n      status: \"created\" as const,\n      url: created.url,\n      number: created.number,\n      baseBranch: created.baseRefName,\n      headBranch: created.headRefName,\n      title: created.title,\n    };\n  });\n\n  const localStatus: GitManager[\"Service\"][\"localStatus\"] = Effect.fn(\"localStatus\")(\n    function* (input) {\n      const cacheKey = yield* normalizeStatusCacheKey(input.cwd);\n      return yield* Cache.get(localStatusResultCache, cacheKey);\n    },\n  );\n  const remoteStatus: GitManager[\"Service\"][\"remoteStatus\"] = Effect.fn(\"remoteStatus\")(\n    function* (input, options) {\n      const cacheKey = yield* normalizeStatusCacheKey(input.cwd);\n      if (options?.refreshUpstream === false) {\n        return yield* readRemoteStatus(cacheKey, options);\n      }\n      return yield* Cache.get(remoteStatusResultCache, cacheKey);\n    },\n  );\n  const status: GitManager[\"Service\"][\"status\"] = Effect.fn(\"status\")(function* (input) {\n    const [local, remote] = yield* Effect.all([localStatus(input), remoteStatus(input)], {\n      concurrency: \"unbounded\",\n    });\n    return mergeGitStatusParts(local, remote);\n  });\n  const invalidateLocalStatus: GitManager[\"Service\"][\"invalidateLocalStatus\"] = Effect.fn(\n    \"invalidateLocalStatus\",\n  )(function* (cwd) {\n    yield* invalidateLocalStatusResultCache(cwd);\n  });\n  const invalidateRemoteStatus: GitManager[\"Service\"][\"invalidateRemoteStatus\"] = Effect.fn(\n    \"invalidateRemoteStatus\",\n  )(function* (cwd) {\n    yield* invalidateRemoteStatusResultCache(cwd);\n  });\n  const invalidateStatus: GitManager[\"Service\"][\"invalidateStatus\"] = Effect.fn(\"invalidateStatus\")(\n    function* (cwd) {\n      yield* invalidateLocalStatusResultCache(cwd);\n      yield* invalidateRemoteStatusResultCache(cwd);\n      // Full invalidation is the explicit-freshness path (git actions, user\n      // refresh); it also bypasses the slow PR-lookup cache. The periodic\n      // status poll only invalidates local/remote and keeps the PR cache warm.\n      yield* bumpPrLookupEpoch(cwd);\n    },\n  );\n\n  const resolvePullRequest: GitManager[\"Service\"][\"resolvePullRequest\"] = Effect.fn(\n    \"resolvePullRequest\",\n  )(function* (input) {\n    const pullRequest = yield* (yield* sourceControlProvider(input.cwd))\n      .getChangeRequest({\n        cwd: input.cwd,\n        reference: normalizePullRequestReference(input.reference),\n      })\n      .pipe(Effect.map((resolved) => toResolvedPullRequest(resolved)));\n\n    return { pullRequest };\n  });\n\n  const preparePullRequestThread: GitManager[\"Service\"][\"preparePullRequestThread\"] = Effect.fn(\n    \"preparePullRequestThread\",\n  )(function* (input) {\n    const maybeRunSetupScript = (worktreePath: string) => {\n      if (!input.threadId) {\n        return Effect.void;\n      }\n      return projectSetupScriptRunner\n        .runForThread({\n          threadId: input.threadId,\n          projectCwd: input.cwd,\n          worktreePath,\n        })\n        .pipe(\n          Effect.catch((error) =>\n            Effect.logWarning(\"GitManager.preparePullRequestThread setup script failed\", {\n              threadId: input.threadId,\n              worktreePath,\n              cause: error,\n            }).pipe(Effect.asVoid),\n          ),\n        );\n    };\n    return yield* Effect.gen(function* () {\n      const normalizedReference = normalizePullRequestReference(input.reference);\n      const rootWorktreePath = yield* canonicalizeExistingPath(input.cwd);\n      const pullRequestSummary = yield* (yield* sourceControlProvider(input.cwd)).getChangeRequest({\n        cwd: input.cwd,\n        reference: normalizedReference,\n      });\n      const pullRequest = toResolvedPullRequest(pullRequestSummary);\n\n      if (input.mode === \"local\") {\n        yield* (yield* sourceControlProvider(input.cwd)).checkoutChangeRequest({\n          cwd: input.cwd,\n          reference: normalizedReference,\n          force: true,\n        });\n        const details = yield* gitCore.statusDetails(input.cwd);\n        yield* configurePullRequestHeadUpstream(\n          input.cwd,\n          {\n            ...pullRequest,\n            ...toPullRequestHeadRemoteInfo(pullRequestSummary),\n          },\n          details.branch ?? pullRequest.headBranch,\n        );\n        return {\n          pullRequest,\n          branch: details.branch ?? pullRequest.headBranch,\n          worktreePath: null,\n        };\n      }\n\n      const ensureExistingWorktreeUpstream = Effect.fn(\"ensureExistingWorktreeUpstream\")(function* (\n        worktreePath: string,\n      ) {\n        const details = yield* gitCore.statusDetails(worktreePath);\n        yield* configurePullRequestHeadUpstream(\n          worktreePath,\n          {\n            ...pullRequest,\n            ...toPullRequestHeadRemoteInfo(pullRequestSummary),\n          },\n          details.branch ?? pullRequest.headBranch,\n        );\n      });\n\n      const pullRequestWithRemoteInfo = {\n        ...pullRequest,\n        ...toPullRequestHeadRemoteInfo(pullRequestSummary),\n      } as const;\n      const localPullRequestBranch =\n        resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo);\n\n      const findLocalHeadBranch = Effect.fn(\"findLocalHeadBranch\")(function* (cwd: string) {\n        const result = yield* gitCore.listRefs({ cwd, refresh: true });\n        const localBranch = result.refs.find(\n          (branch) => !branch.isRemote && branch.name === localPullRequestBranch,\n        );\n        if (localBranch) {\n          return localBranch;\n        }\n        if (localPullRequestBranch === pullRequest.headBranch) {\n          return null;\n        }\n\n        for (const branch of result.refs) {\n          if (branch.isRemote || branch.name !== pullRequest.headBranch || !branch.worktreePath) {\n            continue;\n          }\n\n          const worktreePath = yield* canonicalizeExistingPath(branch.worktreePath);\n          if (worktreePath !== rootWorktreePath) {\n            return branch;\n          }\n        }\n\n        return null;\n      });\n\n      const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd);\n      const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath\n        ? yield* canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath)\n        : null;\n      if (\n        existingBranchBeforeFetch?.worktreePath &&\n        existingBranchBeforeFetchPath !== rootWorktreePath\n      ) {\n        yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath);\n        return {\n          pullRequest,\n          branch: localPullRequestBranch,\n          worktreePath: existingBranchBeforeFetch.worktreePath,\n        };\n      }\n      if (existingBranchBeforeFetchPath === rootWorktreePath) {\n        return yield* new GitManagerError({\n          operation: \"preparePullRequestThread\",\n          cwd: input.cwd,\n          detail:\n            \"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.\",\n        });\n      }\n\n      yield* materializePullRequestHeadBranch(\n        input.cwd,\n        pullRequestWithRemoteInfo,\n        localPullRequestBranch,\n      );\n\n      const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd);\n      const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath\n        ? yield* canonicalizeExistingPath(existingBranchAfterFetch.worktreePath)\n        : null;\n      if (\n        existingBranchAfterFetch?.worktreePath &&\n        existingBranchAfterFetchPath !== rootWorktreePath\n      ) {\n        yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath);\n        return {\n          pullRequest,\n          branch: localPullRequestBranch,\n          worktreePath: existingBranchAfterFetch.worktreePath,\n        };\n      }\n      if (existingBranchAfterFetchPath === rootWorktreePath) {\n        return yield* new GitManagerError({\n          operation: \"preparePullRequestThread\",\n          cwd: input.cwd,\n          detail:\n            \"This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.\",\n        });\n      }\n\n      const worktree = yield* gitCore.createWorktree({\n        cwd: input.cwd,\n        refName: localPullRequestBranch,\n        path: null,\n      });\n      yield* ensureExistingWorktreeUpstream(worktree.worktree.path);\n      yield* maybeRunSetupScript(worktree.worktree.path);\n\n      return {\n        pullRequest,\n        branch: worktree.worktree.refName,\n        worktreePath: worktree.worktree.path,\n      };\n    }).pipe(Effect.ensuring(invalidateStatus(input.cwd)));\n  });\n\n  const runFeatureBranchStep = Effect.fn(\"runFeatureBranchStep\")(function* (\n    settings: SourceControlTextGenerationSettings,\n    cwd: string,\n    branch: string | null,\n    commitMessage?: string,\n    filePaths?: readonly string[],\n  ) {\n    const suggestion = yield* resolveCommitAndBranchSuggestion({\n      cwd,\n      branch,\n      ...(commitMessage ? { commitMessage } : {}),\n      ...(filePaths ? { filePaths } : {}),\n      includeBranch: true,\n      settings,\n    });\n    if (!suggestion) {\n      return yield* new GitManagerError({\n        operation: \"runFeatureBranchStep\",\n        cwd,\n        detail: \"Cannot create a feature branch because there are no changes to commit.\",\n      });\n    }\n\n    const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);\n    const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);\n    const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);\n\n    yield* gitCore.createRef({ cwd, refName: resolvedBranch });\n    yield* Effect.scoped(gitCore.switchRef({ cwd, refName: resolvedBranch }));\n\n    return {\n      branchStep: { status: \"created\" as const, name: resolvedBranch },\n      resolvedCommitMessage: suggestion.commitMessage,\n      resolvedCommitSuggestion: suggestion,\n    };\n  });\n\n  const runStackedAction: GitManager[\"Service\"][\"runStackedAction\"] = Effect.fn(\"runStackedAction\")(\n    function* (input, options) {\n      const progress = yield* createProgressEmitter(input, options);\n      const currentPhase = yield* Ref.make<Option.Option<GitActionProgressPhase>>(Option.none());\n\n      const runAction = Effect.fn(\"runStackedAction.runAction\")(function* (): Effect.fn.Return<\n        GitRunStackedActionResult,\n        GitManagerServiceError\n      > {\n        const initialStatus = yield* gitCore.statusDetails(input.cwd);\n        const wantsCommit = isCommitAction(input.action);\n        const wantsPush =\n          input.action === \"push\" ||\n          input.action === \"commit_push\" ||\n          input.action === \"commit_push_pr\" ||\n          (input.action === \"create_pr\" &&\n            (!initialStatus.hasUpstream || initialStatus.aheadCount > 0));\n        const wantsPr = input.action === \"create_pr\" || input.action === \"commit_push_pr\";\n\n        if (input.featureBranch && !wantsCommit) {\n          return yield* new GitManagerError({\n            operation: \"runStackedAction\",\n            cwd: input.cwd,\n            detail: \"Feature-branch checkout is only supported for commit actions.\",\n          });\n        }\n        if (input.action === \"create_pr\" && initialStatus.hasWorkingTreeChanges) {\n          return yield* new GitManagerError({\n            operation: \"runStackedAction\",\n            cwd: input.cwd,\n            detail: \"Commit local changes before creating a PR.\",\n          });\n        }\n\n        const phases: GitActionProgressPhase[] = [\n          ...(input.featureBranch ? ([\"branch\"] as const) : []),\n          ...(wantsCommit ? ([\"commit\"] as const) : []),\n          ...(wantsPush ? ([\"push\"] as const) : []),\n          ...(wantsPr ? ([\"pr\"] as const) : []),\n        ];\n\n        yield* progress.emit({\n          kind: \"action_started\",\n          phases,\n        });\n\n        if (!input.featureBranch && wantsPush && !initialStatus.branch) {\n          return yield* new GitManagerError({\n            operation: \"runStackedAction\",\n            cwd: input.cwd,\n            detail: \"Cannot push from detached HEAD.\",\n          });\n        }\n        if (!input.featureBranch && wantsPr && !initialStatus.branch) {\n          return yield* new GitManagerError({\n            operation: \"runStackedAction\",\n            cwd: input.cwd,\n            detail: \"Cannot create a pull request from detached HEAD.\",\n          });\n        }\n\n        let branchStep: { status: \"created\" | \"skipped_not_requested\"; name?: string };\n        let commitMessageForStep = input.commitMessage;\n        let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;\n\n        const textGenerationSettings = yield* serverSettingsService.getSettings.pipe(\n          Effect.flatMap((settings) =>\n            settings.sourceControlWriterModelSelection === null\n              ? Effect.succeed({\n                  modelSelection: settings.textGenerationModelSelection,\n                  style: settings.sourceControlWritingStyle,\n                })\n              : providerRegistry.getProviders.pipe(\n                  Effect.map((providers) => ({\n                    modelSelection: ServerSettings.resolveSourceControlWriterModelSelection(\n                      settings,\n                      providers,\n                    ),\n                    style: settings.sourceControlWritingStyle,\n                  })),\n                ),\n          ),\n          Effect.mapError(\n            (cause) =>\n              new GitManagerError({\n                operation: \"runStackedAction\",\n                cwd: input.cwd,\n                detail: \"Failed to get server settings.\",\n                cause,\n              }),\n          ),\n        );\n\n        if (input.featureBranch) {\n          yield* Ref.set(currentPhase, Option.some(\"branch\"));\n          yield* progress.emit({\n            kind: \"phase_started\",\n            phase: \"branch\",\n            label: \"Preparing feature branch...\",\n          });\n          const result = yield* runFeatureBranchStep(\n            textGenerationSettings,\n            input.cwd,\n            initialStatus.branch,\n            input.commitMessage,\n            input.filePaths,\n          );\n          branchStep = result.branchStep;\n          commitMessageForStep = result.resolvedCommitMessage;\n          preResolvedCommitSuggestion = result.resolvedCommitSuggestion;\n        } else {\n          branchStep = { status: \"skipped_not_requested\" as const };\n        }\n\n        const currentBranch = branchStep.name ?? initialStatus.branch;\n        const commitAction = isCommitAction(input.action) ? input.action : null;\n        const changeRequestTerms = wantsPr\n          ? yield* sourceControlProvider(input.cwd).pipe(\n              Effect.map((provider) => getChangeRequestTerminologyForKind(provider.kind)),\n              Effect.orElseSucceed(() => getChangeRequestTerminologyForKind(\"unknown\")),\n            )\n          : null;\n\n        const commit = commitAction\n          ? yield* Ref.set(currentPhase, Option.some(\"commit\")).pipe(\n              Effect.flatMap(() =>\n                runCommitStep(\n                  textGenerationSettings,\n                  input.cwd,\n                  commitAction,\n                  currentBranch,\n                  commitMessageForStep,\n                  preResolvedCommitSuggestion,\n                  input.filePaths,\n                  options?.progressReporter,\n                  progress.actionId,\n                ),\n              ),\n            )\n          : { status: \"skipped_not_requested\" as const };\n\n        const push = wantsPush\n          ? yield* progress\n              .emit({\n                kind: \"phase_started\",\n                phase: \"push\",\n                label: \"Pushing...\",\n              })\n              .pipe(\n                Effect.tap(() => Ref.set(currentPhase, Option.some(\"push\"))),\n                Effect.flatMap(() => gitCore.pushCurrentBranch(input.cwd, currentBranch)),\n              )\n          : { status: \"skipped_not_requested\" as const };\n\n        const pr = wantsPr\n          ? yield* progress\n              .emit({\n                kind: \"phase_started\",\n                phase: \"pr\",\n                label: `Preparing ${changeRequestTerms?.shortLabel ?? \"PR\"}...`,\n              })\n              .pipe(\n                Effect.tap(() => Ref.set(currentPhase, Option.some(\"pr\"))),\n                Effect.flatMap(() =>\n                  runPrStep(textGenerationSettings, input.cwd, currentBranch, progress.emit),\n                ),\n              )\n          : { status: \"skipped_not_requested\" as const };\n\n        const toast = yield* buildCompletionToast(input.cwd, {\n          action: input.action,\n          branch: branchStep,\n          commit,\n          push,\n          pr,\n        });\n\n        const result = {\n          action: input.action,\n          branch: branchStep,\n          commit,\n          push,\n          pr,\n          toast,\n        };\n        yield* progress.emit({\n          kind: \"action_finished\",\n          result,\n        });\n        return result;\n      });\n\n      return yield* runAction().pipe(\n        Effect.ensuring(invalidateStatus(input.cwd)),\n        Effect.tapError((error) =>\n          Effect.flatMap(Ref.get(currentPhase), (phase) =>\n            progress.emit({\n              kind: \"action_failed\",\n              phase: Option.getOrNull(phase),\n              message: error.message,\n            }),\n          ),\n        ),\n      );\n    },\n  );\n\n  return GitManager.of({\n    localStatus,\n    remoteStatus,\n    status,\n    invalidateLocalStatus,\n    invalidateRemoteStatus,\n    invalidateStatus,\n    resolvePullRequest,\n    preparePullRequestThread,\n    runStackedAction,\n  });\n});\n\nexport const layer = Layer.effect(GitManager, make);\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport {\n  GitManagerError,\n  GitCommandError,\n  type VcsSwitchRefInput,\n  type VcsSwitchRefResult,\n  type VcsCreateRefInput,\n  type VcsCreateRefResult,\n  type VcsCreateWorktreeInput,\n  type VcsCreateWorktreeResult,\n  type VcsListRefsInput,\n  type VcsListRefsResult,\n  type GitManagerServiceError,\n  type GitPreparePullRequestThreadInput,\n  type GitPreparePullRequestThreadResult,\n  type GitPullRequestRefInput,\n  type VcsPullResult,\n  type VcsRemoveWorktreeInput,\n  type GitResolvePullRequestResult,\n  type GitRunStackedActionInput,\n  type GitRunStackedActionResult,\n  type VcsStatusInput,\n  type VcsStatusLocalResult,\n  type VcsStatusRemoteResult,\n  type VcsStatusResult,\n} from \"@t3tools/contracts\";\n\nimport * as GitManager from \"./GitManager.ts\";\nimport * as GitVcsDriver from \"../vcs/GitVcsDriver.ts\";\nimport * as VcsDriverRegistry from \"../vcs/VcsDriverRegistry.ts\";\n\nexport class GitWorkflowService extends Context.Service<\n  GitWorkflowService,\n  {\n    readonly status: (\n      input: VcsStatusInput,\n    ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;\n    readonly localStatus: (\n      input: VcsStatusInput,\n    ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;\n    readonly remoteStatus: (\n      input: VcsStatusInput,\n      options?: GitVcsDriver.GitRemoteStatusOptions,\n    ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;\n    readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;\n    readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;\n    readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;\n    readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;\n    readonly runStackedAction: (\n      input: GitRunStackedActionInput,\n      options?: GitManager.GitRunStackedActionOptions,\n    ) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;\n    readonly resolvePullRequest: (\n      input: GitPullRequestRefInput,\n    ) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;\n    readonly preparePullRequestThread: (\n      input: GitPreparePullRequestThreadInput,\n    ) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;\n    readonly listRefs: (\n      input: VcsListRefsInput,\n    ) => Effect.Effect<VcsListRefsResult, GitCommandError>;\n    readonly createWorktree: (\n      input: VcsCreateWorktreeInput,\n    ) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;\n    readonly fetchRemote: (input: {\n      readonly cwd: string;\n      readonly remoteName: string;\n    }) => Effect.Effect<void, GitCommandError>;\n    readonly remoteExists: (input: {\n      readonly cwd: string;\n      readonly remoteName: string;\n    }) => Effect.Effect<boolean, GitCommandError>;\n    readonly resolveRemoteTrackingCommit: (input: {\n      readonly cwd: string;\n      readonly refName: string;\n      readonly fallbackRemoteName: string;\n    }) => Effect.Effect<\n      { readonly commitSha: string; readonly remoteRefName: string },\n      GitCommandError\n    >;\n    readonly removeWorktree: (\n      input: VcsRemoveWorktreeInput,\n    ) => Effect.Effect<void, GitCommandError>;\n    readonly createRef: (\n      input: VcsCreateRefInput,\n    ) => Effect.Effect<VcsCreateRefResult, GitCommandError>;\n    readonly switchRef: (\n      input: VcsSwitchRefInput,\n    ) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;\n    readonly renameBranch: (input: {\n      readonly cwd: string;\n      readonly oldBranch: string;\n      readonly newBranch: string;\n    }) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;\n  }\n>()(\"t3/git/GitWorkflowService\") {}\n\nfunction nonRepositoryLocalStatus(): VcsStatusLocalResult {\n  return {\n    isRepo: false,\n    hasPrimaryRemote: false,\n    isDefaultRef: false,\n    refName: null,\n    hasWorkingTreeChanges: false,\n    workingTree: {\n      files: [],\n      insertions: 0,\n      deletions: 0,\n    },\n  };\n}\n\nfunction nonRepositoryStatus(): VcsStatusResult {\n  return {\n    ...nonRepositoryLocalStatus(),\n    hasUpstream: false,\n    aheadCount: 0,\n    behindCount: 0,\n    aheadOfDefaultCount: 0,\n    pr: null,\n  };\n}\n\nfunction nonRepositoryListRefs(): VcsListRefsResult {\n  return {\n    refs: [],\n    isRepo: false,\n    hasPrimaryRemote: false,\n    nextCursor: null,\n    totalCount: 0,\n  };\n}\n\nexport const make = Effect.gen(function* () {\n  const registry = yield* VcsDriverRegistry.VcsDriverRegistry;\n  const git = yield* GitVcsDriver.GitVcsDriver;\n  const gitManager = yield* GitManager.GitManager;\n\n  const ensureGit = Effect.fn(\"GitWorkflowService.ensureGit\")(function* (\n    operation: string,\n    cwd: string,\n  ) {\n    const handle = yield* registry.resolve({ cwd }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new GitManagerError({\n            operation,\n            cwd,\n            detail: \"Failed to resolve the VCS driver for this Git workflow.\",\n            cause,\n          }),\n      ),\n    );\n    if (handle.kind !== \"git\") {\n      return yield* new GitManagerError({\n        operation,\n        cwd,\n        detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,\n      });\n    }\n  });\n\n  const ensureGitCommand = Effect.fn(\"GitWorkflowService.ensureGitCommand\")(function* (\n    operation: string,\n    cwd: string,\n  ) {\n    const handle = yield* registry.resolve({ cwd }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new GitCommandError({\n            operation,\n            command: \"vcs-route\",\n            cwd,\n            detail: \"Failed to resolve the VCS driver for this Git command.\",\n            cause,\n          }),\n      ),\n    );\n    if (handle.kind !== \"git\") {\n      return yield* new GitCommandError({\n        operation,\n        command: \"vcs-route\",\n        cwd,\n        detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,\n      });\n    }\n  });\n\n  const detectGitRepositoryForStatus = Effect.fn(\"GitWorkflowService.detectGitRepositoryForStatus\")(\n    function* (operation: string, cwd: string) {\n      const handle = yield* registry.detect({ cwd }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new GitManagerError({\n              operation,\n              cwd,\n              detail: \"Failed to detect a VCS repository for this Git workflow.\",\n              cause,\n            }),\n        ),\n      );\n      if (!handle) {\n        return false;\n      }\n      if (handle.kind !== \"git\") {\n        return yield* new GitManagerError({\n          operation,\n          cwd,\n          detail: `The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}. (${cwd})`,\n        });\n      }\n      return true;\n    },\n  );\n\n  const detectGitRepositoryForCommand = Effect.fn(\n    \"GitWorkflowService.detectGitRepositoryForCommand\",\n  )(function* (operation: string, cwd: string) {\n    const handle = yield* registry.detect({ cwd }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new GitCommandError({\n            operation,\n            command: \"vcs-route\",\n            cwd,\n            detail: \"Failed to detect a VCS repository for this Git command.\",\n            cause,\n          }),\n      ),\n    );\n    if (!handle) {\n      return false;\n    }\n    if (handle.kind !== \"git\") {\n      return yield* new GitCommandError({\n        operation,\n        command: \"vcs-route\",\n        cwd,\n        detail: `The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,\n      });\n    }\n    return true;\n  });\n\n  const routeGitManager =\n    <Input extends { readonly cwd: string }, Output>(\n      operation: string,\n      run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,\n    ) =>\n    (input: Input) =>\n      ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));\n\n  return GitWorkflowService.of({\n    status: (input) =>\n      detectGitRepositoryForStatus(\"GitWorkflowService.status\", input.cwd).pipe(\n        Effect.flatMap((isGitRepository) =>\n          isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),\n        ),\n      ),\n    localStatus: (input) =>\n      detectGitRepositoryForStatus(\"GitWorkflowService.localStatus\", input.cwd).pipe(\n        Effect.flatMap((isGitRepository) =>\n          isGitRepository\n            ? gitManager.localStatus(input)\n            : Effect.succeed(nonRepositoryLocalStatus()),\n        ),\n      ),\n    remoteStatus: (input, options) =>\n      detectGitRepositoryForStatus(\"GitWorkflowService.remoteStatus\", input.cwd).pipe(\n        Effect.flatMap((isGitRepository) =>\n          isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),\n        ),\n      ),\n    invalidateLocalStatus: gitManager.invalidateLocalStatus,\n    invalidateRemoteStatus: gitManager.invalidateRemoteStatus,\n    invalidateStatus: gitManager.invalidateStatus,\n    pullCurrentBranch: (cwd) =>\n      ensureGitCommand(\"GitWorkflowService.pullCurrentBranch\", cwd).pipe(\n        Effect.andThen(git.pullCurrentBranch(cwd)),\n      ),\n    runStackedAction: (input, options) =>\n      ensureGit(\"GitWorkflowService.runStackedAction\", input.cwd).pipe(\n        Effect.andThen(gitManager.runStackedAction(input, options)),\n      ),\n    resolvePullRequest: routeGitManager(\n      \"GitWorkflowService.resolvePullRequest\",\n      gitManager.resolvePullRequest,\n    ),\n    preparePullRequestThread: routeGitManager(\n      \"GitWorkflowService.preparePullRequestThread\",\n      gitManager.preparePullRequestThread,\n    ),\n    listRefs: (input) =>\n      detectGitRepositoryForCommand(\"GitWorkflowService.listRefs\", input.cwd).pipe(\n        Effect.flatMap((isGitRepository) =>\n          isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),\n        ),\n      ),\n    createWorktree: (input) =>\n      ensureGitCommand(\"GitWorkflowService.createWorktree\", input.cwd).pipe(\n        Effect.andThen(git.createWorktree(input)),\n      ),\n    fetchRemote: (input) =>\n      ensureGitCommand(\"GitWorkflowService.fetchRemote\", input.cwd).pipe(\n        Effect.andThen(git.fetchRemote(input)),\n      ),\n    remoteExists: (input) =>\n      ensureGitCommand(\"GitWorkflowService.remoteExists\", input.cwd).pipe(\n        Effect.andThen(git.remoteExists(input)),\n      ),\n    resolveRemoteTrackingCommit: (input) =>\n      ensureGitCommand(\"GitWorkflowService.resolveRemoteTrackingCommit\", input.cwd).pipe(\n        Effect.andThen(git.resolveRemoteTrackingCommit(input)),\n      ),\n    removeWorktree: (input) =>\n      ensureGitCommand(\"GitWorkflowService.removeWorktree\", input.cwd).pipe(\n        Effect.andThen(git.removeWorktree(input)),\n      ),\n    createRef: (input) =>\n      ensureGitCommand(\"GitWorkflowService.createRef\", input.cwd).pipe(\n        Effect.andThen(git.createRef(input)),\n      ),\n    switchRef: (input) =>\n      ensureGitCommand(\"GitWorkflowService.switchRef\", input.cwd).pipe(\n        Effect.andThen(Effect.scoped(git.switchRef(input))),\n      ),\n    renameBranch: (input) =>\n      ensureGit(\"GitWorkflowService.renameBranch\", input.cwd).pipe(\n        Effect.andThen(git.renameBranch(input)),\n      ),\n  });\n});\n\nexport const layer = Layer.effect(GitWorkflowService, make);\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\nimport type {\n  GitManagerServiceError,\n  VcsStatusInput,\n  VcsStatusLocalResult,\n  VcsStatusRemoteResult,\n  VcsStatusResult,\n  VcsStatusStreamEvent,\n} from \"@t3tools/contracts\";\nimport { mergeGitStatusParts } from \"@t3tools/shared/git\";\n\nimport * as BackgroundPolicy from \"../background/BackgroundPolicy.ts\";\nimport * as GitWorkflowService from \"../git/GitWorkflowService.ts\";\n\nconst DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);\nconst VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);\nconst VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);\nconst MAX_FAILURE_DIAGNOSTIC_VALUES = 8;\nconst MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;\n\nfunction boundedDiagnosticValue(value: string): string {\n  return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);\n}\n\nfunction diagnosticValueTag(value: unknown): string {\n  try {\n    if (\n      typeof value === \"object\" &&\n      value !== null &&\n      \"_tag\" in value &&\n      typeof value._tag === \"string\"\n    ) {\n      return boundedDiagnosticValue(value._tag);\n    }\n    if (value instanceof Error) {\n      return boundedDiagnosticValue(value.name);\n    }\n    return typeof value;\n  } catch {\n    return \"Uninspectable\";\n  }\n}\n\nfunction diagnosticFailureOperation(value: unknown): string | undefined {\n  try {\n    if (\n      typeof value === \"object\" &&\n      value !== null &&\n      \"operation\" in value &&\n      typeof value.operation === \"string\"\n    ) {\n      return boundedDiagnosticValue(value.operation);\n    }\n  } catch {\n    return undefined;\n  }\n  return undefined;\n}\n\nfunction addUniqueDiagnosticValue(values: Array<string>, value: string | undefined): void {\n  if (\n    value !== undefined &&\n    values.length < MAX_FAILURE_DIAGNOSTIC_VALUES &&\n    !values.includes(value)\n  ) {\n    values.push(value);\n  }\n}\n\nexport function remoteRefreshFailureDiagnostics(cause: Cause.Cause<unknown>) {\n  const failureTags: Array<string> = [];\n  const failureOperations: Array<string> = [];\n  const defectTags: Array<string> = [];\n  let failureCount = 0;\n  let defectCount = 0;\n  let interruptionCount = 0;\n\n  for (const reason of cause.reasons) {\n    if (Cause.isFailReason(reason)) {\n      failureCount += 1;\n      addUniqueDiagnosticValue(failureTags, diagnosticValueTag(reason.error));\n      addUniqueDiagnosticValue(failureOperations, diagnosticFailureOperation(reason.error));\n      continue;\n    }\n    if (Cause.isDieReason(reason)) {\n      defectCount += 1;\n      addUniqueDiagnosticValue(defectTags, diagnosticValueTag(reason.defect));\n      continue;\n    }\n    interruptionCount += 1;\n  }\n\n  return {\n    reasonCount: cause.reasons.length,\n    failureCount,\n    failureTags,\n    failureOperations,\n    defectCount,\n    defectTags,\n    interruptionCount,\n  };\n}\n\ninterface VcsStatusChange {\n  readonly cwd: string;\n  readonly event: VcsStatusStreamEvent;\n}\n\ninterface CachedValue<T> {\n  readonly fingerprint: string;\n  readonly value: T;\n}\n\ninterface CachedVcsStatus {\n  readonly local: CachedValue<VcsStatusLocalResult> | null;\n  readonly remote: CachedValue<VcsStatusRemoteResult | null> | null;\n}\n\ninterface ActiveRemotePoller {\n  readonly fiber: Fiber.Fiber<void, never>;\n  readonly subscriberCount: number;\n  readonly demandCwds: Ref.Ref<ReadonlyMap<string, number>>;\n}\n\ninterface StreamStatusOptions {\n  readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;\n}\n\nexport function remoteRefreshFailureDelay(\n  consecutiveFailures: number,\n  configuredInterval: Duration.Duration,\n) {\n  const exponent = Math.max(0, consecutiveFailures - 1);\n  const backoffMs =\n    Duration.toMillis(VCS_STATUS_REFRESH_FAILURE_BASE_DELAY) * Math.pow(2, exponent);\n  const cappedBackoff = Duration.min(\n    Duration.millis(backoffMs),\n    VCS_STATUS_REFRESH_FAILURE_MAX_DELAY,\n  );\n  return Duration.max(configuredInterval, cappedBackoff);\n}\n\nexport class VcsStatusBroadcaster extends Context.Service<\n  VcsStatusBroadcaster,\n  {\n    readonly getStatus: (\n      input: VcsStatusInput,\n    ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;\n    readonly refreshLocalStatus: (\n      cwd: string,\n    ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;\n    readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;\n    readonly streamStatus: (\n      input: VcsStatusInput,\n      options?: StreamStatusOptions,\n    ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;\n  }\n>()(\"t3/vcs/VcsStatusBroadcaster\") {}\n\nfunction fingerprintStatusPart(status: unknown): string {\n  return JSON.stringify(status);\n}\n\nconst normalizeCwd = (cwd: string) =>\n  Effect.service(FileSystem.FileSystem).pipe(\n    Effect.flatMap((fs) => fs.realPath(cwd)),\n    Effect.orElseSucceed(() => cwd),\n  );\n\nexport const make = Effect.gen(function* () {\n  const workflow = yield* GitWorkflowService.GitWorkflowService;\n  const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;\n  const fs = yield* FileSystem.FileSystem;\n  const changesPubSub = yield* Effect.acquireRelease(\n    PubSub.unbounded<VcsStatusChange>(),\n    (pubsub) => PubSub.shutdown(pubsub),\n  );\n  const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>\n    Scope.close(scope, Exit.void),\n  );\n  const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());\n  const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());\n\n  const getCachedStatus = Effect.fn(\"VcsStatusBroadcaster.getCachedStatus\")(function* (\n    cwd: string,\n  ) {\n    return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));\n  });\n\n  const updateCachedLocalStatus = Effect.fn(\"VcsStatusBroadcaster.updateCachedLocalStatus\")(\n    function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {\n      const nextLocal = {\n        fingerprint: fingerprintStatusPart(local),\n        value: local,\n      } satisfies CachedValue<VcsStatusLocalResult>;\n      const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {\n        const previous = cache.get(cwd) ?? { local: null, remote: null };\n        const nextCache = new Map(cache);\n        nextCache.set(cwd, {\n          ...previous,\n          local: nextLocal,\n        });\n        return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;\n      });\n\n      if (options?.publish && shouldPublish) {\n        yield* PubSub.publish(changesPubSub, {\n          cwd,\n          event: {\n            _tag: \"localUpdated\",\n            local,\n          },\n        });\n      }\n\n      return local;\n    },\n  );\n\n  const updateCachedRemoteStatus = Effect.fn(\"VcsStatusBroadcaster.updateCachedRemoteStatus\")(\n    function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {\n      const nextRemote = {\n        fingerprint: fingerprintStatusPart(remote),\n        value: remote,\n      } satisfies CachedValue<VcsStatusRemoteResult | null>;\n      const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {\n        const previous = cache.get(cwd) ?? { local: null, remote: null };\n        const nextCache = new Map(cache);\n        nextCache.set(cwd, {\n          ...previous,\n          remote: nextRemote,\n        });\n        return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;\n      });\n\n      if (options?.publish && shouldPublish) {\n        yield* PubSub.publish(changesPubSub, {\n          cwd,\n          event: {\n            _tag: \"remoteUpdated\",\n            remote,\n          },\n        });\n      }\n\n      return remote;\n    },\n  );\n\n  const updateCachedStatus = Effect.fn(\"VcsStatusBroadcaster.updateCachedStatus\")(function* (\n    cwd: string,\n    local: VcsStatusLocalResult,\n    remote: VcsStatusRemoteResult | null,\n    options?: { publish?: boolean },\n  ) {\n    const nextLocal = {\n      fingerprint: fingerprintStatusPart(local),\n      value: local,\n    } satisfies CachedValue<VcsStatusLocalResult>;\n    const nextRemote = {\n      fingerprint: fingerprintStatusPart(remote),\n      value: remote,\n    } satisfies CachedValue<VcsStatusRemoteResult | null>;\n    const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {\n      const previous = cache.get(cwd) ?? { local: null, remote: null };\n      const nextCache = new Map(cache);\n      nextCache.set(cwd, {\n        local: nextLocal,\n        remote: nextRemote,\n      });\n      return [\n        previous.local?.fingerprint !== nextLocal.fingerprint ||\n          previous.remote?.fingerprint !== nextRemote.fingerprint,\n        nextCache,\n      ] as const;\n    });\n\n    if (options?.publish && shouldPublish) {\n      yield* PubSub.publish(changesPubSub, {\n        cwd,\n        event: {\n          _tag: \"snapshot\",\n          local,\n          remote,\n        },\n      });\n    }\n\n    return mergeGitStatusParts(local, remote);\n  });\n\n  const loadLocalStatus = Effect.fn(\"VcsStatusBroadcaster.loadLocalStatus\")(function* (\n    cwd: string,\n  ) {\n    const local = yield* workflow.localStatus({ cwd });\n    return yield* updateCachedLocalStatus(cwd, local);\n  });\n\n  const getOrLoadLocalStatus = Effect.fn(\"VcsStatusBroadcaster.getOrLoadLocalStatus\")(function* (\n    cwd: string,\n  ) {\n    const cached = yield* getCachedStatus(cwd);\n    if (cached?.local) {\n      return cached.local.value;\n    }\n    return yield* loadLocalStatus(cwd);\n  });\n\n  const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);\n\n  const getStatus: VcsStatusBroadcaster[\"Service\"][\"getStatus\"] = Effect.fn(\n    \"VcsStatusBroadcaster.getStatus\",\n  )(function* (input) {\n    const cwd = yield* withFileSystem(normalizeCwd(input.cwd));\n    const cached = yield* getCachedStatus(cwd);\n    if (cached?.local && cached.remote) {\n      return mergeGitStatusParts(cached.local.value, cached.remote.value);\n    }\n    const [local, remote] = yield* Effect.all(\n      [\n        cached?.local ? Effect.succeed(cached.local.value) : workflow.localStatus({ cwd }),\n        cached?.remote ? Effect.succeed(cached.remote.value) : workflow.remoteStatus({ cwd }),\n      ],\n      { concurrency: \"unbounded\" },\n    );\n    return yield* updateCachedStatus(cwd, local, remote);\n  });\n\n  const refreshLocalStatusCore = Effect.fn(\"VcsStatusBroadcaster.refreshLocalStatusCore\")(\n    function* (cwd: string) {\n      yield* workflow.invalidateLocalStatus(cwd);\n      const local = yield* workflow.localStatus({ cwd });\n      return yield* updateCachedLocalStatus(cwd, local, { publish: true });\n    },\n  );\n\n  const refreshLocalStatus: VcsStatusBroadcaster[\"Service\"][\"refreshLocalStatus\"] = Effect.fn(\n    \"VcsStatusBroadcaster.refreshLocalStatus\",\n  )(function* (rawCwd) {\n    const cwd = yield* withFileSystem(normalizeCwd(rawCwd));\n    return yield* refreshLocalStatusCore(cwd);\n  });\n\n  const refreshRemoteStatus = Effect.fn(\"VcsStatusBroadcaster.refreshRemoteStatus\")(function* (\n    cwd: string,\n    options?: { readonly refreshUpstream?: boolean },\n  ) {\n    if (options?.refreshUpstream !== false) {\n      yield* workflow.invalidateRemoteStatus(cwd);\n    }\n    const remote = yield* workflow.remoteStatus({ cwd }, options);\n    return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });\n  });\n\n  const refreshStatus: VcsStatusBroadcaster[\"Service\"][\"refreshStatus\"] = Effect.fn(\n    \"VcsStatusBroadcaster.refreshStatus\",\n  )(function* (rawCwd) {\n    const cwd = yield* withFileSystem(normalizeCwd(rawCwd));\n    // invalidateStatus (not the two partial invalidations) so an explicit\n    // refresh also bypasses GitManager's slow PR-lookup cache.\n    yield* workflow.invalidateStatus(cwd);\n    const [local, remote] = yield* Effect.all(\n      [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],\n      { concurrency: \"unbounded\" },\n    );\n    return yield* updateCachedStatus(cwd, local, remote, { publish: true });\n  });\n\n  const makeRemoteRefreshLoop = (\n    cwd: string,\n    demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,\n    automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,\n    refreshImmediately: boolean,\n  ) => {\n    return Effect.gen(function* () {\n      const consecutiveFailuresRef = yield* Ref.make(0);\n      const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);\n      const refreshRemoteStatusIfEnabled = Effect.gen(function* () {\n        const configuredInterval = yield* automaticRemoteRefreshInterval;\n        const activeInterval = Duration.isZero(configuredInterval)\n          ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL\n          : configuredInterval;\n        const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);\n        if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {\n          return activeInterval;\n        }\n\n        const demandCwds = yield* Ref.get(demandCwdsRef);\n        const shouldRun =\n          needsInitialRefresh ||\n          (yield* Effect.all(\n            [...demandCwds.keys()].map((demandCwd) =>\n              backgroundPolicy.shouldRunScopeWork({\n                type: \"vcs-status\",\n                cwd: demandCwd,\n              }),\n            ),\n            { concurrency: \"unbounded\" },\n          )).some(Boolean);\n        if (!shouldRun) {\n          return activeInterval;\n        }\n\n        const exit = yield* refreshRemoteStatus(cwd, {\n          refreshUpstream: !Duration.isZero(configuredInterval),\n        }).pipe(Effect.exit);\n        if (Exit.isSuccess(exit)) {\n          yield* Ref.set(needsInitialRefreshRef, false);\n          yield* Ref.set(consecutiveFailuresRef, 0);\n          return activeInterval;\n        }\n\n        const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);\n        if (interruptionReasons.length > 0) {\n          return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));\n        }\n\n        const consecutiveFailures = yield* Ref.updateAndGet(\n          consecutiveFailuresRef,\n          (count) => count + 1,\n        );\n        const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);\n        yield* Effect.logWarning(\"VCS remote status refresh failed\", {\n          cwdLength: cwd.length,\n          ...remoteRefreshFailureDiagnostics(exit.cause),\n          consecutiveFailures,\n          nextDelayMs: Duration.toMillis(nextDelay),\n        });\n        return nextDelay;\n      });\n\n      if (!refreshImmediately) {\n        const configuredInterval = yield* automaticRemoteRefreshInterval;\n        yield* Effect.sleep(\n          Duration.isZero(configuredInterval)\n            ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL\n            : configuredInterval,\n        );\n      }\n\n      return yield* refreshRemoteStatusIfEnabled.pipe(\n        Effect.repeat(\n          Schedule.identity<Duration.Duration>().pipe(\n            Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),\n          ),\n        ),\n        Effect.asVoid,\n      );\n    });\n  };\n\n  const retainRemotePoller = Effect.fn(\"VcsStatusBroadcaster.retainRemotePoller\")(function* (\n    cwd: string,\n    demandCwd: string,\n    automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,\n    refreshImmediately: boolean,\n  ) {\n    yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {\n      const existing = activePollers.get(cwd);\n      if (existing) {\n        return Ref.update(existing.demandCwds, (demandCwds) => {\n          const next = new Map(demandCwds);\n          next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);\n          return next;\n        }).pipe(\n          Effect.map(() => {\n            const nextPollers = new Map(activePollers);\n            nextPollers.set(cwd, {\n              ...existing,\n              subscriberCount: existing.subscriberCount + 1,\n            });\n            return [undefined, nextPollers] as const;\n          }),\n        );\n      }\n\n      return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(\n        Effect.flatMap((demandCwds) =>\n          makeRemoteRefreshLoop(\n            cwd,\n            demandCwds,\n            automaticRemoteRefreshInterval,\n            refreshImmediately,\n          ).pipe(\n            Effect.forkIn(broadcasterScope),\n            Effect.map((fiber) => {\n              const nextPollers = new Map(activePollers);\n              nextPollers.set(cwd, {\n                fiber,\n                subscriberCount: 1,\n                demandCwds,\n              });\n              return [undefined, nextPollers] as const;\n            }),\n          ),\n        ),\n      );\n    });\n  });\n\n  const releaseRemotePoller = Effect.fn(\"VcsStatusBroadcaster.releaseRemotePoller\")(function* (\n    cwd: string,\n    demandCwd: string,\n  ) {\n    const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {\n      const existing = activePollers.get(cwd);\n      if (!existing) {\n        return Effect.succeed([null, activePollers] as const);\n      }\n\n      if (existing.subscriberCount > 1) {\n        return Ref.update(existing.demandCwds, (demandCwds) => {\n          const nextDemandCwds = new Map(demandCwds);\n          const count = nextDemandCwds.get(demandCwd) ?? 0;\n          if (count <= 1) {\n            nextDemandCwds.delete(demandCwd);\n          } else {\n            nextDemandCwds.set(demandCwd, count - 1);\n          }\n          return nextDemandCwds;\n        }).pipe(\n          Effect.as([\n            null,\n            new Map(activePollers).set(cwd, {\n              ...existing,\n              subscriberCount: existing.subscriberCount - 1,\n            }),\n          ] as const),\n        );\n      }\n\n      return Effect.succeed([\n        existing.fiber,\n        new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),\n      ] as const);\n    });\n\n    if (pollerToInterrupt) {\n      yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);\n    }\n  });\n\n  const streamStatus: VcsStatusBroadcaster[\"Service\"][\"streamStatus\"] = (input, options) =>\n    Stream.unwrap(\n      Effect.gen(function* () {\n        const cwd = yield* withFileSystem(normalizeCwd(input.cwd));\n        const subscription = yield* PubSub.subscribe(changesPubSub);\n        const initialLocal = yield* getOrLoadLocalStatus(cwd);\n        const cachedStatus = yield* getCachedStatus(cwd);\n        const initialRemote = cachedStatus?.remote?.value ?? null;\n        yield* retainRemotePoller(\n          cwd,\n          input.cwd,\n          options?.automaticRemoteRefreshInterval ??\n            Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),\n          cachedStatus?.remote === null || cachedStatus?.remote === undefined,\n        );\n\n        const release = releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);\n\n        return Stream.concat(\n          Stream.make({\n            _tag: \"snapshot\" as const,\n            local: initialLocal,\n            remote: initialRemote,\n          }),\n          Stream.fromSubscription(subscription).pipe(\n            Stream.filter((event) => event.cwd === cwd),\n            Stream.map((event) => event.event),\n          ),\n        ).pipe(Stream.ensuring(release));\n      }),\n    );\n\n  return VcsStatusBroadcaster.of({\n    getStatus,\n    refreshLocalStatus,\n    refreshStatus,\n    streamStatus,\n  });\n});\n\nexport const layer = Layer.effect(VcsStatusBroadcaster, make);\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport {\n  type VcsDriverKind,\n  type VcsError,\n  type VcsInitInput,\n  VcsUnsupportedOperationError,\n} from \"@t3tools/contracts\";\nimport * as VcsDriverRegistry from \"./VcsDriverRegistry.ts\";\n\nexport class VcsProvisioningService extends Context.Service<\n  VcsProvisioningService,\n  {\n    readonly initRepository: (input: VcsInitInput) => Effect.Effect<void, VcsError>;\n  }\n>()(\"t3/vcs/VcsProvisioningService\") {}\n\nfunction resolveRequestedKind(\n  kind: VcsDriverKind | undefined,\n): Effect.Effect<VcsDriverKind, VcsUnsupportedOperationError> {\n  if (kind === undefined) {\n    return Effect.succeed(\"git\");\n  }\n  if (kind === \"unknown\") {\n    return Effect.fail(\n      new VcsUnsupportedOperationError({\n        operation: \"VcsProvisioningService.resolveRequestedKind\",\n        kind,\n        detail: \"A concrete VCS driver kind is required for repository provisioning.\",\n      }),\n    );\n  }\n  return Effect.succeed(kind);\n}\n\nexport const make = Effect.gen(function* () {\n  const registry = yield* VcsDriverRegistry.VcsDriverRegistry;\n\n  const initRepository: VcsProvisioningService[\"Service\"][\"initRepository\"] = Effect.fn(\n    \"VcsProvisioningService.initRepository\",\n  )(function* (input) {\n    const kind = yield* resolveRequestedKind(input.kind);\n    const driver = yield* registry.get(kind);\n    return yield* driver.initRepository(input);\n  });\n\n  return VcsProvisioningService.of({\n    initRepository,\n  });\n});\n\nexport const layer = Layer.effect(VcsProvisioningService, make);\n","import * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\n\nimport {\n  VcsRepositoryDetectionError,\n  VcsUnsupportedOperationError,\n  type ReviewDiffFileContentsInput,\n  type ReviewDiffFileContentsResult,\n  type ReviewDiffPreviewError,\n  type ReviewDiffPreviewInput,\n  type ReviewDiffPreviewResult,\n} from \"@t3tools/contracts\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport * as GitVcsDriver from \"../vcs/GitVcsDriver.ts\";\nimport * as VcsDriverRegistry from \"../vcs/VcsDriverRegistry.ts\";\n\nexport class ReviewService extends Context.Service<\n  ReviewService,\n  {\n    readonly getDiffPreview: (\n      input: ReviewDiffPreviewInput,\n    ) => Effect.Effect<ReviewDiffPreviewResult, ReviewDiffPreviewError>;\n    readonly getDiffFileContents: (\n      input: ReviewDiffFileContentsInput,\n    ) => Effect.Effect<ReviewDiffFileContentsResult, ReviewDiffPreviewError>;\n  }\n>()(\"t3/review/ReviewService\") {}\n\nexport const make = Effect.gen(function* () {\n  const config = yield* ServerConfig.ServerConfig;\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;\n  const git = yield* GitVcsDriver.GitVcsDriver;\n\n  const canonicalizePath = (value: string) => {\n    const resolvedPath = path.resolve(value);\n    return fileSystem.realPath(resolvedPath).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          cause.reason._tag === \"NotFound\"\n            ? Effect.succeed(resolvedPath)\n            : Effect.fail(\n                new VcsRepositoryDetectionError({\n                  operation: \"ReviewService.assertWorkspaceBoundCwd.canonicalizePath\",\n                  cwd: resolvedPath,\n                  detail: \"Failed to resolve a path while validating the review workspace.\",\n                  cause,\n                }),\n              ),\n      }),\n    );\n  };\n\n  const isWithinRoot = (candidate: string, root: string) => {\n    const relative = path.relative(root, candidate);\n    return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n  };\n\n  const assertWorkspaceBoundCwd = Effect.fn(\"ReviewService.assertWorkspaceBoundCwd\")(function* (\n    operation: \"ReviewService.getDiffPreview\" | \"ReviewService.getDiffFileContents\",\n    cwd: string,\n  ) {\n    const [candidate, workspaceRoot, worktreesRoot] = yield* Effect.all([\n      canonicalizePath(cwd),\n      canonicalizePath(config.cwd),\n      canonicalizePath(config.worktreesDir),\n    ]);\n\n    if (isWithinRoot(candidate, workspaceRoot) || isWithinRoot(candidate, worktreesRoot)) {\n      return;\n    }\n\n    return yield* new VcsRepositoryDetectionError({\n      operation,\n      cwd,\n      detail:\n        operation === \"ReviewService.getDiffPreview\"\n          ? \"Review diff preview cwd must stay within the configured workspace root.\"\n          : \"Review diff file contents cwd must stay within the configured workspace root.\",\n    });\n  });\n\n  const getDiffPreview: ReviewService[\"Service\"][\"getDiffPreview\"] = Effect.fn(\n    \"ReviewService.getDiffPreview\",\n  )(function* (input) {\n    yield* assertWorkspaceBoundCwd(\"ReviewService.getDiffPreview\", input.cwd);\n\n    const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: \"auto\" });\n    if (!handle) {\n      return {\n        cwd: input.cwd,\n        generatedAt: yield* DateTime.now,\n        sources: [],\n      };\n    }\n\n    const getDriverDiffPreview = handle.driver.getDiffPreview;\n    if (!getDriverDiffPreview) {\n      if (handle.kind === \"git\") {\n        return yield* git.getReviewDiffPreview(input);\n      }\n      return yield* new VcsUnsupportedOperationError({\n        operation: \"ReviewService.getDiffPreview\",\n        kind: handle.kind,\n        detail: `The ${handle.kind} VCS driver does not support review diff previews.`,\n      });\n    }\n\n    return yield* getDriverDiffPreview(input);\n  });\n\n  const getDiffFileContents: ReviewService[\"Service\"][\"getDiffFileContents\"] = Effect.fn(\n    \"ReviewService.getDiffFileContents\",\n  )(function* (input) {\n    yield* assertWorkspaceBoundCwd(\"ReviewService.getDiffFileContents\", input.cwd);\n\n    const handle = yield* vcsRegistry.detect({ cwd: input.cwd, requestedKind: \"auto\" });\n    if (handle?.kind !== \"git\") {\n      return yield* new VcsUnsupportedOperationError({\n        operation: \"ReviewService.getDiffFileContents\",\n        kind: handle?.kind ?? \"unknown\",\n        detail: \"Unchanged diff expansion currently requires a Git repository.\",\n      });\n    }\n\n    return yield* git.getReviewDiffFileContents(input);\n  });\n\n  return ReviewService.of({\n    getDiffPreview,\n    getDiffFileContents,\n  });\n});\n\nexport const layer = Layer.effect(ReviewService, make);\n","import {\n  AuthAccessReadScope,\n  AuthOrchestrationOperateScope,\n  AuthOrchestrationReadScope,\n  AuthRelayReadScope,\n  AuthRelayWriteScope,\n  AuthReviewWriteScope,\n  AuthTerminalOperateScope,\n  ORCHESTRATION_WS_METHODS,\n  type AuthEnvironmentScope,\n  WS_METHODS,\n  WsRpcGroup,\n} from \"@t3tools/contracts\";\nimport type * as RpcGroup from \"effect/unstable/rpc/RpcGroup\";\n\ntype WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>[\"_tag\"];\n\n/**\n * Keep authorization coverage coupled to the RPC group itself. Adding an RPC to\n * `WsRpcGroup` without choosing a scope is a type error instead of a production\n * runtime failure.\n */\nexport const RPC_REQUIRED_SCOPES = {\n  [ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,\n  [ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.subscribeShell]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,\n  [ORCHESTRATION_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverProbe]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverRefreshProviders]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverUpdateProvider]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverUpdateServer]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverUpdateServerWithProgress]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverUpsertKeybinding]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverRemoveKeybinding]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverGetSettings]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverUpdateSettings]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverDiscoverSourceControl]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetTraceDiagnostics]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetProcessDiagnostics]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetProcessResourceHistory]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverGetUsageSummary]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,\n  [WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,\n  [WS_METHODS.serverGetBackgroundPolicy]: AuthOrchestrationReadScope,\n  [WS_METHODS.cloudGetRelayClientStatus]: AuthRelayReadScope,\n  [WS_METHODS.cloudInstallRelayClient]: AuthRelayWriteScope,\n  [WS_METHODS.sourceControlLookupRepository]: AuthOrchestrationReadScope,\n  [WS_METHODS.sourceControlCloneRepository]: AuthOrchestrationOperateScope,\n  [WS_METHODS.sourceControlPublishRepository]: AuthOrchestrationOperateScope,\n  [WS_METHODS.projectsListEntries]: AuthOrchestrationReadScope,\n  [WS_METHODS.projectsReadFile]: AuthOrchestrationReadScope,\n  [WS_METHODS.projectsSearchContents]: AuthOrchestrationReadScope,\n  [WS_METHODS.projectsSearchEntries]: AuthOrchestrationReadScope,\n  [WS_METHODS.projectsWriteFile]: AuthOrchestrationOperateScope,\n  [WS_METHODS.shellOpenInEditor]: AuthOrchestrationOperateScope,\n  [WS_METHODS.filesystemBrowse]: AuthOrchestrationReadScope,\n  [WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,\n  [WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,\n  [WS_METHODS.vcsPull]: AuthOrchestrationOperateScope,\n  [WS_METHODS.gitRunStackedAction]: AuthOrchestrationOperateScope,\n  [WS_METHODS.gitResolvePullRequest]: AuthOrchestrationOperateScope,\n  [WS_METHODS.gitPreparePullRequestThread]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsListRefs]: AuthOrchestrationReadScope,\n  [WS_METHODS.vcsCreateWorktree]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsRemoveWorktree]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsCreateRef]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsSwitchRef]: AuthOrchestrationOperateScope,\n  [WS_METHODS.vcsInit]: AuthOrchestrationOperateScope,\n  [WS_METHODS.reviewGetDiffPreview]: AuthReviewWriteScope,\n  [WS_METHODS.reviewGetDiffFileContents]: AuthReviewWriteScope,\n  [WS_METHODS.terminalOpen]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalAttach]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalWrite]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalResize]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalClear]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalRestart]: AuthTerminalOperateScope,\n  [WS_METHODS.terminalClose]: AuthTerminalOperateScope,\n  [WS_METHODS.subscribeTerminalEvents]: AuthTerminalOperateScope,\n  [WS_METHODS.subscribeTerminalMetadata]: AuthTerminalOperateScope,\n  [WS_METHODS.previewOpen]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewNavigate]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewResize]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewRefresh]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewClose]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewList]: AuthOrchestrationReadScope,\n  [WS_METHODS.previewReportStatus]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewAutomationConnect]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewAutomationRespond]: AuthOrchestrationOperateScope,\n  [WS_METHODS.previewAutomationFocusHost]: AuthOrchestrationOperateScope,\n  [WS_METHODS.subscribePreviewEvents]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeDiscoveredLocalServers]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeServerConfig]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeServerLifecycle]: AuthOrchestrationReadScope,\n  [WS_METHODS.subscribeAuthAccess]: AuthAccessReadScope,\n  [WS_METHODS.subscribeBackgroundPolicy]: AuthOrchestrationReadScope,\n} as const satisfies Readonly<Record<WsRpcMethod, AuthEnvironmentScope>>;\n\nexport function requiredScopeForRpcMethod(method: string): AuthEnvironmentScope {\n  if (!Object.hasOwn(RPC_REQUIRED_SCOPES, method)) {\n    throw new Error(`RPC method ${method} has no declared authorization scope.`);\n  }\n  const requiredScope = RPC_REQUIRED_SCOPES[method as WsRpcMethod];\n  if (requiredScope === undefined) {\n    throw new Error(`RPC method ${method} has no declared authorization scope.`);\n  }\n  return requiredScope;\n}\n","import type {\n  DesktopElectronProcessMetric,\n  DesktopHostTelemetrySnapshot,\n  ResourceMonitorProcessSample,\n  ResourceMonitorSnapshotEvent,\n  ResourceTelemetryAggregate,\n  ResourceTelemetryProcess,\n  ResourceTelemetryProcessCategory,\n} from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Option from \"effect/Option\";\n\nconst MAX_DELTA_INTERVAL_MS = 30_000;\nconst ELECTRON_IDENTITY_TOLERANCE_MS = 2_000;\n\nexport interface ProcessState {\n  readonly process: ResourceTelemetryProcess;\n  readonly sampledAtMs: number;\n}\n\nexport interface GroupCounters {\n  readonly cpuTimeMs: number;\n  readonly ioReadBytes: number;\n  readonly ioWriteBytes: number;\n  readonly processStarts: number;\n  readonly processExits: number;\n}\n\nexport interface TelemetryCounters {\n  readonly backend: GroupCounters;\n  readonly electron: GroupCounters;\n  readonly monitor: GroupCounters;\n  readonly allT3: GroupCounters;\n}\n\nexport interface ProcessDelta {\n  readonly identityKey: string;\n  readonly category: ResourceTelemetryProcessCategory;\n  readonly cpuTimeMs: number;\n  readonly ioReadBytes: number;\n  readonly ioWriteBytes: number;\n}\n\nexport interface MergeProcessesInput {\n  readonly serverPid: number;\n  readonly sidecarPid: Option.Option<number>;\n  readonly fallbackSampledAtMs: number;\n  readonly nativeSnapshot: Option.Option<ResourceMonitorSnapshotEvent>;\n  readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;\n  readonly electronRootPids?: ReadonlySet<number>;\n  readonly electronRootStartTimes?: ReadonlyMap<number, number>;\n  readonly previous: ReadonlyMap<string, ProcessState>;\n  readonly counters: TelemetryCounters;\n  readonly updatePrevious: boolean;\n}\n\nexport interface MergeProcessesResult {\n  readonly sampledAtMs: number;\n  readonly processes: ReadonlyArray<ResourceTelemetryProcess>;\n  readonly previous: ReadonlyMap<string, ProcessState>;\n  readonly counters: TelemetryCounters;\n  readonly groups: {\n    readonly backend: ResourceTelemetryAggregate;\n    readonly electron: ResourceTelemetryAggregate;\n    readonly monitor: ResourceTelemetryAggregate;\n    readonly allT3: ResourceTelemetryAggregate;\n  };\n  readonly deltas: ReadonlyArray<ProcessDelta>;\n}\n\nexport const emptyGroupCounters = (): GroupCounters => ({\n  cpuTimeMs: 0,\n  ioReadBytes: 0,\n  ioWriteBytes: 0,\n  processStarts: 0,\n  processExits: 0,\n});\n\nexport const emptyTelemetryCounters = (): TelemetryCounters => ({\n  backend: emptyGroupCounters(),\n  electron: emptyGroupCounters(),\n  monitor: emptyGroupCounters(),\n  allT3: emptyGroupCounters(),\n});\n\nexport function processIdentityKey(pid: number, startTimeMs: number): string {\n  return `${pid}:${startTimeMs}`;\n}\n\nfunction finiteNonNegative(value: number): number {\n  return Number.isFinite(value) ? Math.max(0, value) : 0;\n}\n\nfunction categoryGroup(\n  category: ResourceTelemetryProcessCategory,\n): \"backend\" | \"electron\" | \"monitor\" {\n  if (category === \"resource-monitor\") return \"monitor\";\n  if (category.startsWith(\"electron-\")) return \"electron\";\n  return \"backend\";\n}\n\nfunction electronCategory(metric: DesktopElectronProcessMetric): ResourceTelemetryProcessCategory {\n  switch (metric.type) {\n    case \"Browser\":\n      return \"electron-main\";\n    case \"Tab\":\n      return \"electron-renderer\";\n    case \"GPU\":\n      return \"electron-gpu\";\n    default:\n      return \"electron-utility\";\n  }\n}\n\nfunction inferredElectronCategory(\n  process: ResourceMonitorProcessSample,\n): ResourceTelemetryProcessCategory {\n  const command = process.command.toLowerCase();\n  if (command.includes(\"--type=renderer\")) return \"electron-renderer\";\n  if (command.includes(\"--type=gpu-process\")) return \"electron-gpu\";\n  return \"electron-utility\";\n}\n\nfunction matchElectronMetric(\n  process: ResourceMonitorProcessSample,\n  metricsByPid: ReadonlyMap<number, DesktopElectronProcessMetric>,\n): DesktopElectronProcessMetric | undefined {\n  const metric = metricsByPid.get(process.pid);\n  if (!metric) return undefined;\n  return Math.abs(metric.creationTimeMs - process.startTimeMs) <= ELECTRON_IDENTITY_TOLERANCE_MS\n    ? metric\n    : undefined;\n}\n\nfunction syntheticNativeSample(\n  metric: DesktopElectronProcessMetric,\n  sampledAtMs: number,\n  previous: ProcessState | undefined,\n): ResourceMonitorProcessSample {\n  const cpuTimeMs =\n    metric.cumulativeCpuSeconds !== undefined\n      ? Math.max(0, Math.round(metric.cumulativeCpuSeconds * 1_000))\n      : previous\n        ? previous.process.cpuTimeMs +\n          Math.max(0, ((sampledAtMs - previous.sampledAtMs) * metric.cpuPercent) / 100)\n        : 0;\n  return {\n    pid: metric.pid,\n    ppid: 0,\n    startTimeMs: metric.creationTimeMs,\n    runTimeMs: Math.max(0, sampledAtMs - metric.creationTimeMs),\n    name: metric.name ?? metric.serviceName ?? metric.type,\n    command: metric.name ?? metric.serviceName ?? metric.type,\n    status: \"Running\",\n    cpuPercent: metric.cpuPercent,\n    cpuTimeMs,\n    residentBytes: metric.workingSetBytes,\n    virtualBytes: 0,\n    ioReadBytes: 0,\n    ioWriteBytes: 0,\n    ioSemantics: \"storage\",\n  };\n}\n\nfunction processDepths(\n  processes: ReadonlyArray<ResourceMonitorProcessSample>,\n  roots: ReadonlySet<number>,\n): ReadonlyMap<number, number> {\n  const childrenByParent = new Map<number, number[]>();\n  for (const process of processes) {\n    const children = childrenByParent.get(process.ppid) ?? [];\n    children.push(process.pid);\n    childrenByParent.set(process.ppid, children);\n  }\n\n  const depths = new Map<number, number>();\n  const queue = [...roots].map((pid) => ({ pid, depth: 0 }));\n  while (queue.length > 0) {\n    const current = queue.shift();\n    if (!current || depths.has(current.pid)) continue;\n    depths.set(current.pid, current.depth);\n    for (const childPid of childrenByParent.get(current.pid) ?? []) {\n      queue.push({ pid: childPid, depth: current.depth + 1 });\n    }\n  }\n  return depths;\n}\n\nfunction isElectronDescendant(\n  pid: number,\n  processesByPid: ReadonlyMap<number, ResourceMonitorProcessSample>,\n  electronPids: ReadonlySet<number>,\n): boolean {\n  const visited = new Set<number>();\n  let currentPid = pid;\n  while (!visited.has(currentPid)) {\n    visited.add(currentPid);\n    if (electronPids.has(currentPid)) return true;\n    const current = processesByPid.get(currentPid);\n    if (!current || current.ppid <= 0 || current.ppid === currentPid) return false;\n    currentPid = current.ppid;\n  }\n  return false;\n}\n\nfunction hasElectronAncestor(\n  process: ResourceMonitorProcessSample,\n  processesByPid: ReadonlyMap<number, ResourceMonitorProcessSample>,\n  electronPids: ReadonlySet<number>,\n): boolean {\n  const visited = new Set<number>();\n  let currentPid = process.ppid;\n  while (currentPid > 0 && !visited.has(currentPid)) {\n    visited.add(currentPid);\n    if (electronPids.has(currentPid)) return true;\n    const current = processesByPid.get(currentPid);\n    if (!current || current.ppid === currentPid) return false;\n    currentPid = current.ppid;\n  }\n  return false;\n}\n\nfunction orderProcessTree(\n  processes: ReadonlyArray<ResourceTelemetryProcess>,\n  rootPids: ReadonlyArray<number>,\n): ReadonlyArray<ResourceTelemetryProcess> {\n  const processesByPid = new Map(processes.map((process) => [process.identity.pid, process]));\n  const childrenByParent = new Map<number, ResourceTelemetryProcess[]>();\n  for (const process of processes) {\n    const children = childrenByParent.get(process.ppid) ?? [];\n    children.push(process);\n    childrenByParent.set(process.ppid, children);\n  }\n  for (const children of childrenByParent.values()) {\n    children.sort((left, right) => left.identity.pid - right.identity.pid);\n  }\n\n  const ordered: ResourceTelemetryProcess[] = [];\n  const visited = new Set<number>();\n  const visit = (process: ResourceTelemetryProcess): void => {\n    if (visited.has(process.identity.pid)) return;\n    visited.add(process.identity.pid);\n    ordered.push(process);\n    for (const child of childrenByParent.get(process.identity.pid) ?? []) {\n      visit(child);\n    }\n  };\n\n  for (const rootPid of rootPids) {\n    const root = processesByPid.get(rootPid);\n    if (root) visit(root);\n  }\n  for (const process of processes.toSorted(\n    (left, right) => left.depth - right.depth || left.identity.pid - right.identity.pid,\n  )) {\n    visit(process);\n  }\n  return ordered;\n}\n\nfunction delta(input: {\n  readonly current: number;\n  readonly previous: number;\n  readonly elapsedMs: number;\n}): number {\n  if (\n    input.elapsedMs <= 0 ||\n    input.elapsedMs > MAX_DELTA_INTERVAL_MS ||\n    input.current < input.previous\n  ) {\n    return 0;\n  }\n  return input.current - input.previous;\n}\n\nfunction incrementCounters(counters: GroupCounters, update: Partial<GroupCounters>): GroupCounters {\n  return {\n    cpuTimeMs: counters.cpuTimeMs + (update.cpuTimeMs ?? 0),\n    ioReadBytes: counters.ioReadBytes + (update.ioReadBytes ?? 0),\n    ioWriteBytes: counters.ioWriteBytes + (update.ioWriteBytes ?? 0),\n    processStarts: counters.processStarts + (update.processStarts ?? 0),\n    processExits: counters.processExits + (update.processExits ?? 0),\n  };\n}\n\nfunction applyLifecycleCounters(input: {\n  readonly counters: TelemetryCounters;\n  readonly deltas: ReadonlyArray<ProcessDelta>;\n  readonly current: ReadonlyMap<string, ProcessState>;\n  readonly previous: ReadonlyMap<string, ProcessState>;\n}): TelemetryCounters {\n  let backend = input.counters.backend;\n  let electron = input.counters.electron;\n  let monitor = input.counters.monitor;\n  let allT3 = input.counters.allT3;\n  for (const processDelta of input.deltas) {\n    const group = categoryGroup(processDelta.category);\n    switch (group) {\n      case \"backend\":\n        backend = incrementCounters(backend, processDelta);\n        break;\n      case \"electron\":\n        electron = incrementCounters(electron, processDelta);\n        break;\n      case \"monitor\":\n        monitor = incrementCounters(monitor, processDelta);\n        break;\n    }\n    allT3 = incrementCounters(allT3, processDelta);\n  }\n\n  for (const [identityKey, current] of input.current) {\n    if (input.previous.has(identityKey)) continue;\n    const group = categoryGroup(current.process.category);\n    switch (group) {\n      case \"backend\":\n        backend = incrementCounters(backend, { processStarts: 1 });\n        break;\n      case \"electron\":\n        electron = incrementCounters(electron, { processStarts: 1 });\n        break;\n      case \"monitor\":\n        monitor = incrementCounters(monitor, { processStarts: 1 });\n        break;\n    }\n    allT3 = incrementCounters(allT3, { processStarts: 1 });\n  }\n\n  for (const [identityKey, previous] of input.previous) {\n    if (input.current.has(identityKey)) continue;\n    const group = categoryGroup(previous.process.category);\n    switch (group) {\n      case \"backend\":\n        backend = incrementCounters(backend, { processExits: 1 });\n        break;\n      case \"electron\":\n        electron = incrementCounters(electron, { processExits: 1 });\n        break;\n      case \"monitor\":\n        monitor = incrementCounters(monitor, { processExits: 1 });\n        break;\n    }\n    allT3 = incrementCounters(allT3, { processExits: 1 });\n  }\n\n  return { backend, electron, monitor, allT3 };\n}\n\nfunction aggregate(\n  processes: ReadonlyArray<ResourceTelemetryProcess>,\n  counters: GroupCounters,\n): ResourceTelemetryAggregate {\n  return {\n    processCount: processes.length,\n    currentCpuPercent: processes.reduce((total, process) => total + process.cpuPercent, 0),\n    cpuTimeMs: counters.cpuTimeMs,\n    currentRssBytes: processes.reduce((total, process) => total + process.residentBytes, 0),\n    peakRssBytes: processes.reduce((total, process) => total + process.peakResidentBytes, 0),\n    ioReadBytes: counters.ioReadBytes,\n    ioWriteBytes: counters.ioWriteBytes,\n    ioReadBytesPerSecond: processes.reduce(\n      (total, process) => total + process.ioReadBytesPerSecond,\n      0,\n    ),\n    ioWriteBytesPerSecond: processes.reduce(\n      (total, process) => total + process.ioWriteBytesPerSecond,\n      0,\n    ),\n    processStarts: counters.processStarts,\n    processExits: counters.processExits,\n  };\n}\n\nexport function mergeProcesses(input: MergeProcessesInput): MergeProcessesResult {\n  const nativeProcesses = Option.match(input.nativeSnapshot, {\n    onNone: () => [] as ReadonlyArray<ResourceMonitorProcessSample>,\n    onSome: (snapshot) => snapshot.processes,\n  });\n  const electronMetrics = Option.match(input.desktopSnapshot, {\n    onNone: () => [] as ReadonlyArray<DesktopElectronProcessMetric>,\n    onSome: (snapshot) => snapshot.electronProcesses,\n  });\n  const sampledAtMs = Option.match(input.nativeSnapshot, {\n    onNone: () =>\n      Option.match(input.desktopSnapshot, {\n        onNone: () => input.fallbackSampledAtMs,\n        onSome: (snapshot) => snapshot.sampledAtUnixMs,\n      }),\n    onSome: (native) =>\n      Option.match(input.desktopSnapshot, {\n        onNone: () => native.sampledAtUnixMs,\n        onSome: (desktop) => Math.max(native.sampledAtUnixMs, desktop.sampledAtUnixMs),\n      }),\n  });\n  const nativeSampledAtMs = Option.map(\n    input.nativeSnapshot,\n    (snapshot) => snapshot.sampledAtUnixMs,\n  );\n  const desktopSampledAtMs = Option.map(\n    input.desktopSnapshot,\n    (snapshot) => snapshot.sampledAtUnixMs,\n  );\n  const nativeProcessPids = new Set(nativeProcesses.map((process) => process.pid));\n  const nativeByPid = new Map(nativeProcesses.map((process) => [process.pid, process]));\n  const metricsByPid = new Map<number, DesktopElectronProcessMetric>();\n  for (const metric of electronMetrics) {\n    const nativeProcess = nativeByPid.get(metric.pid);\n    if (!nativeProcess) {\n      nativeByPid.set(\n        metric.pid,\n        syntheticNativeSample(\n          metric,\n          Option.getOrElse(desktopSampledAtMs, () => sampledAtMs),\n          input.previous.get(processIdentityKey(metric.pid, metric.creationTimeMs)),\n        ),\n      );\n      metricsByPid.set(metric.pid, metric);\n      continue;\n    }\n    if (\n      Math.abs(metric.creationTimeMs - nativeProcess.startTimeMs) <= ELECTRON_IDENTITY_TOLERANCE_MS\n    ) {\n      metricsByPid.set(metric.pid, metric);\n    }\n  }\n  const processes = [...nativeByPid.values()];\n  const processesByPid = new Map(processes.map((process) => [process.pid, process]));\n  const requestedElectronRootPids = input.electronRootPids ?? new Set<number>();\n  const explicitElectronRootPids = new Set(\n    [...requestedElectronRootPids].filter((pid) => {\n      const process = processesByPid.get(pid);\n      if (!process) return false;\n      const expectedStartTime = input.electronRootStartTimes?.get(pid);\n      if (expectedStartTime !== undefined) {\n        return Math.abs(process.startTimeMs - expectedStartTime) <= ELECTRON_IDENTITY_TOLERANCE_MS;\n      }\n      if (metricsByPid.has(pid)) return true;\n      return [...input.previous.values()].some(\n        (previous) =>\n          previous.process.category === \"electron-main\" &&\n          previous.process.identity.pid === pid &&\n          previous.process.identity.startTimeMs === process.startTimeMs,\n      );\n    }),\n  );\n  const electronPids = new Set([...metricsByPid.keys(), ...explicitElectronRootPids]);\n  const electronRootPids = [\n    ...explicitElectronRootPids,\n    ...[...electronPids]\n      .filter((pid) => {\n        if (explicitElectronRootPids.has(pid)) return false;\n        const process = processesByPid.get(pid);\n        return process === undefined\n          ? true\n          : !hasElectronAncestor(process, processesByPid, electronPids);\n      })\n      .toSorted((left, right) => left - right),\n  ].filter((pid, index, values) => values.indexOf(pid) === index);\n  const rootPids = [input.serverPid, ...electronRootPids];\n  const roots = new Set(rootPids);\n  const depths = processDepths(processes, roots);\n  const childrenByParent = new Map<number, number[]>();\n  for (const process of processes) {\n    const children = childrenByParent.get(process.ppid) ?? [];\n    children.push(process.pid);\n    childrenByParent.set(process.ppid, children);\n  }\n\n  const nextPrevious = new Map<string, ProcessState>();\n  const processDeltas: ProcessDelta[] = [];\n  const normalized = processes.map((process): ResourceTelemetryProcess => {\n    const identityKey = processIdentityKey(process.pid, process.startTimeMs);\n    const previous = input.previous.get(identityKey);\n    const counterSampledAtMs = nativeProcessPids.has(process.pid)\n      ? Option.getOrElse(nativeSampledAtMs, () => sampledAtMs)\n      : Option.getOrElse(desktopSampledAtMs, () => sampledAtMs);\n    const elapsedMs = previous ? counterSampledAtMs - previous.sampledAtMs : 0;\n    const cpuTimeDelta = previous\n      ? delta({\n          current: process.cpuTimeMs,\n          previous: previous.process.cpuTimeMs,\n          elapsedMs,\n        })\n      : 0;\n    const ioReadDelta = previous\n      ? delta({\n          current: process.ioReadBytes,\n          previous: previous.process.ioReadBytes,\n          elapsedMs,\n        })\n      : 0;\n    const ioWriteDelta = previous\n      ? delta({\n          current: process.ioWriteBytes,\n          previous: previous.process.ioWriteBytes,\n          elapsedMs,\n        })\n      : 0;\n    const electronMetric = matchElectronMetric(process, metricsByPid);\n    const category: ResourceTelemetryProcessCategory =\n      process.pid === input.serverPid\n        ? \"server\"\n        : Option.contains(input.sidecarPid, process.pid)\n          ? \"resource-monitor\"\n          : explicitElectronRootPids.has(process.pid)\n            ? \"electron-main\"\n            : electronMetric\n              ? electronCategory(electronMetric)\n              : isElectronDescendant(process.pid, processesByPid, electronPids)\n                ? inferredElectronCategory(process)\n                : \"server-child\";\n    const firstSeenAt = previous?.process.firstSeenAt ?? DateTime.makeUnsafe(sampledAtMs);\n    const preservePreviousRates = !input.updatePrevious && previous !== undefined;\n    const cpuPercent = preservePreviousRates\n      ? previous.process.cpuPercent\n      : previous && elapsedMs > 0 && elapsedMs <= MAX_DELTA_INTERVAL_MS\n        ? (cpuTimeDelta / elapsedMs) * 100\n        : finiteNonNegative(process.cpuPercent);\n    const normalizedProcess: ResourceTelemetryProcess = {\n      identity: {\n        pid: process.pid,\n        startTimeMs: process.startTimeMs,\n      },\n      ppid: process.ppid,\n      childPids: [...(childrenByParent.get(process.pid) ?? [])].toSorted(\n        (left, right) => left - right,\n      ),\n      depth: depths.get(process.pid) ?? 0,\n      name: process.name,\n      command: process.command,\n      status: process.status,\n      category,\n      ...(electronMetric ? { electronType: electronMetric.type } : {}),\n      ...(electronMetric?.serviceName ? { electronServiceName: electronMetric.serviceName } : {}),\n      cpuPercent: finiteNonNegative(cpuPercent),\n      cpuTimeMs: process.cpuTimeMs,\n      residentBytes: process.residentBytes,\n      peakResidentBytes: Math.max(\n        process.residentBytes,\n        electronMetric?.peakWorkingSetBytes ?? 0,\n        previous?.process.peakResidentBytes ?? 0,\n      ),\n      virtualBytes: process.virtualBytes,\n      ioReadBytes: process.ioReadBytes,\n      ioWriteBytes: process.ioWriteBytes,\n      ioReadBytesPerSecond: preservePreviousRates\n        ? previous.process.ioReadBytesPerSecond\n        : elapsedMs > 0\n          ? finiteNonNegative((ioReadDelta * 1_000) / elapsedMs)\n          : 0,\n      ioWriteBytesPerSecond: preservePreviousRates\n        ? previous.process.ioWriteBytesPerSecond\n        : elapsedMs > 0\n          ? finiteNonNegative((ioWriteDelta * 1_000) / elapsedMs)\n          : 0,\n      ioSemantics: process.ioSemantics,\n      ...(electronMetric ? { idleWakeupsPerSecond: electronMetric.idleWakeupsPerSecond } : {}),\n      runTimeMs: process.runTimeMs,\n      firstSeenAt,\n      lastSeenAt: DateTime.makeUnsafe(sampledAtMs),\n    };\n    nextPrevious.set(identityKey, {\n      process: normalizedProcess,\n      sampledAtMs: counterSampledAtMs,\n    });\n    processDeltas.push({\n      identityKey,\n      category,\n      cpuTimeMs: cpuTimeDelta,\n      ioReadBytes: ioReadDelta,\n      ioWriteBytes: ioWriteDelta,\n    });\n    return normalizedProcess;\n  });\n  const ordered = orderProcessTree(normalized, rootPids);\n\n  const counters = input.updatePrevious\n    ? applyLifecycleCounters({\n        counters: input.counters,\n        deltas: processDeltas,\n        current: nextPrevious,\n        previous: input.previous,\n      })\n    : input.counters;\n  const backendProcesses = ordered.filter(\n    (process) => categoryGroup(process.category) === \"backend\",\n  );\n  const electronProcesses = ordered.filter(\n    (process) => categoryGroup(process.category) === \"electron\",\n  );\n  const monitorProcesses = ordered.filter(\n    (process) => categoryGroup(process.category) === \"monitor\",\n  );\n\n  return {\n    sampledAtMs,\n    processes: ordered,\n    previous: input.updatePrevious ? nextPrevious : input.previous,\n    counters,\n    groups: {\n      backend: aggregate(backendProcesses, counters.backend),\n      electron: aggregate(electronProcesses, counters.electron),\n      monitor: aggregate(monitorProcesses, counters.monitor),\n      allT3: aggregate(ordered, counters.allT3),\n    },\n    deltas: processDeltas,\n  };\n}\n","import {\n  HostProcessArchitecture,\n  HostProcessEnvironment,\n  HostProcessPlatform,\n} from \"@t3tools/shared/hostProcess\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport { ServerConfig } from \"../config.ts\";\n\nexport class ResourceMonitorBinaryUnsupported extends Schema.TaggedErrorClass<ResourceMonitorBinaryUnsupported>()(\n  \"ResourceMonitorBinaryUnsupported\",\n  {\n    platform: Schema.String,\n    architecture: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Resource monitoring is unsupported on ${this.platform}/${this.architecture}.`;\n  }\n}\n\nexport class ResourceMonitorBinaryNotFound extends Schema.TaggedErrorClass<ResourceMonitorBinaryNotFound>()(\n  \"ResourceMonitorBinaryNotFound\",\n  {\n    platform: Schema.String,\n    architecture: Schema.String,\n    candidates: Schema.Array(Schema.String),\n  },\n) {\n  override get message(): string {\n    return `Resource monitor binary was not found for ${this.platform}/${this.architecture}.`;\n  }\n}\n\nexport class ResourceMonitorBinaryNotExecutable extends Schema.TaggedErrorClass<ResourceMonitorBinaryNotExecutable>()(\n  \"ResourceMonitorBinaryNotExecutable\",\n  {\n    path: Schema.String,\n    mode: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Resource monitor binary at '${this.path}' is not executable.`;\n  }\n}\n\nexport type ResourceMonitorBinaryError =\n  | ResourceMonitorBinaryUnsupported\n  | ResourceMonitorBinaryNotFound\n  | ResourceMonitorBinaryNotExecutable;\n\nexport class ResourceMonitorBinary extends Context.Service<\n  ResourceMonitorBinary,\n  {\n    readonly resolve: Effect.Effect<string, ResourceMonitorBinaryError>;\n  }\n>()(\"t3/resourceTelemetry/ResourceMonitorBinary\") {}\n\nfunction binaryName(platform: NodeJS.Platform): string {\n  return platform === \"win32\" ? \"synaptic-resource-monitor.exe\" : \"synaptic-resource-monitor\";\n}\n\nexport type ResourceMonitorLinuxLibc = \"gnu\" | \"musl\";\n\nfunction detectResourceMonitorLinuxLibc(): ResourceMonitorLinuxLibc {\n  try {\n    const report = process.report?.getReport() as\n      | {\n          readonly header?: {\n            readonly glibcVersionRuntime?: unknown;\n          };\n        }\n      | undefined;\n    return typeof report?.header?.glibcVersionRuntime === \"string\" ? \"gnu\" : \"musl\";\n  } catch {\n    return \"musl\";\n  }\n}\n\nexport const ResourceMonitorHostLinuxLibc = Context.Reference<ResourceMonitorLinuxLibc>(\n  \"t3/resourceTelemetry/ResourceMonitorHostLinuxLibc\",\n  {\n    defaultValue: detectResourceMonitorLinuxLibc,\n  },\n);\n\nexport function resourceMonitorPlatformKey(\n  platform: NodeJS.Platform,\n  architecture: NodeJS.Architecture,\n): string | undefined {\n  if (\n    (platform !== \"darwin\" && platform !== \"linux\" && platform !== \"win32\") ||\n    (architecture !== \"arm64\" && architecture !== \"x64\")\n  ) {\n    return undefined;\n  }\n  return `${platform}-${architecture}`;\n}\n\nexport function resourceMonitorRustTarget(\n  platform: NodeJS.Platform,\n  architecture: NodeJS.Architecture,\n  linuxLibc: ResourceMonitorLinuxLibc,\n): string | undefined {\n  if (platform === \"darwin\") {\n    return architecture === \"arm64\"\n      ? \"aarch64-apple-darwin\"\n      : architecture === \"x64\"\n        ? \"x86_64-apple-darwin\"\n        : undefined;\n  }\n  if (platform === \"linux\") {\n    if (linuxLibc !== \"gnu\") {\n      return undefined;\n    }\n    return architecture === \"arm64\"\n      ? \"aarch64-unknown-linux-gnu\"\n      : architecture === \"x64\"\n        ? \"x86_64-unknown-linux-gnu\"\n        : undefined;\n  }\n  if (platform === \"win32\") {\n    return architecture === \"arm64\"\n      ? \"aarch64-pc-windows-msvc\"\n      : architecture === \"x64\"\n        ? \"x86_64-pc-windows-msvc\"\n        : undefined;\n  }\n  return undefined;\n}\n\nexport const make = Effect.fn(\"resourceTelemetry.resourceMonitorBinary.make\")(function* () {\n  const config = yield* ServerConfig;\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const platform = yield* HostProcessPlatform;\n  const architecture = yield* HostProcessArchitecture;\n  const environment = yield* HostProcessEnvironment;\n  const linuxLibc = yield* ResourceMonitorHostLinuxLibc;\n  const executableName = binaryName(platform);\n  const platformKey = resourceMonitorPlatformKey(platform, architecture);\n  const rustTarget = resourceMonitorRustTarget(platform, architecture, linuxLibc);\n  const overrideCandidates = [\n    environment.SYNAPTIC_RESOURCE_MONITOR_PATH,\n    config.resourceMonitorPath,\n  ].filter((candidate): candidate is string => Boolean(candidate));\n  const bundledCandidates =\n    platformKey === undefined || rustTarget === undefined\n      ? []\n      : [\n          path.resolve(import.meta.dirname, \"resource-monitor\", platformKey, executableName),\n          path.resolve(import.meta.dirname, \"resource-monitor\", executableName),\n          path.resolve(import.meta.dirname, \"../resource-monitor\", executableName),\n          path.resolve(\n            import.meta.dirname,\n            \"../../../../native/resource-monitor/target\",\n            rustTarget,\n            \"release\",\n            executableName,\n          ),\n          path.resolve(\n            import.meta.dirname,\n            \"../../../native/resource-monitor/target\",\n            rustTarget,\n            \"release\",\n            executableName,\n          ),\n          path.resolve(\n            import.meta.dirname,\n            \"../../../../native/resource-monitor/target/release\",\n            executableName,\n          ),\n          path.resolve(\n            import.meta.dirname,\n            \"../../../../native/resource-monitor/target/debug\",\n            executableName,\n          ),\n        ];\n  if (overrideCandidates.length === 0 && bundledCandidates.length === 0) {\n    return ResourceMonitorBinary.of({\n      resolve: Effect.fail(\n        new ResourceMonitorBinaryUnsupported({\n          platform,\n          architecture,\n        }),\n      ),\n    });\n  }\n\n  const candidates = [...overrideCandidates, ...bundledCandidates];\n\n  const resolve: ResourceMonitorBinary[\"Service\"][\"resolve\"] = Effect.gen(function* () {\n    for (const candidate of candidates) {\n      const exists = yield* fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));\n      if (!exists) continue;\n\n      if (platform !== \"win32\") {\n        const stat = yield* fileSystem.stat(candidate).pipe(Effect.option);\n        if (Option.isSome(stat) && (stat.value.mode & 0o111) === 0) {\n          return yield* new ResourceMonitorBinaryNotExecutable({\n            path: candidate,\n            mode: stat.value.mode,\n          });\n        }\n      }\n\n      return candidate;\n    }\n\n    return yield* new ResourceMonitorBinaryNotFound({\n      platform,\n      architecture,\n      candidates,\n    });\n  });\n\n  return ResourceMonitorBinary.of({ resolve });\n});\n\nexport const layer = Layer.effect(ResourceMonitorBinary, make());\n","import type {\n  HostPowerSnapshot,\n  ResourceMonitorCapabilities,\n  ResourceMonitorCommand,\n  ResourceMonitorEvent,\n  ResourceMonitorExternalProcess,\n  ResourceMonitorHelloEvent,\n  ResourceMonitorSnapshotEvent,\n  ResourceTelemetrySourceStatus,\n} from \"@t3tools/contracts\";\nimport {\n  RESOURCE_MONITOR_PROTOCOL_VERSION,\n  ResourceMonitorCommand as ResourceMonitorCommandSchema,\n  ResourceMonitorEvent as ResourceMonitorEventSchema,\n} from \"@t3tools/contracts\";\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Ndjson from \"effect/unstable/encoding/Ndjson\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport * as ResourceMonitorBinary from \"./ResourceMonitorBinary.ts\";\nimport { ServerConfig } from \"../config.ts\";\nimport { subscribeBeforeSnapshotWithoutMutex } from \"../utils/subscribeBeforeSnapshot.ts\";\n\nconst SAMPLE_INTERVAL_MS = 1_000;\nconst UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS = 5_000;\nconst BATTERY_SAMPLE_INTERVAL_MS = 5_000;\nconst CONSTRAINED_SAMPLE_INTERVAL_MS = 15_000;\nconst HANDSHAKE_TIMEOUT = Duration.seconds(5);\nconst SAMPLE_REQUEST_TIMEOUT = Duration.seconds(5);\nconst HISTORY_REQUEST_TIMEOUT = Duration.seconds(15);\nconst INITIAL_RESTART_DELAY = Duration.millis(500);\nconst MAX_RESTART_DELAY = Duration.seconds(10);\nconst FAILURE_WINDOW_MS = 60_000;\nconst MAX_FAILURES_PER_WINDOW = 5;\n\nexport class NativeTelemetrySpawnFailed extends Schema.TaggedErrorClass<NativeTelemetrySpawnFailed>()(\n  \"NativeTelemetrySpawnFailed\",\n  {\n    path: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to start resource monitor '${this.path}'.`;\n  }\n}\n\nexport class NativeTelemetryHandshakeTimedOut extends Schema.TaggedErrorClass<NativeTelemetryHandshakeTimedOut>()(\n  \"NativeTelemetryHandshakeTimedOut\",\n  {\n    timeoutMs: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Resource monitor handshake timed out after ${this.timeoutMs}ms.`;\n  }\n}\n\nexport class NativeTelemetryRequestTimedOut extends Schema.TaggedErrorClass<NativeTelemetryRequestTimedOut>()(\n  \"NativeTelemetryRequestTimedOut\",\n  {\n    operation: Schema.Literals([\"readHistory\", \"sampleNow\"]),\n    timeoutMs: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Resource monitor '${this.operation}' request timed out after ${this.timeoutMs}ms.`;\n  }\n}\n\nexport class NativeTelemetryProtocolMismatch extends Schema.TaggedErrorClass<NativeTelemetryProtocolMismatch>()(\n  \"NativeTelemetryProtocolMismatch\",\n  {\n    expectedVersion: Schema.Number,\n    receivedVersion: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Resource monitor protocol ${this.receivedVersion} is incompatible with expected protocol ${this.expectedVersion}.`;\n  }\n}\n\nexport class NativeTelemetryDecodeFailed extends Schema.TaggedErrorClass<NativeTelemetryDecodeFailed>()(\n  \"NativeTelemetryDecodeFailed\",\n  {\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return \"Failed to decode resource monitor output.\";\n  }\n}\n\nexport class NativeTelemetryCommandFailed extends Schema.TaggedErrorClass<NativeTelemetryCommandFailed>()(\n  \"NativeTelemetryCommandFailed\",\n  {\n    operation: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Resource monitor command '${this.operation}' failed.`;\n  }\n}\n\nexport class NativeTelemetryExited extends Schema.TaggedErrorClass<NativeTelemetryExited>()(\n  \"NativeTelemetryExited\",\n  {\n    exitCode: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Resource monitor exited with code ${this.exitCode}.`;\n  }\n}\n\nexport class NativeTelemetryStreamClosed extends Schema.TaggedErrorClass<NativeTelemetryStreamClosed>()(\n  \"NativeTelemetryStreamClosed\",\n  {},\n) {\n  override get message(): string {\n    return \"Resource monitor event stream closed unexpectedly.\";\n  }\n}\n\nexport class NativeTelemetryUnavailable extends Schema.TaggedErrorClass<NativeTelemetryUnavailable>()(\n  \"NativeTelemetryUnavailable\",\n  {\n    reason: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Resource monitor is unavailable: ${this.reason}`;\n  }\n}\n\nexport type NativeTelemetryClientError =\n  | ResourceMonitorBinary.ResourceMonitorBinaryError\n  | NativeTelemetrySpawnFailed\n  | NativeTelemetryHandshakeTimedOut\n  | NativeTelemetryRequestTimedOut\n  | NativeTelemetryProtocolMismatch\n  | NativeTelemetryDecodeFailed\n  | NativeTelemetryCommandFailed\n  | NativeTelemetryExited\n  | NativeTelemetryStreamClosed\n  | NativeTelemetryUnavailable;\n\nexport interface NativeTelemetryClientHealth {\n  readonly status: ResourceTelemetrySourceStatus;\n  readonly hello: Option.Option<ResourceMonitorHelloEvent>;\n  readonly lastSampleAt: Option.Option<DateTime.Utc>;\n  readonly lastError: Option.Option<string>;\n  readonly restartCount: number;\n  readonly sampleIntervalMs: number;\n}\n\nexport interface NativeTelemetrySnapshot {\n  readonly generation: number;\n  readonly snapshot: ResourceMonitorSnapshotEvent;\n}\n\nexport class NativeTelemetryClient extends Context.Service<\n  NativeTelemetryClient,\n  {\n    readonly capabilities: Effect.Effect<ResourceMonitorCapabilities, NativeTelemetryClientError>;\n    readonly snapshots: Stream.Stream<NativeTelemetrySnapshot, NativeTelemetryClientError>;\n    readonly readHistory: (\n      windowMs: number,\n    ) => Effect.Effect<ReadonlyArray<ResourceMonitorSnapshotEvent>, NativeTelemetryClientError>;\n    readonly setExternalProcesses: (\n      processes: ReadonlyArray<ResourceMonitorExternalProcess>,\n    ) => Effect.Effect<void, NativeTelemetryClientError>;\n    readonly setHostPowerState: (\n      snapshot: HostPowerSnapshot,\n    ) => Effect.Effect<void, NativeTelemetryClientError>;\n    readonly sampleNow: Effect.Effect<NativeTelemetrySnapshot, NativeTelemetryClientError>;\n    readonly retry: Effect.Effect<boolean>;\n    readonly health: Effect.Effect<NativeTelemetryClientHealth>;\n    readonly subscribeHealth: Effect.Effect<\n      {\n        readonly latest: NativeTelemetryClientHealth;\n        readonly changes: Stream.Stream<NativeTelemetryClientHealth>;\n      },\n      never,\n      Scope.Scope\n    >;\n  }\n>()(\"t3/resourceTelemetry/NativeTelemetryClient\") {}\n\ninterface ClientState {\n  readonly status: ResourceTelemetrySourceStatus;\n  readonly handle: Option.Option<ChildProcessSpawner.ChildProcessHandle>;\n  readonly hello: Option.Option<ResourceMonitorHelloEvent>;\n  readonly lastSampleAt: Option.Option<DateTime.Utc>;\n  readonly lastError: Option.Option<string>;\n  readonly restartCount: number;\n}\n\nexport interface CollectionControl {\n  readonly hostPower: HostPowerSnapshot;\n  readonly liveSubscriberCount: number;\n  readonly sampleIntervalMs: number;\n}\n\ninterface PendingHistoryRequest {\n  readonly deferred: Deferred.Deferred<\n    ReadonlyArray<ResourceMonitorSnapshotEvent>,\n    NativeTelemetryClientError\n  >;\n  readonly snapshots: ReadonlyArray<ResourceMonitorSnapshotEvent>;\n}\n\nconst initialState: ClientState = {\n  status: \"starting\",\n  handle: Option.none(),\n  hello: Option.none(),\n  lastSampleAt: Option.none(),\n  lastError: Option.none(),\n  restartCount: 0,\n};\n\nfunction toHealth(state: ClientState, sampleIntervalMs: number): NativeTelemetryClientHealth {\n  return {\n    status: state.status,\n    hello: state.hello,\n    lastSampleAt: state.lastSampleAt,\n    lastError: state.lastError,\n    restartCount: state.restartCount,\n    sampleIntervalMs,\n  };\n}\n\nfunction isThermallyConstrained(snapshot: HostPowerSnapshot): boolean {\n  return snapshot.thermalState === \"serious\" || snapshot.thermalState === \"critical\";\n}\n\nexport function resolveNativeSampleIntervalMs(\n  snapshot: HostPowerSnapshot,\n  liveSubscriberCount: number,\n): number {\n  if (snapshot.stale || snapshot.source === \"unknown\") {\n    return liveSubscriberCount > 0 ? SAMPLE_INTERVAL_MS : UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS;\n  }\n  if (\n    snapshot.suspended ||\n    snapshot.locked === \"true\" ||\n    snapshot.lowPowerMode === \"true\" ||\n    isThermallyConstrained(snapshot)\n  ) {\n    return CONSTRAINED_SAMPLE_INTERVAL_MS;\n  }\n  if (snapshot.onBattery === \"true\") return BATTERY_SAMPLE_INTERVAL_MS;\n  return SAMPLE_INTERVAL_MS;\n}\n\nexport function commitCollectionControlUpdate<E, R>(\n  desiredState: Ref.Ref<CollectionControl>,\n  appliedState: Ref.Ref<CollectionControl>,\n  update: (current: CollectionControl) => CollectionControl,\n  apply: (previous: CollectionControl, next: CollectionControl) => Effect.Effect<void, E, R>,\n): Effect.Effect<readonly [CollectionControl, CollectionControl], E, R> {\n  return Effect.gen(function* () {\n    const [previousDesired, next] = yield* Ref.modify(desiredState, (previous) => {\n      const next = update(previous);\n      return [[previous, next] as const, next];\n    });\n    const previousApplied = yield* Ref.get(appliedState);\n    yield* apply(previousApplied, next);\n    yield* Ref.set(appliedState, next);\n    return [previousDesired, next] as const;\n  });\n}\n\nexport function synchronizeCollectionControlOnStart<E1, R1, E2, R2>(\n  mutex: Semaphore.Semaphore,\n  desiredState: Ref.Ref<CollectionControl>,\n  appliedState: Ref.Ref<CollectionControl>,\n  apply: (control: CollectionControl) => Effect.Effect<void, E1, R1>,\n  markReady: Effect.Effect<void, E2, R2>,\n) {\n  return mutex.withPermits(1)(\n    Effect.gen(function* () {\n      const control = yield* Ref.get(desiredState);\n      yield* apply(control);\n      yield* Ref.set(appliedState, control);\n      yield* markReady;\n      return control;\n    }),\n  );\n}\n\nconst decodeMonitorEvent: (\n  value: unknown,\n) => Effect.Effect<ResourceMonitorEvent, Schema.SchemaError> = Schema.decodeUnknownEffect(\n  ResourceMonitorEventSchema,\n);\nconst encodeMonitorCommand = Schema.encodeEffect(\n  Schema.fromJsonString(ResourceMonitorCommandSchema),\n);\nconst isProtocolMismatch = Schema.is(NativeTelemetryProtocolMismatch);\nconst isDecodeFailed = Schema.is(NativeTelemetryDecodeFailed);\nconst isCommandFailed = Schema.is(NativeTelemetryCommandFailed);\n\nfunction eventVersion(value: unknown): number | undefined {\n  if (typeof value !== \"object\" || value === null) return undefined;\n  const version = Reflect.get(value, \"version\");\n  return typeof version === \"number\" ? version : undefined;\n}\n\nfunction restartDelay(attempt: number): Duration.Duration {\n  return Duration.min(Duration.times(INITIAL_RESTART_DELAY, 2 ** attempt), MAX_RESTART_DELAY);\n}\n\nexport function retainRecentNativeTelemetryFailures(\n  failures: ReadonlyArray<number>,\n  now: number,\n): ReadonlyArray<number> {\n  return failures.filter((failedAt) => now - failedAt <= FAILURE_WINDOW_MS);\n}\n\nfunction errorMessage(error: NativeTelemetryClientError): string {\n  return error.message;\n}\n\nexport function nativeTelemetrySupervisorFailureMessage(_cause: Cause.Cause<unknown>): string {\n  return \"Resource monitor supervisor stopped unexpectedly.\";\n}\n\nexport function canRequestNativeTelemetryRetry(\n  status: ResourceTelemetrySourceStatus,\n  hasHandle: boolean,\n): boolean {\n  return status !== \"healthy\" && status !== \"starting\" && !hasHandle;\n}\n\nexport function canCommandNativeTelemetrySidecar(\n  status: ResourceTelemetrySourceStatus,\n  hasHandle: boolean,\n): boolean {\n  return hasHandle && (status === \"healthy\" || status === \"degraded\");\n}\n\nexport const make = Effect.fn(\"resourceTelemetry.nativeTelemetryClient.make\")(function* () {\n  const binary = yield* ResourceMonitorBinary.ResourceMonitorBinary;\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const crypto = yield* Crypto.Crypto;\n  const config = yield* ServerConfig;\n  const initializedAt = yield* DateTime.now;\n  const state = yield* Ref.make(initialState);\n  const collectionControl = yield* Ref.make<CollectionControl>({\n    hostPower: {\n      source: \"unknown\",\n      idle: \"unknown\",\n      idleSeconds: null,\n      locked: \"unknown\",\n      suspended: false,\n      onBattery: \"unknown\",\n      lowPowerMode: \"unknown\",\n      thermalState: \"unknown\",\n      stale: true,\n      updatedAt: initializedAt,\n    },\n    liveSubscriberCount: 0,\n    sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,\n  });\n  const appliedCollectionControl = yield* Ref.make(yield* Ref.get(collectionControl));\n  const externalProcesses = yield* Ref.make<ReadonlyArray<ResourceMonitorExternalProcess>>([]);\n  const pendingSamples = yield* Ref.make(\n    new Map<string, Deferred.Deferred<NativeTelemetrySnapshot, NativeTelemetryClientError>>(),\n  );\n  const pendingHistories = yield* Ref.make(new Map<string, PendingHistoryRequest>());\n  const snapshots = yield* PubSub.sliding<NativeTelemetrySnapshot>(8);\n  const healthChanges = yield* PubSub.sliding<NativeTelemetryClientHealth>(4);\n  const retryQueue = yield* Queue.sliding<void>(1);\n  const commandMutex = yield* Semaphore.make(1);\n  const controlMutex = yield* Semaphore.make(1);\n  const currentHealth = Effect.all([Ref.get(state), Ref.get(collectionControl)]).pipe(\n    Effect.map(([current, control]) => toHealth(current, control.sampleIntervalMs)),\n  );\n  const publishHealth = currentHealth.pipe(\n    Effect.flatMap((health) => PubSub.publish(healthChanges, health)),\n    Effect.asVoid,\n  );\n\n  const failPending = (error: NativeTelemetryClientError) =>\n    Effect.gen(function* () {\n      const samples = yield* Ref.getAndSet(pendingSamples, new Map());\n      const histories = yield* Ref.getAndSet(pendingHistories, new Map());\n      yield* Effect.forEach(samples.values(), (deferred) => Deferred.fail(deferred, error), {\n        discard: true,\n      });\n      yield* Effect.forEach(\n        histories.values(),\n        (request) => Deferred.fail(request.deferred, error),\n        { discard: true },\n      );\n    });\n\n  const writeCommand = (\n    handle: ChildProcessSpawner.ChildProcessHandle,\n    command: ResourceMonitorCommand,\n  ): Effect.Effect<void, NativeTelemetryClientError> =>\n    commandMutex.withPermits(1)(\n      encodeMonitorCommand(command).pipe(\n        Effect.map((encoded) => `${encoded}\\n`),\n        Effect.mapError(\n          (cause) =>\n            new NativeTelemetryCommandFailed({\n              operation: command.type,\n              cause,\n            }),\n        ),\n        Effect.flatMap((encoded) =>\n          Stream.run(Stream.encodeText(Stream.make(encoded)), handle.stdin),\n        ),\n        Effect.mapError(\n          (cause) =>\n            new NativeTelemetryCommandFailed({\n              operation: command.type,\n              cause,\n            }),\n        ),\n      ),\n    );\n\n  const processEvent = (\n    event: ResourceMonitorEvent,\n    helloDeferred: Deferred.Deferred<ResourceMonitorHelloEvent>,\n    generation: number,\n  ): Effect.Effect<void, NativeTelemetryClientError> => {\n    switch (event.type) {\n      case \"hello\":\n        return Ref.update(state, (current) => ({\n          ...current,\n          status: \"starting\" as const,\n          hello: Option.some(event),\n          lastError: Option.none(),\n        })).pipe(\n          Effect.andThen(publishHealth),\n          Effect.andThen(Deferred.succeed(helloDeferred, event)),\n          Effect.asVoid,\n        );\n      case \"snapshot\":\n        return Effect.gen(function* () {\n          const nativeSnapshot = { generation, snapshot: event } satisfies NativeTelemetrySnapshot;\n          const sampledAt = DateTime.makeUnsafe(event.sampledAtUnixMs);\n          yield* Ref.update(state, (current) => ({\n            ...current,\n            status: \"healthy\" as const,\n            lastSampleAt: Option.some(sampledAt),\n            lastError: Option.none(),\n          }));\n          yield* publishHealth;\n          yield* PubSub.publish(snapshots, nativeSnapshot);\n          if (event.requestId) {\n            const deferred = yield* Ref.modify(pendingSamples, (pending) => {\n              const next = new Map(pending);\n              const current = next.get(event.requestId!);\n              next.delete(event.requestId!);\n              return [Option.fromUndefinedOr(current), next];\n            });\n            if (Option.isSome(deferred)) {\n              yield* Deferred.succeed(deferred.value, nativeSnapshot);\n            }\n          }\n        });\n      case \"historyChunk\":\n        return Effect.gen(function* () {\n          const latestSnapshot = event.snapshots.at(-1);\n          yield* Ref.update(state, (current) => ({\n            ...current,\n            status: \"healthy\" as const,\n            lastSampleAt: latestSnapshot\n              ? Option.some(DateTime.makeUnsafe(latestSnapshot.sampledAtUnixMs))\n              : current.lastSampleAt,\n            lastError: Option.none(),\n          }));\n          yield* publishHealth;\n          const completed = yield* Ref.modify(pendingHistories, (pending) => {\n            const request = pending.get(event.requestId);\n            if (!request) return [Option.none(), pending] as const;\n            const snapshots = [...request.snapshots, ...event.snapshots];\n            const next = new Map(pending);\n            if (event.done) {\n              next.delete(event.requestId);\n              return [Option.some({ deferred: request.deferred, snapshots }), next] as const;\n            }\n            next.set(event.requestId, { deferred: request.deferred, snapshots });\n            return [Option.none(), next] as const;\n          });\n          if (Option.isSome(completed)) {\n            yield* Deferred.succeed(completed.value.deferred, completed.value.snapshots);\n          }\n        });\n      case \"error\":\n        return Ref.update(state, (current) => ({\n          ...current,\n          status: \"degraded\" as const,\n          lastError: Option.some(event.message),\n        })).pipe(\n          Effect.andThen(publishHealth),\n          Effect.andThen(\n            event.recoverable\n              ? Effect.void\n              : Effect.fail(\n                  new NativeTelemetryCommandFailed({\n                    operation: event.code,\n                    cause: event.message,\n                  }),\n                ),\n          ),\n        );\n    }\n  };\n\n  const runAttempt: Effect.Effect<void, NativeTelemetryClientError> = Effect.scoped(\n    Effect.gen(function* () {\n      const executablePath = yield* binary.resolve;\n      const command = ChildProcess.make(executablePath, [], {\n        cwd: config.cwd,\n        stdin: {\n          stream: \"pipe\",\n          endOnDone: false,\n        },\n        stdout: \"pipe\",\n        stderr: \"pipe\",\n        killSignal: \"SIGTERM\",\n        forceKillAfter: Duration.seconds(2),\n      });\n      const handle = yield* Effect.acquireRelease(\n        spawner\n          .spawn(command)\n          .pipe(\n            Effect.mapError(\n              (cause) => new NativeTelemetrySpawnFailed({ path: executablePath, cause }),\n            ),\n          ),\n        (child) => child.kill().pipe(Effect.ignore),\n      );\n      yield* Ref.update(state, (current) => ({\n        ...current,\n        status: \"starting\" as const,\n        handle: Option.some(handle),\n        hello: Option.none(),\n      }));\n      yield* publishHealth;\n      const generation = (yield* Ref.get(state)).restartCount;\n\n      const helloDeferred = yield* Deferred.make<ResourceMonitorHelloEvent>();\n      const eventFiber = yield* handle.stdout.pipe(\n        Stream.pipeThroughChannel(Ndjson.decode({ ignoreEmptyLines: true })),\n        Stream.mapEffect(\n          (\n            value,\n          ): Effect.Effect<\n            ResourceMonitorEvent,\n            NativeTelemetryProtocolMismatch | NativeTelemetryDecodeFailed\n          > => {\n            const version = eventVersion(value);\n            if (version !== undefined && version !== RESOURCE_MONITOR_PROTOCOL_VERSION) {\n              return Effect.fail(\n                new NativeTelemetryProtocolMismatch({\n                  expectedVersion: RESOURCE_MONITOR_PROTOCOL_VERSION,\n                  receivedVersion: version,\n                }),\n              );\n            }\n            return decodeMonitorEvent(value).pipe(\n              Effect.mapError((cause) => new NativeTelemetryDecodeFailed({ cause })),\n            );\n          },\n        ),\n        Stream.runForEach((event) => processEvent(event, helloDeferred, generation)),\n        Effect.mapError((cause) =>\n          isProtocolMismatch(cause) || isDecodeFailed(cause) || isCommandFailed(cause)\n            ? cause\n            : new NativeTelemetryDecodeFailed({ cause }),\n        ),\n        Effect.forkScoped,\n      );\n      yield* handle.stderr.pipe(Stream.runDrain, Effect.ignore, Effect.forkScoped);\n\n      const hello = yield* Deferred.await(helloDeferred).pipe(\n        Effect.timeoutOption(HANDSHAKE_TIMEOUT),\n        Effect.flatMap(\n          Option.match({\n            onNone: () =>\n              Effect.fail(\n                new NativeTelemetryHandshakeTimedOut({\n                  timeoutMs: Duration.toMillis(HANDSHAKE_TIMEOUT),\n                }),\n              ),\n            onSome: Effect.succeed,\n          }),\n        ),\n      );\n      yield* synchronizeCollectionControlOnStart(\n        controlMutex,\n        collectionControl,\n        appliedCollectionControl,\n        (control) =>\n          Effect.gen(function* () {\n            yield* writeCommand(handle, {\n              version: RESOURCE_MONITOR_PROTOCOL_VERSION,\n              type: \"configure\",\n              rootPid: process.pid,\n              sampleIntervalMs: control.sampleIntervalMs,\n              externalProcesses: [...(yield* Ref.get(externalProcesses))],\n            });\n            if (control.liveSubscriberCount > 0) {\n              yield* writeCommand(handle, {\n                version: RESOURCE_MONITOR_PROTOCOL_VERSION,\n                type: \"setStreaming\",\n                enabled: true,\n              });\n            }\n          }),\n        Ref.update(state, (current) => ({\n          ...current,\n          status: \"healthy\" as const,\n          hello: Option.some(hello),\n        })).pipe(Effect.andThen(publishHealth)),\n      );\n\n      yield* writeCommand(handle, {\n        version: RESOURCE_MONITOR_PROTOCOL_VERSION,\n        type: \"setExternalProcesses\",\n        processes: [...(yield* Ref.get(externalProcesses))],\n      });\n\n      const exitEffect = handle.exitCode.pipe(\n        Effect.mapError(\n          (cause) =>\n            new NativeTelemetryCommandFailed({\n              operation: \"waitForExit\",\n              cause,\n            }),\n        ),\n        Effect.flatMap((exitCode) =>\n          Effect.fail(new NativeTelemetryExited({ exitCode: Number(exitCode) })),\n        ),\n      );\n      const decoderEffect = Fiber.join(eventFiber).pipe(\n        Effect.andThen(Effect.fail(new NativeTelemetryStreamClosed())),\n      );\n      return yield* Effect.raceFirst(exitEffect, decoderEffect);\n    }),\n  ).pipe(\n    Effect.ensuring(\n      Ref.update(state, (current) => ({\n        ...current,\n        handle: Option.none(),\n      })),\n    ),\n  );\n\n  yield* Effect.gen(function* () {\n    let failures: ReadonlyArray<number> = [];\n    let restartAttempt = 0;\n\n    while (true) {\n      const result = yield* Effect.result(runAttempt);\n      if (Result.isSuccess(result)) {\n        return;\n      }\n\n      const error = result.failure;\n      const now = DateTime.toEpochMillis(yield* DateTime.now);\n      const recentFailures = retainRecentNativeTelemetryFailures(failures, now);\n      if (recentFailures.length === 0) {\n        restartAttempt = 0;\n      }\n      failures = [...recentFailures, now];\n      const exhausted = failures.length >= MAX_FAILURES_PER_WINDOW;\n      yield* Ref.update(state, (current) => ({\n        ...current,\n        status: exhausted ? (\"unavailable\" as const) : (\"degraded\" as const),\n        hello: Option.none(),\n        lastError: Option.some(errorMessage(error)),\n        restartCount: current.restartCount + 1,\n      }));\n      yield* publishHealth;\n      yield* failPending(error);\n\n      if (exhausted) {\n        yield* Queue.take(retryQueue);\n        failures = [];\n        restartAttempt = 0;\n        yield* Ref.update(state, (current) => ({\n          ...current,\n          status: \"starting\" as const,\n          hello: Option.none(),\n          lastError: Option.none(),\n        }));\n        yield* publishHealth;\n        continue;\n      }\n\n      const manuallyRetried = yield* Effect.raceFirst(\n        Effect.sleep(restartDelay(restartAttempt)).pipe(Effect.as(false)),\n        Queue.take(retryQueue).pipe(Effect.as(true)),\n      );\n      restartAttempt = manuallyRetried ? 0 : restartAttempt + 1;\n    }\n  }).pipe(\n    Effect.catchCause((cause) =>\n      Cause.hasInterruptsOnly(cause)\n        ? Effect.void\n        : Ref.update(state, (current) => ({\n            ...current,\n            status: \"unavailable\" as const,\n            hello: Option.none(),\n            lastError: Option.some(nativeTelemetrySupervisorFailureMessage(cause)),\n          })).pipe(\n            Effect.andThen(publishHealth),\n            Effect.andThen(\n              Effect.logWarning(\"Resource monitor supervisor failed\", {\n                cause: Cause.pretty(cause),\n              }),\n            ),\n          ),\n    ),\n    Effect.forkScoped,\n  );\n\n  const applyCollectionControl = Effect.fn(\n    \"resourceTelemetry.nativeTelemetryClient.applyCollectionControl\",\n  )(function* (previous: CollectionControl, next: CollectionControl) {\n    const current = yield* Ref.get(state);\n    if (canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {\n      const handle = Option.getOrThrow(current.handle);\n      if (previous.sampleIntervalMs !== next.sampleIntervalMs) {\n        yield* writeCommand(handle, {\n          version: RESOURCE_MONITOR_PROTOCOL_VERSION,\n          type: \"setSampleInterval\",\n          sampleIntervalMs: next.sampleIntervalMs,\n        });\n      }\n      const wasStreaming = previous.liveSubscriberCount > 0;\n      const isStreaming = next.liveSubscriberCount > 0;\n      if (wasStreaming !== isStreaming) {\n        yield* writeCommand(handle, {\n          version: RESOURCE_MONITOR_PROTOCOL_VERSION,\n          type: \"setStreaming\",\n          enabled: isStreaming,\n        });\n      }\n    }\n  });\n\n  const updateCollectionControl = (update: (current: CollectionControl) => CollectionControl) =>\n    controlMutex.withPermits(1)(\n      commitCollectionControlUpdate(\n        collectionControl,\n        appliedCollectionControl,\n        update,\n        applyCollectionControl,\n      ).pipe(Effect.ensuring(publishHealth), Effect.asVoid),\n    );\n\n  const setHostPowerState: NativeTelemetryClient[\"Service\"][\"setHostPowerState\"] = (hostPower) =>\n    updateCollectionControl((current) => ({\n      ...current,\n      hostPower,\n      sampleIntervalMs: resolveNativeSampleIntervalMs(hostPower, current.liveSubscriberCount),\n    }));\n\n  const changeLiveSubscriberCount = Effect.fn(\n    \"resourceTelemetry.nativeTelemetryClient.changeLiveSubscriberCount\",\n  )(function* (delta: 1 | -1) {\n    yield* updateCollectionControl((current) => {\n      const liveSubscriberCount = Math.max(0, current.liveSubscriberCount + delta);\n      return {\n        ...current,\n        liveSubscriberCount,\n        sampleIntervalMs: resolveNativeSampleIntervalMs(current.hostPower, liveSubscriberCount),\n      };\n    });\n  });\n\n  const liveSnapshots = Stream.unwrap(\n    Effect.gen(function* () {\n      const subscription = yield* PubSub.subscribe(snapshots);\n      yield* Effect.acquireRelease(changeLiveSubscriberCount(1), () =>\n        changeLiveSubscriberCount(-1).pipe(Effect.ignore),\n      );\n      return Stream.fromSubscription(subscription);\n    }),\n  );\n\n  const setExternalProcesses: NativeTelemetryClient[\"Service\"][\"setExternalProcesses\"] = (\n    processes,\n  ) =>\n    Effect.gen(function* () {\n      yield* Ref.set(externalProcesses, [...processes]);\n      const current = yield* Ref.get(state);\n      if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) return;\n      yield* writeCommand(Option.getOrThrow(current.handle), {\n        version: RESOURCE_MONITOR_PROTOCOL_VERSION,\n        type: \"setExternalProcesses\",\n        processes: [...processes],\n      });\n    });\n\n  const readHistory: NativeTelemetryClient[\"Service\"][\"readHistory\"] = (windowMs) =>\n    Effect.gen(function* () {\n      const current = yield* Ref.get(state);\n      if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {\n        return yield* new NativeTelemetryUnavailable({\n          reason: Option.getOrElse(current.lastError, () => \"sidecar is not running\"),\n        });\n      }\n      const requestId = yield* crypto.randomUUIDv4.pipe(\n        Effect.mapError(\n          (cause) =>\n            new NativeTelemetryCommandFailed({\n              operation: \"createHistoryRequestId\",\n              cause,\n            }),\n        ),\n      );\n      const deferred = yield* Deferred.make<\n        ReadonlyArray<ResourceMonitorSnapshotEvent>,\n        NativeTelemetryClientError\n      >();\n      yield* Ref.update(pendingHistories, (pending) => {\n        const next = new Map(pending);\n        next.set(requestId, { deferred, snapshots: [] });\n        return next;\n      });\n      return yield* writeCommand(Option.getOrThrow(current.handle), {\n        version: RESOURCE_MONITOR_PROTOCOL_VERSION,\n        type: \"readHistory\",\n        requestId,\n        windowMs: Math.max(0, Math.round(windowMs)),\n      }).pipe(\n        Effect.andThen(\n          Deferred.await(deferred).pipe(\n            Effect.timeoutOption(HISTORY_REQUEST_TIMEOUT),\n            Effect.flatMap(\n              Option.match({\n                onNone: () =>\n                  Effect.fail(\n                    new NativeTelemetryRequestTimedOut({\n                      operation: \"readHistory\",\n                      timeoutMs: Duration.toMillis(HISTORY_REQUEST_TIMEOUT),\n                    }),\n                  ),\n                onSome: Effect.succeed,\n              }),\n            ),\n          ),\n        ),\n        Effect.ensuring(\n          Ref.update(pendingHistories, (pending) => {\n            const next = new Map(pending);\n            next.delete(requestId);\n            return next;\n          }),\n        ),\n      );\n    });\n\n  const sampleNow: NativeTelemetryClient[\"Service\"][\"sampleNow\"] = Effect.gen(function* () {\n    const current = yield* Ref.get(state);\n    if (!canCommandNativeTelemetrySidecar(current.status, Option.isSome(current.handle))) {\n      return yield* new NativeTelemetryUnavailable({\n        reason: Option.getOrElse(current.lastError, () => \"sidecar is not running\"),\n      });\n    }\n\n    const requestId = yield* crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new NativeTelemetryCommandFailed({\n            operation: \"createRequestId\",\n            cause,\n          }),\n      ),\n    );\n    const deferred = yield* Deferred.make<NativeTelemetrySnapshot, NativeTelemetryClientError>();\n    yield* Ref.update(pendingSamples, (pending) => {\n      const next = new Map(pending);\n      next.set(requestId, deferred);\n      return next;\n    });\n    return yield* writeCommand(Option.getOrThrow(current.handle), {\n      version: RESOURCE_MONITOR_PROTOCOL_VERSION,\n      type: \"sampleNow\",\n      requestId,\n    }).pipe(\n      Effect.andThen(\n        Deferred.await(deferred).pipe(\n          Effect.timeoutOption(SAMPLE_REQUEST_TIMEOUT),\n          Effect.flatMap(\n            Option.match({\n              onNone: () =>\n                Effect.fail(\n                  new NativeTelemetryRequestTimedOut({\n                    operation: \"sampleNow\",\n                    timeoutMs: Duration.toMillis(SAMPLE_REQUEST_TIMEOUT),\n                  }),\n                ),\n              onSome: Effect.succeed,\n            }),\n          ),\n        ),\n      ),\n      Effect.ensuring(\n        Ref.update(pendingSamples, (pending) => {\n          const next = new Map(pending);\n          next.delete(requestId);\n          return next;\n        }),\n      ),\n    );\n  });\n\n  const health = currentHealth;\n\n  return NativeTelemetryClient.of({\n    capabilities: Ref.get(state).pipe(\n      Effect.flatMap((current) =>\n        Option.match(current.hello, {\n          onNone: () =>\n            Effect.fail(\n              new NativeTelemetryUnavailable({\n                reason: Option.getOrElse(current.lastError, () => \"handshake is incomplete\"),\n              }),\n            ),\n          onSome: (hello) => Effect.succeed(hello.capabilities),\n        }),\n      ),\n    ),\n    snapshots: liveSnapshots,\n    readHistory,\n    setExternalProcesses,\n    setHostPowerState,\n    sampleNow,\n    retry: Ref.get(state).pipe(\n      Effect.flatMap((current) =>\n        !canRequestNativeTelemetryRetry(current.status, Option.isSome(current.handle))\n          ? Effect.succeed(false)\n          : Queue.offer(retryQueue, undefined).pipe(Effect.as(true)),\n      ),\n    ),\n    health,\n    subscribeHealth: subscribeBeforeSnapshotWithoutMutex(healthChanges, health),\n  });\n});\n\nexport const layer = Layer.effect(NativeTelemetryClient, make());\n\nexport const layerTest = (\n  overrides: Partial<NativeTelemetryClient[\"Service\"]> = {},\n): Layer.Layer<NativeTelemetryClient> => {\n  const health =\n    overrides.health ??\n    Effect.succeed({\n      status: \"unavailable\" as const,\n      hello: Option.none<ResourceMonitorHelloEvent>(),\n      lastSampleAt: Option.none<DateTime.Utc>(),\n      lastError: Option.some(\"Resource monitor test implementation is unavailable.\"),\n      restartCount: 0,\n      sampleIntervalMs: UNKNOWN_BACKGROUND_SAMPLE_INTERVAL_MS,\n    });\n  return Layer.succeed(\n    NativeTelemetryClient,\n    NativeTelemetryClient.of({\n      capabilities: Effect.succeed({\n        cumulativeCpuTime: true,\n        currentCpuPercent: true,\n        residentMemory: true,\n        virtualMemory: true,\n        ioBytes: true,\n        processStartTime: true,\n        processTree: true,\n      }),\n      snapshots: Stream.empty,\n      readHistory: () =>\n        Effect.fail(\n          new NativeTelemetryUnavailable({\n            reason: \"No resource monitor history was configured for this test.\",\n          }),\n        ),\n      setExternalProcesses: () => Effect.void,\n      setHostPowerState: () => Effect.void,\n      sampleNow: Effect.fail(\n        new NativeTelemetryUnavailable({\n          reason: \"No resource monitor sample was configured for this test.\",\n        }),\n      ),\n      retry: Effect.succeed(false),\n      health,\n      subscribeHealth:\n        overrides.subscribeHealth ??\n        health.pipe(\n          Effect.map((initial) => ({\n            latest: initial,\n            changes: Stream.empty,\n          })),\n        ),\n      ...overrides,\n    }),\n  );\n};\n","import type { ResourceAttributionEntry, ResourceAttributionSnapshot } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\n\nexport interface ResourceAttributionRecord {\n  readonly component: string;\n  readonly operation: string;\n  readonly logicalReadBytes?: number;\n  readonly logicalWriteBytes?: number;\n  readonly count?: number;\n  readonly durationMs?: number;\n}\n\nexport class ResourceAttribution extends Context.Service<\n  ResourceAttribution,\n  {\n    readonly record: (input: ResourceAttributionRecord) => Effect.Effect<void>;\n    readonly snapshot: Effect.Effect<ResourceAttributionSnapshot>;\n  }\n>()(\"t3/resourceTelemetry/ResourceAttribution\") {}\n\nfunction key(input: Pick<ResourceAttributionRecord, \"component\" | \"operation\">): string {\n  return `${input.component}\\u0000${input.operation}`;\n}\n\nfunction nonNegativeInteger(value: number | undefined, fallback: number): number {\n  if (value === undefined) return fallback;\n  if (!Number.isFinite(value)) return 0;\n  return Math.max(0, Math.round(value));\n}\n\nexport const make = Effect.fn(\"resourceTelemetry.resourceAttribution.make\")(function* () {\n  const entries = yield* Ref.make(new Map<string, ResourceAttributionEntry>());\n\n  const record: ResourceAttribution[\"Service\"][\"record\"] = (input) =>\n    Ref.update(entries, (current) => {\n      const next = new Map(current);\n      const entryKey = key(input);\n      const existing = next.get(entryKey);\n      next.set(entryKey, {\n        component: input.component,\n        operation: input.operation,\n        logicalReadBytes:\n          (existing?.logicalReadBytes ?? 0) + nonNegativeInteger(input.logicalReadBytes, 0),\n        logicalWriteBytes:\n          (existing?.logicalWriteBytes ?? 0) + nonNegativeInteger(input.logicalWriteBytes, 0),\n        count: (existing?.count ?? 0) + nonNegativeInteger(input.count, 1),\n        durationMs: (existing?.durationMs ?? 0) + nonNegativeInteger(input.durationMs, 0),\n      });\n      return next;\n    });\n\n  return ResourceAttribution.of({\n    record,\n    snapshot: Effect.gen(function* () {\n      const readAt = yield* DateTime.now;\n      const current = yield* Ref.get(entries);\n      return {\n        readAt,\n        entries: [...current.values()].toSorted(\n          (left, right) => right.logicalWriteBytes - left.logicalWriteBytes,\n        ),\n      };\n    }),\n  });\n});\n\nexport const layer = Layer.effect(ResourceAttribution, make());\n","import type {\n  DesktopHostTelemetrySnapshot,\n  ResourceMonitorSnapshotEvent,\n  ResourceTelemetryHealth,\n  ResourceTelemetryHistory,\n  ResourceTelemetryHistoryBucket,\n  ResourceTelemetryProcess,\n  ResourceTelemetryProcessSummary,\n} from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Option from \"effect/Option\";\n\nimport {\n  emptyTelemetryCounters,\n  mergeProcesses,\n  processIdentityKey,\n  type ProcessState,\n  type TelemetryCounters,\n} from \"./Model.ts\";\n\nconst MAX_HISTORY_WINDOW_MS = 60 * 60_000;\n\nexport function normalizeResourceTelemetryHistoryInput(input: {\n  readonly windowMs: number;\n  readonly bucketMs: number;\n}): { readonly windowMs: number; readonly bucketMs: number } {\n  const windowMs = Math.max(1_000, Math.min(MAX_HISTORY_WINDOW_MS, input.windowMs));\n  return {\n    windowMs,\n    bucketMs: Math.max(1_000, Math.min(windowMs, input.bucketMs)),\n  };\n}\n\ninterface AggregateSample {\n  readonly sampledAtMs: number;\n  readonly cpuPercent: number;\n  readonly rssBytes: number;\n  readonly processCount: number;\n  readonly ioReadBytes: number;\n  readonly ioWriteBytes: number;\n}\n\ninterface ProcessSample {\n  readonly sampledAtMs: number;\n  readonly process: ResourceTelemetryProcess;\n  readonly cpuTimeMs: number;\n  readonly ioReadBytes: number;\n  readonly ioWriteBytes: number;\n}\n\nexport interface BuildResourceTelemetryHistoryInput {\n  readonly readAt: DateTime.Utc;\n  readonly windowMs: number;\n  readonly bucketMs: number;\n  readonly sampleIntervalMs: number;\n  readonly serverPid: number;\n  readonly sidecarPid: Option.Option<number>;\n  readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;\n  readonly snapshots: ReadonlyArray<ResourceMonitorSnapshotEvent>;\n  readonly health: ResourceTelemetryHealth;\n}\n\nexport type ResourceTelemetryHistoryWithLegacyBuckets = ResourceTelemetryHistory & {\n  readonly legacyBackendBuckets?: ReadonlyArray<ResourceTelemetryHistoryBucket>;\n};\n\nfunction summarizeProcesses(\n  samples: ReadonlyArray<ProcessSample>,\n): ReadonlyArray<ResourceTelemetryProcessSummary> {\n  const groups = new Map<string, ProcessSample[]>();\n  for (const sample of samples) {\n    const identityKey = processIdentityKey(\n      sample.process.identity.pid,\n      sample.process.identity.startTimeMs,\n    );\n    const current = groups.get(identityKey) ?? [];\n    current.push(sample);\n    groups.set(identityKey, current);\n  }\n\n  return [...groups.values()]\n    .map((processSamples): ResourceTelemetryProcessSummary => {\n      const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);\n      const first = sorted[0]!;\n      const latest = sorted[sorted.length - 1]!;\n      const cpuTotal = sorted.reduce((total, sample) => total + sample.process.cpuPercent, 0);\n      return {\n        identity: latest.process.identity,\n        ppid: latest.process.ppid,\n        depth: latest.process.depth,\n        name: latest.process.name,\n        command: latest.process.command,\n        category: latest.process.category,\n        firstSeenAt: first.process.firstSeenAt,\n        lastSeenAt: latest.process.lastSeenAt,\n        currentCpuPercent: latest.process.cpuPercent,\n        avgCpuPercent: cpuTotal / sorted.length,\n        maxCpuPercent: Math.max(...sorted.map((sample) => sample.process.cpuPercent)),\n        cpuTimeMs: sorted.reduce((total, sample) => total + sample.cpuTimeMs, 0),\n        currentRssBytes: latest.process.residentBytes,\n        peakRssBytes: Math.max(...sorted.map((sample) => sample.process.residentBytes)),\n        ioReadBytes: sorted.reduce((total, sample) => total + sample.ioReadBytes, 0),\n        ioWriteBytes: sorted.reduce((total, sample) => total + sample.ioWriteBytes, 0),\n        ioSemantics: latest.process.ioSemantics,\n        sampleCount: sorted.length,\n      };\n    })\n    .toSorted(\n      (left, right) => right.cpuTimeMs - left.cpuTimeMs || right.peakRssBytes - left.peakRssBytes,\n    );\n}\n\nfunction buildBuckets(input: {\n  readonly samples: ReadonlyArray<AggregateSample>;\n  readonly nowMs: number;\n  readonly windowMs: number;\n  readonly bucketMs: number;\n}): ReadonlyArray<ResourceTelemetryHistoryBucket> {\n  const windowStartMs = input.nowMs - input.windowMs;\n  const buckets: ResourceTelemetryHistoryBucket[] = [];\n  for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += input.bucketMs) {\n    const endedAtMs = Math.min(input.nowMs, startedAtMs + input.bucketMs);\n    const samples = input.samples.filter(\n      (sample) =>\n        sample.sampledAtMs >= startedAtMs &&\n        (endedAtMs === input.nowMs\n          ? sample.sampledAtMs <= endedAtMs\n          : sample.sampledAtMs < endedAtMs),\n    );\n    const cpuTotal = samples.reduce((total, sample) => total + sample.cpuPercent, 0);\n    buckets.push({\n      startedAt: DateTime.makeUnsafe(startedAtMs),\n      endedAt: DateTime.makeUnsafe(endedAtMs),\n      avgCpuPercent: samples.length === 0 ? 0 : cpuTotal / samples.length,\n      maxCpuPercent:\n        samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.cpuPercent)),\n      maxRssBytes: samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.rssBytes)),\n      ioReadBytes: samples.reduce((total, sample) => total + sample.ioReadBytes, 0),\n      ioWriteBytes: samples.reduce((total, sample) => total + sample.ioWriteBytes, 0),\n      maxProcessCount:\n        samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.processCount)),\n    });\n  }\n  return buckets;\n}\n\nexport function buildResourceTelemetryHistory(\n  input: BuildResourceTelemetryHistoryInput,\n): ResourceTelemetryHistoryWithLegacyBuckets & {\n  readonly legacyBackendBuckets: ReadonlyArray<ResourceTelemetryHistoryBucket>;\n} {\n  const readAtMs = DateTime.toEpochMillis(input.readAt);\n  const { windowMs, bucketMs } = normalizeResourceTelemetryHistoryInput(input);\n  const windowStartMs = readAtMs - windowMs;\n  const eligibleSnapshots = input.snapshots\n    .filter((snapshot) => snapshot.sampledAtUnixMs <= readAtMs)\n    .toSorted((left, right) => left.sampledAtUnixMs - right.sampledAtUnixMs);\n  const snapshotsInWindow = eligibleSnapshots.filter(\n    (snapshot) => snapshot.sampledAtUnixMs >= windowStartMs,\n  );\n  const precedingSnapshot = eligibleSnapshots.findLast(\n    (snapshot) => snapshot.sampledAtUnixMs < windowStartMs,\n  );\n  const snapshots = precedingSnapshot\n    ? [precedingSnapshot, ...snapshotsInWindow]\n    : snapshotsInWindow;\n  const aggregateSamples: AggregateSample[] = [];\n  const legacyBackendAggregateSamples: AggregateSample[] = [];\n  const processSamples: ProcessSample[] = [];\n  let previous: ReadonlyMap<string, ProcessState> = new Map();\n  let counters: TelemetryCounters = emptyTelemetryCounters();\n  let previousSnapshotAtMs: number | undefined;\n\n  for (const snapshot of snapshots) {\n    const deltaWindowFraction =\n      previousSnapshotAtMs !== undefined &&\n      previousSnapshotAtMs < windowStartMs &&\n      snapshot.sampledAtUnixMs > previousSnapshotAtMs\n        ? Math.max(\n            0,\n            Math.min(\n              1,\n              (snapshot.sampledAtUnixMs - windowStartMs) /\n                (snapshot.sampledAtUnixMs - previousSnapshotAtMs),\n            ),\n          )\n        : 1;\n    previousSnapshotAtMs = snapshot.sampledAtUnixMs;\n    const recordedExternalProcesses =\n      snapshot.externalProcesses ??\n      Option.match(input.desktopSnapshot, {\n        onNone: () => [],\n        onSome: (desktopSnapshot) => [\n          {\n            pid: desktopSnapshot.electronPid,\n            startTimeMs: desktopSnapshot.electronProcesses.find(\n              (metric) => metric.pid === desktopSnapshot.electronPid,\n            )?.creationTimeMs,\n          },\n        ],\n      });\n    const electronRootPids = new Set(recordedExternalProcesses.map((process) => process.pid));\n    const electronRootStartTimes = new Map(\n      recordedExternalProcesses.flatMap((process) =>\n        process.startTimeMs === undefined ? [] : [[process.pid, process.startTimeMs] as const],\n      ),\n    );\n    const merged = mergeProcesses({\n      serverPid: input.serverPid,\n      sidecarPid: input.sidecarPid,\n      fallbackSampledAtMs: snapshot.sampledAtUnixMs,\n      nativeSnapshot: Option.some(snapshot),\n      desktopSnapshot: Option.none(),\n      electronRootPids,\n      electronRootStartTimes,\n      previous,\n      counters,\n      updatePrevious: true,\n    });\n    previous = new Map([...previous, ...merged.previous]);\n    counters = merged.counters;\n    if (snapshot.sampledAtUnixMs < windowStartMs) {\n      continue;\n    }\n    const deltas =\n      deltaWindowFraction === 1\n        ? merged.deltas\n        : merged.deltas.map((delta) => ({\n            ...delta,\n            cpuTimeMs: Math.round(delta.cpuTimeMs * deltaWindowFraction),\n            ioReadBytes: Math.round(delta.ioReadBytes * deltaWindowFraction),\n            ioWriteBytes: Math.round(delta.ioWriteBytes * deltaWindowFraction),\n          }));\n    const deltasByIdentity = new Map(\n      deltas.map((processDelta) => [processDelta.identityKey, processDelta]),\n    );\n    aggregateSamples.push({\n      sampledAtMs: snapshot.sampledAtUnixMs,\n      cpuPercent: merged.groups.allT3.currentCpuPercent,\n      rssBytes: merged.groups.allT3.currentRssBytes,\n      processCount: merged.groups.allT3.processCount,\n      ioReadBytes: deltas.reduce((total, process) => total + process.ioReadBytes, 0),\n      ioWriteBytes: deltas.reduce((total, process) => total + process.ioWriteBytes, 0),\n    });\n    const backendDeltas = deltas.filter(\n      (processDelta) =>\n        processDelta.category === \"server\" ||\n        processDelta.category === \"server-child\" ||\n        processDelta.category === \"provider-root\" ||\n        processDelta.category === \"terminal-root\",\n    );\n    legacyBackendAggregateSamples.push({\n      sampledAtMs: snapshot.sampledAtUnixMs,\n      cpuPercent: merged.groups.backend.currentCpuPercent,\n      rssBytes: merged.groups.backend.currentRssBytes,\n      processCount: merged.groups.backend.processCount,\n      ioReadBytes: backendDeltas.reduce((total, process) => total + process.ioReadBytes, 0),\n      ioWriteBytes: backendDeltas.reduce((total, process) => total + process.ioWriteBytes, 0),\n    });\n    for (const process of merged.processes) {\n      const processDelta = deltasByIdentity.get(\n        processIdentityKey(process.identity.pid, process.identity.startTimeMs),\n      );\n      processSamples.push({\n        sampledAtMs: snapshot.sampledAtUnixMs,\n        process,\n        cpuTimeMs: processDelta?.cpuTimeMs ?? 0,\n        ioReadBytes: processDelta?.ioReadBytes ?? 0,\n        ioWriteBytes: processDelta?.ioWriteBytes ?? 0,\n      });\n    }\n  }\n\n  return {\n    readAt: input.readAt,\n    windowMs,\n    bucketMs,\n    sampleIntervalMs: input.sampleIntervalMs,\n    retainedSampleCount: aggregateSamples.length + processSamples.length,\n    buckets: buildBuckets({ samples: aggregateSamples, nowMs: readAtMs, windowMs, bucketMs }),\n    legacyBackendBuckets: buildBuckets({\n      samples: legacyBackendAggregateSamples,\n      nowMs: readAtMs,\n      windowMs,\n      bucketMs,\n    }),\n    topProcesses: summarizeProcesses(processSamples),\n    health: input.health,\n  };\n}\n","import type {\n  DesktopHostTelemetrySnapshot,\n  HostPowerSnapshot,\n  ResourceMonitorSnapshotEvent,\n  ResourceTelemetryHealth,\n  ResourceTelemetryHistoryInput,\n  ResourceTelemetryProcessIdentity,\n  ResourceTelemetryRetryResult,\n  ResourceTelemetrySnapshot,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as DesktopTelemetryReceiver from \"./DesktopTelemetryReceiver.ts\";\nimport {\n  emptyTelemetryCounters,\n  mergeProcesses,\n  type ProcessState,\n  type TelemetryCounters,\n} from \"./Model.ts\";\nimport * as NativeTelemetryClient from \"./NativeTelemetryClient.ts\";\nimport * as ResourceAttribution from \"./ResourceAttribution.ts\";\nimport {\n  buildResourceTelemetryHistory,\n  normalizeResourceTelemetryHistoryInput,\n  type ResourceTelemetryHistoryWithLegacyBuckets,\n} from \"./ResourceTelemetryHistory.ts\";\nimport { subscribeBeforeSnapshot } from \"../utils/subscribeBeforeSnapshot.ts\";\n\nexport class ResourceTelemetryRefreshFailed extends Schema.TaggedErrorClass<ResourceTelemetryRefreshFailed>()(\n  \"ResourceTelemetryRefreshFailed\",\n  {\n    operation: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Resource telemetry operation '${this.operation}' failed.`;\n  }\n}\n\nexport class ResourceTelemetry extends Context.Service<\n  ResourceTelemetry,\n  {\n    readonly latest: Effect.Effect<ResourceTelemetrySnapshot>;\n    readonly changes: Stream.Stream<ResourceTelemetrySnapshot>;\n    readonly subscribe: Effect.Effect<\n      {\n        readonly latest: ResourceTelemetrySnapshot;\n        readonly changes: Stream.Stream<ResourceTelemetrySnapshot>;\n      },\n      never,\n      Scope.Scope\n    >;\n    readonly readHistory: (\n      input: ResourceTelemetryHistoryInput,\n    ) => Effect.Effect<ResourceTelemetryHistoryWithLegacyBuckets>;\n    readonly refresh: Effect.Effect<ResourceTelemetrySnapshot, ResourceTelemetryRefreshFailed>;\n    readonly validateProcessIdentity: (\n      identity: ResourceTelemetryProcessIdentity,\n    ) => Effect.Effect<boolean, ResourceTelemetryRefreshFailed>;\n    readonly retry: Effect.Effect<ResourceTelemetryRetryResult>;\n  }\n>()(\"t3/resourceTelemetry/ResourceTelemetry\") {}\n\ninterface TelemetryState {\n  readonly nativeSnapshot: Option.Option<ResourceMonitorSnapshotEvent>;\n  readonly desktopSnapshot: Option.Option<DesktopHostTelemetrySnapshot>;\n  readonly previous: ReadonlyMap<string, ProcessState>;\n  readonly counters: TelemetryCounters;\n  readonly latest: ResourceTelemetrySnapshot;\n  readonly lastNativeSequence: number;\n  readonly lastNativeGeneration: number;\n}\n\ninterface LiveTelemetryState {\n  readonly retainCount: number;\n  readonly scope: Option.Option<Scope.Closeable>;\n}\n\nfunction unknownPower(updatedAt: DateTime.Utc): HostPowerSnapshot {\n  return {\n    source: \"unknown\",\n    idle: \"unknown\",\n    idleSeconds: null,\n    locked: \"unknown\",\n    suspended: false,\n    onBattery: \"unknown\",\n    lowPowerMode: \"unknown\",\n    thermalState: \"unknown\",\n    stale: true,\n    updatedAt,\n  };\n}\n\nfunction buildHealth(input: {\n  readonly native: NativeTelemetryClient.NativeTelemetryClientHealth;\n  readonly desktop: DesktopTelemetryReceiver.DesktopTelemetryReceiverHealth;\n  readonly nativeSnapshot: Option.Option<ResourceMonitorSnapshotEvent>;\n}): ResourceTelemetryHealth {\n  return {\n    native: {\n      status: input.native.status,\n      lastSampleAt: input.native.lastSampleAt,\n      lastError: input.native.lastError,\n    },\n    desktop: {\n      status: input.desktop.status,\n      lastSampleAt: input.desktop.lastSampleAt,\n      lastError: input.desktop.lastError,\n    },\n    sidecarVersion: Option.map(input.native.hello, (hello) => hello.sidecarVersion),\n    sidecarPid: Option.map(input.native.hello, (hello) => hello.sidecarPid),\n    restartCount: input.native.restartCount,\n    collectionDurationMicros: Option.match(input.nativeSnapshot, {\n      onNone: () => 0,\n      onSome: (snapshot) => snapshot.collectionDurationMicros,\n    }),\n    scannedProcessCount: Option.match(input.nativeSnapshot, {\n      onNone: () => 0,\n      onSome: (snapshot) => snapshot.scannedProcessCount,\n    }),\n    retainedProcessCount: Option.match(input.nativeSnapshot, {\n      onNone: () => 0,\n      onSome: (snapshot) => snapshot.retainedProcessCount,\n    }),\n    inaccessibleProcessCount: Option.match(input.nativeSnapshot, {\n      onNone: () => 0,\n      onSome: (snapshot) => snapshot.inaccessibleProcessCount,\n    }),\n  };\n}\n\nexport const make = Effect.fn(\"resourceTelemetry.resourceTelemetry.make\")(function* () {\n  const nativeClient = yield* NativeTelemetryClient.NativeTelemetryClient;\n  const desktopReceiver = yield* DesktopTelemetryReceiver.DesktopTelemetryReceiver;\n  const attribution = yield* ResourceAttribution.ResourceAttribution;\n  const mutex = yield* Semaphore.make(1);\n  const changes = yield* PubSub.sliding<ResourceTelemetrySnapshot>(8);\n  const initialReadAt = yield* DateTime.now;\n  const nativeHealthSubscription = yield* nativeClient.subscribeHealth;\n  const desktopHealthSubscription = yield* desktopReceiver.subscribeHealth;\n  const desktopSubscription = yield* desktopReceiver.subscribe;\n  const initialDesktop = desktopSubscription.latest;\n  if (Option.isSome(initialDesktop)) {\n    const electronRoot = initialDesktop.value.electronProcesses.find(\n      (process) => process.pid === initialDesktop.value.electronPid,\n    );\n    yield* nativeClient\n      .setExternalProcesses([\n        {\n          pid: initialDesktop.value.electronPid,\n          ...(electronRoot === undefined ? {} : { startTimeMs: electronRoot.creationTimeMs }),\n        },\n      ])\n      .pipe(Effect.ignore);\n    yield* nativeClient.setHostPowerState(initialDesktop.value.power).pipe(Effect.ignore);\n  }\n  const initialNativeHealth = nativeHealthSubscription.latest;\n  const initialDesktopHealth = desktopHealthSubscription.latest;\n  const initialAttribution = yield* attribution.snapshot;\n  const initialMerge = mergeProcesses({\n    serverPid: process.pid,\n    sidecarPid: Option.map(initialNativeHealth.hello, (hello) => hello.sidecarPid),\n    fallbackSampledAtMs: DateTime.toEpochMillis(initialReadAt),\n    nativeSnapshot: Option.none(),\n    desktopSnapshot: initialDesktop,\n    previous: new Map(),\n    counters: emptyTelemetryCounters(),\n    updatePrevious: false,\n  });\n  const initialSnapshot: ResourceTelemetrySnapshot = {\n    readAt: initialReadAt,\n    sampleIntervalMs: initialNativeHealth.sampleIntervalMs,\n    processes: initialMerge.processes,\n    groups: initialMerge.groups,\n    power: Option.match(initialDesktop, {\n      onNone: () => unknownPower(initialReadAt),\n      onSome: (desktop) => desktop.power,\n    }),\n    speedLimitPercent: Option.flatMap(initialDesktop, (desktop) => desktop.speedLimitPercent),\n    attribution: initialAttribution,\n    health: buildHealth({\n      native: initialNativeHealth,\n      desktop: initialDesktopHealth,\n      nativeSnapshot: Option.none(),\n    }),\n  };\n  const state = yield* Ref.make<TelemetryState>({\n    nativeSnapshot: Option.none(),\n    desktopSnapshot: initialDesktop,\n    previous: new Map(),\n    counters: emptyTelemetryCounters(),\n    latest: initialSnapshot,\n    lastNativeSequence: 0,\n    lastNativeGeneration: initialNativeHealth.restartCount,\n  });\n  const liveState = yield* Ref.make<LiveTelemetryState>({\n    retainCount: 0,\n    scope: Option.none(),\n  });\n  const liveMutex = yield* Semaphore.make(1);\n  const refreshHealth = mutex.withPermits(1)(\n    Effect.gen(function* () {\n      const current = yield* Ref.get(state);\n      const [nativeHealth, desktopHealth] = yield* Effect.all([\n        nativeClient.health,\n        desktopReceiver.health,\n      ]);\n      const snapshot: ResourceTelemetrySnapshot = {\n        ...current.latest,\n        health: buildHealth({\n          native: nativeHealth,\n          desktop: desktopHealth,\n          nativeSnapshot: current.nativeSnapshot,\n        }),\n      };\n      yield* Ref.set(state, {\n        ...current,\n        latest: snapshot,\n      });\n      if ((yield* Ref.get(liveState)).retainCount > 0) {\n        yield* PubSub.publish(changes, snapshot);\n      }\n    }),\n  );\n\n  const rebuild = (input: {\n    readonly nativeSnapshot?: NativeTelemetryClient.NativeTelemetrySnapshot;\n    readonly desktopSnapshot?: DesktopHostTelemetrySnapshot;\n    readonly updatePrevious: boolean;\n    readonly publishWhenLive?: boolean;\n  }): Effect.Effect<ResourceTelemetrySnapshot> =>\n    mutex.withPermits(1)(\n      Effect.gen(function* () {\n        const current = yield* Ref.get(state);\n        const nativeHealth = yield* nativeClient.health;\n        const incomingNativeSnapshot = input.nativeSnapshot;\n        if (\n          incomingNativeSnapshot &&\n          (incomingNativeSnapshot.generation < nativeHealth.restartCount ||\n            incomingNativeSnapshot.generation < current.lastNativeGeneration ||\n            (incomingNativeSnapshot.generation === current.lastNativeGeneration &&\n              incomingNativeSnapshot.snapshot.sequence <= current.lastNativeSequence))\n        ) {\n          return current.latest;\n        }\n        const nativeSnapshot = incomingNativeSnapshot\n          ? Option.some(incomingNativeSnapshot.snapshot)\n          : current.nativeSnapshot;\n        const desktopSnapshot = input.desktopSnapshot\n          ? Option.some(input.desktopSnapshot)\n          : current.desktopSnapshot;\n        const [desktopHealth, attributionSnapshot] = yield* Effect.all([\n          desktopReceiver.health,\n          attribution.snapshot,\n        ]);\n        const recordedElectronRoots = Option.match(nativeSnapshot, {\n          onNone: () => [],\n          onSome: (snapshot) => snapshot.externalProcesses ?? [],\n        });\n        const electronRootPids = new Set(recordedElectronRoots.map((process) => process.pid));\n        Option.match(desktopSnapshot, {\n          onNone: () => undefined,\n          onSome: (desktop) => electronRootPids.add(desktop.electronPid),\n        });\n        const electronRootStartTimes = new Map(\n          recordedElectronRoots.flatMap((process) =>\n            process.startTimeMs === undefined ? [] : [[process.pid, process.startTimeMs] as const],\n          ),\n        );\n        const merged = mergeProcesses({\n          serverPid: process.pid,\n          sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),\n          fallbackSampledAtMs: DateTime.toEpochMillis(current.latest.readAt),\n          nativeSnapshot,\n          desktopSnapshot,\n          electronRootPids,\n          electronRootStartTimes,\n          previous: current.previous,\n          counters: current.counters,\n          updatePrevious: input.updatePrevious,\n        });\n        const readAt = DateTime.makeUnsafe(merged.sampledAtMs);\n        const snapshot: ResourceTelemetrySnapshot = {\n          readAt,\n          sampleIntervalMs: nativeHealth.sampleIntervalMs,\n          processes: merged.processes,\n          groups: merged.groups,\n          power: Option.match(desktopSnapshot, {\n            onNone: () => unknownPower(readAt),\n            onSome: (desktop) => desktop.power,\n          }),\n          speedLimitPercent: Option.match(desktopSnapshot, {\n            onNone: () => Option.none(),\n            onSome: (desktop) => desktop.speedLimitPercent,\n          }),\n          attribution: attributionSnapshot,\n          health: buildHealth({\n            native: nativeHealth,\n            desktop: desktopHealth,\n            nativeSnapshot,\n          }),\n        };\n        yield* Ref.set(state, {\n          nativeSnapshot,\n          desktopSnapshot,\n          previous: merged.previous,\n          counters: merged.counters,\n          latest: snapshot,\n          lastNativeSequence:\n            incomingNativeSnapshot?.snapshot.sequence ?? current.lastNativeSequence,\n          lastNativeGeneration: incomingNativeSnapshot?.generation ?? current.lastNativeGeneration,\n        });\n        if (!input.publishWhenLive || (yield* Ref.get(liveState)).retainCount > 0) {\n          yield* PubSub.publish(changes, snapshot);\n        }\n        return snapshot;\n      }),\n    );\n\n  const ingestNative = (snapshot: NativeTelemetryClient.NativeTelemetrySnapshot) =>\n    rebuild({ nativeSnapshot: snapshot, updatePrevious: true });\n  const ingestDesktop = (snapshot: DesktopHostTelemetrySnapshot) =>\n    Effect.gen(function* () {\n      const electronRoot = snapshot.electronProcesses.find(\n        (process) => process.pid === snapshot.electronPid,\n      );\n      yield* nativeClient\n        .setExternalProcesses([\n          {\n            pid: snapshot.electronPid,\n            ...(electronRoot === undefined ? {} : { startTimeMs: electronRoot.creationTimeMs }),\n          },\n        ])\n        .pipe(Effect.ignore);\n      yield* nativeClient.setHostPowerState(snapshot.power).pipe(Effect.ignore);\n      return yield* rebuild({\n        desktopSnapshot: snapshot,\n        updatePrevious: false,\n        publishWhenLive: true,\n      });\n    });\n\n  yield* desktopSubscription.changes.pipe(\n    Stream.runForEach((snapshot) => ingestDesktop(snapshot)),\n    Effect.forkScoped,\n  );\n\n  const acquireLive = liveMutex.withPermits(1)(\n    Effect.uninterruptible(\n      Effect.gen(function* () {\n        const current = yield* Ref.get(liveState);\n        if (current.retainCount > 0) {\n          yield* Ref.set(liveState, { ...current, retainCount: current.retainCount + 1 });\n          return;\n        }\n\n        const scope = yield* Scope.make();\n        yield* desktopReceiver.setDiagnosticsDemand(true).pipe(Effect.ignore);\n        yield* nativeClient.snapshots.pipe(\n          Stream.runForEach(ingestNative),\n          Effect.catch((error) =>\n            Effect.logWarning(\"Native resource telemetry stream stopped\", {\n              cause: error.message,\n            }),\n          ),\n          Effect.forkIn(scope),\n        );\n        yield* nativeClient.sampleNow.pipe(\n          Effect.flatMap(ingestNative),\n          Effect.ignore,\n          Effect.forkIn(scope),\n        );\n        yield* Ref.set(liveState, { retainCount: 1, scope: Option.some(scope) });\n      }),\n    ),\n  );\n\n  const releaseLive = liveMutex.withPermits(1)(\n    Effect.gen(function* () {\n      const current = yield* Ref.get(liveState);\n      if (current.retainCount <= 1) {\n        yield* Ref.set(liveState, { retainCount: 0, scope: Option.none() });\n        if (Option.isSome(current.scope)) {\n          yield* Scope.close(current.scope.value, Exit.void).pipe(Effect.ignore);\n        }\n        yield* desktopReceiver.setDiagnosticsDemand(false).pipe(Effect.ignore);\n        return;\n      }\n      yield* Ref.set(liveState, { ...current, retainCount: current.retainCount - 1 });\n    }),\n  );\n\n  const latest = Ref.get(state).pipe(Effect.map((current) => current.latest));\n  const subscribe = subscribeBeforeSnapshot(\n    changes,\n    Effect.acquireRelease(acquireLive, () => releaseLive).pipe(Effect.andThen(latest)),\n    mutex,\n  );\n  const liveChanges = Stream.unwrap(Effect.map(subscribe, ({ changes }) => changes));\n\n  const readHistory: ResourceTelemetry[\"Service\"][\"readHistory\"] = (input) =>\n    Effect.gen(function* () {\n      const readAt = yield* DateTime.now;\n      const normalizedInput = normalizeResourceTelemetryHistoryInput(input);\n      const historyResult = yield* Effect.result(\n        nativeClient.readHistory(normalizedInput.windowMs),\n      );\n      if (Result.isFailure(historyResult)) {\n        yield* Effect.logWarning(\"Failed to read native resource telemetry history\", {\n          cause: historyResult.failure.message,\n        });\n      }\n      const [nativeHealth, desktopHealth] = yield* Effect.all([\n        nativeClient.health,\n        desktopReceiver.health,\n      ]);\n      const current = yield* Ref.get(state);\n      return buildResourceTelemetryHistory({\n        readAt,\n        windowMs: normalizedInput.windowMs,\n        bucketMs: normalizedInput.bucketMs,\n        sampleIntervalMs: nativeHealth.sampleIntervalMs,\n        serverPid: process.pid,\n        sidecarPid: Option.map(nativeHealth.hello, (hello) => hello.sidecarPid),\n        desktopSnapshot: current.desktopSnapshot,\n        snapshots: Result.isSuccess(historyResult) ? historyResult.success : [],\n        health: buildHealth({\n          native: nativeHealth,\n          desktop: desktopHealth,\n          nativeSnapshot: current.nativeSnapshot,\n        }),\n      });\n    });\n  yield* nativeHealthSubscription.changes.pipe(\n    Stream.runForEach(() => refreshHealth),\n    Effect.forkScoped,\n  );\n  yield* desktopHealthSubscription.changes.pipe(\n    Stream.runForEach(() => refreshHealth),\n    Effect.forkScoped,\n  );\n\n  const refresh: ResourceTelemetry[\"Service\"][\"refresh\"] = nativeClient.sampleNow.pipe(\n    Effect.flatMap(ingestNative),\n    Effect.mapError(\n      (cause) =>\n        new ResourceTelemetryRefreshFailed({\n          operation: \"refresh\",\n          cause,\n        }),\n    ),\n  );\n\n  const validateProcessIdentity: ResourceTelemetry[\"Service\"][\"validateProcessIdentity\"] = (\n    identity,\n  ) =>\n    nativeClient.sampleNow.pipe(\n      Effect.map(({ snapshot }) =>\n        snapshot.processes.some(\n          (process) => process.pid === identity.pid && process.startTimeMs === identity.startTimeMs,\n        ),\n      ),\n      Effect.mapError(\n        (cause) =>\n          new ResourceTelemetryRefreshFailed({\n            operation: \"validateProcessIdentity\",\n            cause,\n          }),\n      ),\n    );\n\n  return ResourceTelemetry.of({\n    latest,\n    changes: liveChanges,\n    subscribe,\n    readHistory,\n    refresh,\n    validateProcessIdentity,\n    retry: nativeClient.retry.pipe(\n      Effect.zip(Ref.get(state)),\n      Effect.map(\n        ([accepted, current]): ResourceTelemetryRetryResult => ({\n          accepted,\n          snapshot: current.latest,\n        }),\n      ),\n    ),\n  });\n});\n\nexport const layer = Layer.effect(ResourceTelemetry, make());\n","import type {\n  ResourceTelemetryProcessCategory,\n  ServerProcessDiagnosticsEntry,\n  ServerProcessDiagnosticsResult,\n  ServerProcessSignal,\n  ServerSignalProcessResult,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ResourceTelemetry from \"../resourceTelemetry/ResourceTelemetry.ts\";\n\nexport class ProcessSignalFailed extends Schema.TaggedErrorClass<ProcessSignalFailed>()(\n  \"ProcessSignalFailed\",\n  {\n    pid: Schema.Number,\n    signal: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to signal process ${this.pid} with ${this.signal}.`;\n  }\n}\n\nexport class ProcessDiagnostics extends Context.Service<\n  ProcessDiagnostics,\n  {\n    readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;\n    readonly signal: (input: {\n      readonly pid: number;\n      readonly startTimeMs: number;\n      readonly signal: ServerProcessSignal;\n    }) => Effect.Effect<ServerSignalProcessResult>;\n  }\n>()(\"t3/diagnostics/ProcessDiagnostics\") {}\n\nfunction formatElapsed(runTimeMs: number): string {\n  const totalSeconds = Math.max(0, Math.floor(runTimeMs / 1_000));\n  const hours = Math.floor(totalSeconds / 3_600);\n  const minutes = Math.floor((totalSeconds % 3_600) / 60);\n  const seconds = totalSeconds % 60;\n  return hours > 0\n    ? `${hours}:${String(minutes).padStart(2, \"0\")}:${String(seconds).padStart(2, \"0\")}`\n    : `${minutes}:${String(seconds).padStart(2, \"0\")}`;\n}\n\nfunction canSignalCategory(category: ResourceTelemetryProcessCategory): boolean {\n  return (\n    category === \"server-child\" || category === \"provider-root\" || category === \"terminal-root\"\n  );\n}\n\nexport const make = Effect.fn(\"makeProcessDiagnostics\")(function* () {\n  const telemetry = yield* ResourceTelemetry.ResourceTelemetry;\n  const refreshedTelemetry = telemetry.refresh.pipe(Effect.catch(() => telemetry.latest));\n  const read: ProcessDiagnostics[\"Service\"][\"read\"] = refreshedTelemetry.pipe(\n    Effect.map((snapshot) => {\n      const processes = snapshot.processes\n        .filter((entry) => canSignalCategory(entry.category))\n        .map(\n          (entry): ServerProcessDiagnosticsEntry => ({\n            pid: entry.identity.pid,\n            startTimeMs: entry.identity.startTimeMs,\n            ppid: entry.ppid,\n            pgid: Option.none(),\n            status: entry.status || \"Unknown\",\n            cpuPercent: entry.cpuPercent,\n            rssBytes: entry.residentBytes,\n            elapsed: formatElapsed(entry.runTimeMs),\n            command: entry.command || entry.name || \"unknown\",\n            depth: Math.max(0, entry.depth - 1),\n            childPids: entry.childPids,\n          }),\n        );\n      return {\n        serverPid: process.pid,\n        readAt: snapshot.readAt,\n        processCount: processes.length,\n        totalRssBytes: processes.reduce((total, entry) => total + entry.rssBytes, 0),\n        totalCpuPercent: processes.reduce((total, entry) => total + entry.cpuPercent, 0),\n        processes,\n        error: Option.map(snapshot.health.native.lastError, (message) => ({ message })),\n      };\n    }),\n  );\n\n  const signal: ProcessDiagnostics[\"Service\"][\"signal\"] = Effect.fn(\"ProcessDiagnostics.signal\")(\n    function* (input) {\n      if (input.pid === process.pid) {\n        return {\n          pid: input.pid,\n          signal: input.signal,\n          signaled: false,\n          message: Option.some(\"Refusing to signal the Synaptic Code server process.\"),\n        };\n      }\n      const current = yield* telemetry.refresh.pipe(Effect.option);\n      if (Option.isNone(current)) {\n        return {\n          pid: input.pid,\n          signal: input.signal,\n          signaled: false,\n          message: Option.some(\n            `Could not refresh process ${input.pid}; refusing to signal a stale identity.`,\n          ),\n        };\n      }\n      const selected = current.value.processes.find(\n        (entry) =>\n          entry.identity.pid === input.pid && entry.identity.startTimeMs === input.startTimeMs,\n      );\n      if (!selected) {\n        return {\n          pid: input.pid,\n          signal: input.signal,\n          signaled: false,\n          message: Option.some(\n            `Process ${input.pid} no longer matches the selected process identity.`,\n          ),\n        };\n      }\n      if (!canSignalCategory(selected.category)) {\n        return {\n          pid: input.pid,\n          signal: input.signal,\n          signaled: false,\n          message: Option.some(\n            `Process ${input.pid} is not a signalable Synaptic Code backend descendant.`,\n          ),\n        };\n      }\n      return yield* Effect.try({\n        try: () => {\n          process.kill(input.pid, input.signal);\n          return {\n            pid: input.pid,\n            signal: input.signal,\n            signaled: true,\n            message: Option.none(),\n          };\n        },\n        catch: (cause) =>\n          new ProcessSignalFailed({\n            pid: input.pid,\n            signal: input.signal,\n            cause,\n          }),\n      }).pipe(\n        Effect.catch((error) =>\n          Effect.succeed({\n            pid: input.pid,\n            signal: input.signal,\n            signaled: false,\n            message: Option.some(\n              error instanceof Error ? error.message : \"Failed to signal process.\",\n            ),\n          }),\n        ),\n      );\n    },\n  );\n\n  return ProcessDiagnostics.of({ read, signal });\n});\n\nexport const layer = Layer.effect(ProcessDiagnostics, make());\n","import type {\n  ResourceTelemetryProcessCategory,\n  ServerProcessResourceHistoryInput,\n  ServerProcessResourceHistoryResult,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\n\nimport * as ResourceTelemetry from \"../resourceTelemetry/ResourceTelemetry.ts\";\n\nexport class ProcessResourceMonitor extends Context.Service<\n  ProcessResourceMonitor,\n  {\n    readonly readHistory: (\n      input: ServerProcessResourceHistoryInput,\n    ) => Effect.Effect<ServerProcessResourceHistoryResult>;\n  }\n>()(\"t3/diagnostics/ProcessResourceMonitor\") {}\n\nfunction isLegacyBackendCategory(category: ResourceTelemetryProcessCategory): boolean {\n  return (\n    category === \"server\" ||\n    category === \"server-child\" ||\n    category === \"provider-root\" ||\n    category === \"terminal-root\"\n  );\n}\n\nexport const make = Effect.fn(\"makeProcessResourceMonitor\")(function* () {\n  const telemetry = yield* ResourceTelemetry.ResourceTelemetry;\n  const readHistory: ProcessResourceMonitor[\"Service\"][\"readHistory\"] = (input) =>\n    telemetry.readHistory(input).pipe(\n      Effect.map((history) => {\n        const topProcesses = history.topProcesses\n          .filter((entry) => isLegacyBackendCategory(entry.category))\n          .map((entry) => ({\n            processKey: `${entry.identity.pid}:${entry.identity.startTimeMs}`,\n            pid: entry.identity.pid,\n            ppid: entry.ppid,\n            command: entry.command || entry.name || \"unknown\",\n            depth: entry.depth,\n            isServerRoot: entry.category === \"server\",\n            firstSeenAt: entry.firstSeenAt,\n            lastSeenAt: entry.lastSeenAt,\n            currentCpuPercent: entry.currentCpuPercent,\n            avgCpuPercent: entry.avgCpuPercent,\n            maxCpuPercent: entry.maxCpuPercent,\n            cpuSecondsApprox: entry.cpuTimeMs / 1_000,\n            currentRssBytes: entry.currentRssBytes,\n            maxRssBytes: entry.peakRssBytes,\n            sampleCount: entry.sampleCount,\n          }));\n        return {\n          readAt: history.readAt,\n          windowMs: history.windowMs,\n          bucketMs: history.bucketMs,\n          sampleIntervalMs: history.sampleIntervalMs,\n          retainedSampleCount: history.retainedSampleCount,\n          totalCpuSecondsApprox: topProcesses.reduce(\n            (total, entry) => total + entry.cpuSecondsApprox,\n            0,\n          ),\n          buckets: (history.legacyBackendBuckets ?? history.buckets).map((bucket) => ({\n            startedAt: bucket.startedAt,\n            endedAt: bucket.endedAt,\n            avgCpuPercent: bucket.avgCpuPercent,\n            maxCpuPercent: bucket.maxCpuPercent,\n            maxRssBytes: bucket.maxRssBytes,\n            maxProcessCount: bucket.maxProcessCount,\n          })),\n          topProcesses,\n          error: history.health.native.lastError.pipe(\n            Option.map((message) => ({\n              failureTag: \"ProcessDiagnosticsQueryFailedError\" as const,\n              message,\n            })),\n          ),\n        };\n      }),\n    );\n\n  return ProcessResourceMonitor.of({ readHistory });\n});\n\nexport const layer = Layer.effect(ProcessResourceMonitor, make());\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeOS from \"node:os\";\nimport * as NodePath from \"node:path\";\n\n/**\n * Expand a leading `~` (or `~/…`, `~\\…`) in a user-supplied path to the\n * current user's home directory. Spawned processes don't get shell\n * expansion, so env vars like `CODEX_HOME=~/.codex-work` would be passed\n * verbatim and treated as relative paths by the receiver.\n *\n * Matches the behavior of the other `expandHomePath` helpers in the\n * workspace layers and CLI bootstrap: `~` alone and both `~/` and `~\\`\n * separators are handled. Returns the input unchanged if it doesn't\n * start with `~` or is empty. Does not handle `~user` (other-user)\n * expansion.\n */\nexport function expandHomePath(value: string): string {\n  if (!value) return value;\n  if (value === \"~\") return NodeOS.homedir();\n  if (value.startsWith(\"~/\") || value.startsWith(\"~\\\\\")) {\n    return NodePath.join(NodeOS.homedir(), value.slice(2));\n  }\n  return value;\n}\n","import * as NodeOS from \"node:os\";\n\nimport type { ClaudeSettings } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Path from \"effect/Path\";\n\nimport { expandHomePath } from \"../../pathExpansion.ts\";\n\nexport const resolveClaudeHomePath = Effect.fn(\"resolveClaudeHomePath\")(function* (\n  config: Pick<ClaudeSettings, \"homePath\">,\n): Effect.fn.Return<string, never, Path.Path> {\n  const path = yield* Path.Path;\n  const homePath = config.homePath.trim();\n  return path.resolve(homePath.length > 0 ? expandHomePath(homePath) : NodeOS.homedir());\n});\n\nexport const makeClaudeEnvironment = Effect.fn(\"makeClaudeEnvironment\")(function* (\n  config: Pick<ClaudeSettings, \"homePath\">,\n  baseEnv?: NodeJS.ProcessEnv,\n): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {\n  const resolvedBaseEnv = baseEnv ?? process.env;\n  const homePath = config.homePath.trim();\n  if (homePath.length === 0) return resolvedBaseEnv;\n  const resolvedHomePath = yield* resolveClaudeHomePath(config);\n  return {\n    ...resolvedBaseEnv,\n    // Isolate this instance's config via CLAUDE_CONFIG_DIR rather than HOME.\n    // Overriding HOME also relocates the macOS login keychain lookup\n    // ($HOME/Library/Keychains), so the spawned CLI can't find its stored\n    // OAuth credentials and reports \"Not logged in\". CLAUDE_CONFIG_DIR points\n    // Claude Code at its config dir directly while leaving HOME (and the\n    // keychain) intact.\n    CLAUDE_CONFIG_DIR: resolvedHomePath,\n  };\n});\n\nexport const makeClaudeContinuationGroupKey = Effect.fn(\"makeClaudeContinuationGroupKey\")(\n  function* (config: Pick<ClaudeSettings, \"homePath\">): Effect.fn.Return<string, never, Path.Path> {\n    const resolvedHomePath = yield* resolveClaudeHomePath(config);\n    return `claude:home:${resolvedHomePath}`;\n  },\n);\n\nexport const makeClaudeCapabilitiesCacheKey = Effect.fn(\"makeClaudeCapabilitiesCacheKey\")(\n  function* (\n    config: Pick<ClaudeSettings, \"binaryPath\" | \"homePath\">,\n    cwd?: string,\n  ): Effect.fn.Return<string, never, Path.Path> {\n    const resolvedHomePath = yield* resolveClaudeHomePath(config);\n    return `${config.binaryPath}\\0${resolvedHomePath}\\0${cwd ?? \"\"}`;\n  },\n);\n","import * as NodeOS from \"node:os\";\n\nimport { ProviderDriverKind, type CodexSettings } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as PlatformError from \"effect/PlatformError\";\n\nimport { expandHomePath } from \"../../pathExpansion.ts\";\n\nexport interface CodexHomeLayout {\n  readonly mode: \"direct\" | \"authOverlay\";\n  readonly sharedHomePath: string;\n  readonly effectiveHomePath: string | undefined;\n  readonly continuationKey: string;\n}\n\nconst KNOWN_SHARED_DIRECTORIES = [\n  \"sessions\",\n  \"archived_sessions\",\n  \"sqlite\",\n  \"shell_snapshots\",\n  \"worktrees\",\n  \"skills\",\n  \"plugins\",\n  \"cache\",\n  \"logs\",\n  \"mcp-oauth-locks\",\n] as const;\n\nconst PRIVATE_ENTRY_NAMES = new Set([\"auth.json\", \"models_cache.json\"]);\nconst SHADOW_LOCAL_ENTRY_NAMES = new Set([\"log\", \"memories\", \"tmp\"]);\nconst REPLACEABLE_SHARED_RUNTIME_DIRECTORIES = new Set([\"mcp-oauth-locks\"]);\n\nfunction resolveHomePath(path: Path.Path, value: string | undefined): string {\n  const expanded =\n    value && value.trim().length > 0\n      ? expandHomePath(value)\n      : path.join(NodeOS.homedir(), \".codex\");\n  return path.resolve(expanded);\n}\n\nexport const resolveCodexHomeLayout = Effect.fn(\"resolveCodexHomeLayout\")(function* (\n  config: CodexSettings,\n): Effect.fn.Return<CodexHomeLayout, never, Path.Path> {\n  const path = yield* Path.Path;\n  const sharedHomePath = resolveHomePath(path, config.homePath);\n  const shadowHomePath = config.shadowHomePath.trim();\n  if (shadowHomePath.length === 0) {\n    return {\n      mode: \"direct\",\n      sharedHomePath,\n      effectiveHomePath: config.homePath.trim().length > 0 ? sharedHomePath : undefined,\n      continuationKey: `codex:home:${sharedHomePath}`,\n    };\n  }\n\n  const effectiveHomePath = path.resolve(expandHomePath(shadowHomePath));\n  return {\n    mode: \"authOverlay\",\n    sharedHomePath,\n    effectiveHomePath,\n    continuationKey: `codex:home:${sharedHomePath}`,\n  };\n});\n\nconst CodexShadowHomeContext = {\n  sharedHomePath: Schema.String,\n  effectiveHomePath: Schema.String,\n};\n\nexport class CodexShadowHomeFileSystemError extends Schema.TaggedErrorClass<CodexShadowHomeFileSystemError>()(\n  \"CodexShadowHomeFileSystemError\",\n  {\n    ...CodexShadowHomeContext,\n    operation: Schema.Literals([\"readLink\", \"makeDirectory\", \"readDirectory\", \"remove\", \"symlink\"]),\n    path: Schema.String,\n    targetPath: Schema.optional(Schema.String),\n    entryName: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    const target = this.targetPath === undefined ? \"\" : ` to '${this.targetPath}'`;\n    return `Codex shadow home filesystem operation '${this.operation}' failed for '${this.path}'${target}.`;\n  }\n}\n\nexport class CodexShadowHomePathConflictError extends Schema.TaggedErrorClass<CodexShadowHomePathConflictError>()(\n  \"CodexShadowHomePathConflictError\",\n  CodexShadowHomeContext,\n) {\n  override get message(): string {\n    return `Codex shadow home path '${this.effectiveHomePath}' must be different from the shared home path '${this.sharedHomePath}'.`;\n  }\n}\n\nexport class CodexShadowHomeEntryConflictError extends Schema.TaggedErrorClass<CodexShadowHomeEntryConflictError>()(\n  \"CodexShadowHomeEntryConflictError\",\n  {\n    ...CodexShadowHomeContext,\n    entryName: Schema.String,\n    linkPath: Schema.String,\n    targetPath: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Cannot create Codex shadow home entry '${this.entryName}' because '${this.linkPath}' already exists and is not a symlink.`;\n  }\n}\n\nexport class CodexShadowHomePrivateEntrySymlinkError extends Schema.TaggedErrorClass<CodexShadowHomePrivateEntrySymlinkError>()(\n  \"CodexShadowHomePrivateEntrySymlinkError\",\n  {\n    ...CodexShadowHomeContext,\n    entryName: Schema.String,\n    path: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Codex shadow home private entry '${this.entryName}' at '${this.path}' must be a real file, not a symlink.`;\n  }\n}\n\nexport const CodexShadowHomeError = Schema.Union([\n  CodexShadowHomeFileSystemError,\n  CodexShadowHomePathConflictError,\n  CodexShadowHomeEntryConflictError,\n  CodexShadowHomePrivateEntrySymlinkError,\n]);\nexport type CodexShadowHomeError = typeof CodexShadowHomeError.Type;\n\ntype LinkState =\n  | {\n      readonly _tag: \"Missing\";\n    }\n  | {\n      readonly _tag: \"NotSymlink\";\n    }\n  | {\n      readonly _tag: \"Symlink\";\n      readonly target: string;\n    };\n\nfunction isNotSymlinkError(error: PlatformError.PlatformError): boolean {\n  const cause = error.reason.cause;\n  return (\n    error.reason._tag === \"Unknown\" &&\n    typeof cause === \"object\" &&\n    cause !== null &&\n    \"code\" in cause &&\n    cause.code === \"EINVAL\"\n  );\n}\n\nconst readLinkState = Effect.fn(\"CodexHomeLayout.readLinkState\")(function* (input: {\n  readonly fileSystem: FileSystem.FileSystem;\n  readonly sharedHomePath: string;\n  readonly effectiveHomePath: string;\n  readonly entryName: string;\n  readonly linkPath: string;\n}): Effect.fn.Return<LinkState, CodexShadowHomeError> {\n  return yield* input.fileSystem.readLink(input.linkPath).pipe(\n    Effect.map((target): LinkState => ({ _tag: \"Symlink\", target })),\n    Effect.catchTags({\n      PlatformError: (cause) => {\n        if (cause.reason._tag === \"NotFound\") {\n          return Effect.succeed<LinkState>({ _tag: \"Missing\" });\n        }\n        if (isNotSymlinkError(cause)) {\n          return Effect.succeed<LinkState>({ _tag: \"NotSymlink\" });\n        }\n        return new CodexShadowHomeFileSystemError({\n          sharedHomePath: input.sharedHomePath,\n          effectiveHomePath: input.effectiveHomePath,\n          operation: \"readLink\",\n          path: input.linkPath,\n          entryName: input.entryName,\n          cause,\n        });\n      },\n    }),\n  );\n});\n\nconst removePrivateSymlink = Effect.fn(\"CodexHomeLayout.removePrivateSymlink\")(function* (input: {\n  readonly fileSystem: FileSystem.FileSystem;\n  readonly sharedHomePath: string;\n  readonly effectiveHomePath: string;\n  readonly entryName: string;\n}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {\n  const path = yield* Path.Path;\n  const privatePath = path.join(input.effectiveHomePath, input.entryName);\n  const state = yield* readLinkState({\n    ...input,\n    linkPath: privatePath,\n  });\n  if (state._tag === \"Symlink\") {\n    yield* input.fileSystem.remove(privatePath).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          new CodexShadowHomeFileSystemError({\n            sharedHomePath: input.sharedHomePath,\n            effectiveHomePath: input.effectiveHomePath,\n            operation: \"remove\",\n            path: privatePath,\n            entryName: input.entryName,\n            cause,\n          }),\n      }),\n    );\n  }\n});\n\nconst ensureSymlink = Effect.fn(\"CodexHomeLayout.ensureSymlink\")(function* (input: {\n  readonly fileSystem: FileSystem.FileSystem;\n  readonly sharedHomePath: string;\n  readonly effectiveHomePath: string;\n  readonly entryName: string;\n}): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {\n  const path = yield* Path.Path;\n  const target = path.join(input.sharedHomePath, input.entryName);\n  const link = path.join(input.effectiveHomePath, input.entryName);\n  const state = yield* readLinkState({\n    ...input,\n    linkPath: link,\n  });\n\n  const createLink = input.fileSystem.symlink(target, link).pipe(\n    Effect.catchTags({\n      PlatformError: (cause) =>\n        new CodexShadowHomeFileSystemError({\n          sharedHomePath: input.sharedHomePath,\n          effectiveHomePath: input.effectiveHomePath,\n          operation: \"symlink\",\n          path: link,\n          targetPath: target,\n          entryName: input.entryName,\n          cause,\n        }),\n    }),\n  );\n\n  if (state._tag === \"NotSymlink\") {\n    if (!REPLACEABLE_SHARED_RUNTIME_DIRECTORIES.has(input.entryName)) {\n      return yield* new CodexShadowHomeEntryConflictError({\n        sharedHomePath: input.sharedHomePath,\n        effectiveHomePath: input.effectiveHomePath,\n        entryName: input.entryName,\n        linkPath: link,\n        targetPath: target,\n      });\n    }\n\n    yield* input.fileSystem.remove(link, { recursive: true }).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          new CodexShadowHomeFileSystemError({\n            sharedHomePath: input.sharedHomePath,\n            effectiveHomePath: input.effectiveHomePath,\n            operation: \"remove\",\n            path: link,\n            entryName: input.entryName,\n            cause,\n          }),\n      }),\n    );\n    return yield* createLink;\n  }\n\n  if (state._tag === \"Missing\") {\n    return yield* createLink;\n  }\n\n  const resolvedExisting = path.resolve(path.dirname(link), state.target);\n  if (resolvedExisting !== target) {\n    yield* input.fileSystem.remove(link).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          new CodexShadowHomeFileSystemError({\n            sharedHomePath: input.sharedHomePath,\n            effectiveHomePath: input.effectiveHomePath,\n            operation: \"remove\",\n            path: link,\n            entryName: input.entryName,\n            cause,\n          }),\n      }),\n    );\n    yield* createLink;\n  }\n});\n\nconst ensureShadowAuthIsPrivate = Effect.fn(\"CodexHomeLayout.ensureShadowAuthIsPrivate\")(\n  function* (input: {\n    readonly fileSystem: FileSystem.FileSystem;\n    readonly sharedHomePath: string;\n    readonly effectiveHomePath: string;\n  }): Effect.fn.Return<void, CodexShadowHomeError, Path.Path> {\n    const path = yield* Path.Path;\n    const entryName = \"auth.json\";\n    const authPath = path.join(input.effectiveHomePath, entryName);\n    const state = yield* readLinkState({\n      ...input,\n      entryName,\n      linkPath: authPath,\n    });\n    if (state._tag === \"Symlink\") {\n      return yield* new CodexShadowHomePrivateEntrySymlinkError({\n        sharedHomePath: input.sharedHomePath,\n        effectiveHomePath: input.effectiveHomePath,\n        entryName,\n        path: authPath,\n      });\n    }\n  },\n);\n\nexport const materializeCodexShadowHome = Effect.fn(\"materializeCodexShadowHome\")(function* (\n  layout: CodexHomeLayout,\n) {\n  if (layout.mode !== \"authOverlay\") return;\n  const effectiveHomePath = layout.effectiveHomePath;\n  if (!effectiveHomePath) return;\n  if (layout.sharedHomePath === effectiveHomePath) {\n    return yield* new CodexShadowHomePathConflictError({\n      sharedHomePath: layout.sharedHomePath,\n      effectiveHomePath,\n    });\n  }\n\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n\n  const makeDirectory = (directoryPath: string) =>\n    fileSystem.makeDirectory(directoryPath, { recursive: true }).pipe(\n      Effect.catchTags({\n        PlatformError: (cause) =>\n          new CodexShadowHomeFileSystemError({\n            sharedHomePath: layout.sharedHomePath,\n            effectiveHomePath,\n            operation: \"makeDirectory\",\n            path: directoryPath,\n            cause,\n          }),\n      }),\n    );\n\n  yield* Effect.all(\n    [\n      makeDirectory(layout.sharedHomePath),\n      makeDirectory(effectiveHomePath),\n      ...KNOWN_SHARED_DIRECTORIES.map((directory) =>\n        makeDirectory(path.join(layout.sharedHomePath, directory)),\n      ),\n    ],\n    { concurrency: \"unbounded\" },\n  );\n\n  const sharedEntryNames = yield* fileSystem.readDirectory(layout.sharedHomePath).pipe(\n    Effect.catchTags({\n      PlatformError: (cause) =>\n        new CodexShadowHomeFileSystemError({\n          sharedHomePath: layout.sharedHomePath,\n          effectiveHomePath,\n          operation: \"readDirectory\",\n          path: layout.sharedHomePath,\n          cause,\n        }),\n    }),\n  );\n  const entries = new Set<string>(KNOWN_SHARED_DIRECTORIES);\n  for (const entryName of sharedEntryNames) {\n    if (!PRIVATE_ENTRY_NAMES.has(entryName) && !SHADOW_LOCAL_ENTRY_NAMES.has(entryName)) {\n      entries.add(entryName);\n    }\n  }\n\n  yield* Effect.forEach(\n    PRIVATE_ENTRY_NAMES,\n    (entryName) =>\n      entryName === \"auth.json\"\n        ? Effect.void\n        : removePrivateSymlink({\n            fileSystem,\n            sharedHomePath: layout.sharedHomePath,\n            effectiveHomePath,\n            entryName,\n          }),\n    { discard: true },\n  );\n\n  yield* Effect.forEach(\n    entries,\n    (entryName) => {\n      if (PRIVATE_ENTRY_NAMES.has(entryName)) {\n        return Effect.void;\n      }\n      return ensureSymlink({\n        fileSystem,\n        sharedHomePath: layout.sharedHomePath,\n        effectiveHomePath,\n        entryName,\n      });\n    },\n    { discard: true },\n  );\n\n  yield* ensureShadowAuthIsPrivate({\n    fileSystem,\n    sharedHomePath: layout.sharedHomePath,\n    effectiveHomePath,\n  });\n});\n\nexport function codexContinuationIdentity(layout: CodexHomeLayout) {\n  return {\n    driverKind: ProviderDriverKind.make(\"codex\"),\n    continuationKey: layout.continuationKey,\n  };\n}\n","/**\n * Pure parsers for the provider CLIs' on-disk session transcripts.\n *\n * Both parsers are line-at-a-time reducers so callers can stream large files\n * without materialising them. Neither touches the filesystem.\n *\n * @module usageTranscripts\n */\nimport type { UsageProviderKind, UsageTokenTotals } from \"@t3tools/contracts\";\n\nexport interface UsageRecord {\n  readonly provider: UsageProviderKind;\n  readonly timestampMs: number;\n  readonly model: string;\n  readonly sessionId: string;\n  readonly totals: UsageTokenTotals;\n  readonly reportedCostUsd: number | null;\n  /**\n   * Key for cross-file de-duplication, or `null` when the record is inherently\n   * unique and needs no dedup.\n   */\n  readonly dedupeKey: string | null;\n}\n\nconst EMPTY_TOTALS: UsageTokenTotals = {\n  uncachedInputTokens: 0,\n  cachedInputTokens: 0,\n  cacheCreationTokens: 0,\n  outputTokens: 0,\n  reasoningTokens: 0,\n};\n\nfunction int(value: unknown): number {\n  return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;\n}\n\nfunction parseTimestampMs(value: unknown): number | null {\n  if (typeof value !== \"string\") return null;\n  const parsed = Date.parse(value);\n  return Number.isNaN(parsed) ? null : parsed;\n}\n\nexport function addTotals(a: UsageTokenTotals, b: UsageTokenTotals): UsageTokenTotals {\n  return {\n    uncachedInputTokens: a.uncachedInputTokens + b.uncachedInputTokens,\n    cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n    cacheCreationTokens: a.cacheCreationTokens + b.cacheCreationTokens,\n    outputTokens: a.outputTokens + b.outputTokens,\n    reasoningTokens: a.reasoningTokens + b.reasoningTokens,\n  };\n}\n\nexport function totalTokens(totals: UsageTokenTotals): number {\n  // reasoningTokens is a subset of outputTokens and must not be added again.\n  return (\n    totals.uncachedInputTokens +\n    totals.cachedInputTokens +\n    totals.cacheCreationTokens +\n    totals.outputTokens\n  );\n}\n\n/**\n * Cheap substring gate applied before `JSON.parse`.\n *\n * Transcripts are mostly tool output; only a minority of lines carry usage. On\n * a 30-day window this skips roughly half the lines outright and is worth about\n * an order of magnitude.\n */\nexport function mightCarryUsage(line: string, provider: UsageProviderKind): boolean {\n  return provider === \"claude\" ? line.includes('\"usage\"') : line.includes('\"token_count\"');\n}\n\n/* -------------------------------------------------------------------------- */\n/* Claude Code                                                                */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Parses one line of a Claude Code transcript.\n *\n * The provider CLI writes one record per assistant *content block*, and every\n * one of those records repeats the same complete `usage` object for the parent\n * message. Summing them overcounts by roughly 2.4x on a real workload, so the\n * caller must drop repeats by `dedupeKey` and keep the first.\n */\nexport function parseClaudeLine(line: string): UsageRecord | null {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(line);\n  } catch {\n    return null;\n  }\n  if (typeof parsed !== \"object\" || parsed === null) return null;\n\n  const record = parsed as Record<string, unknown>;\n  if (record[\"type\"] !== \"assistant\") return null;\n\n  const message = record[\"message\"];\n  if (typeof message !== \"object\" || message === null) return null;\n  const messageRecord = message as Record<string, unknown>;\n\n  const usage = messageRecord[\"usage\"];\n  if (typeof usage !== \"object\" || usage === null) return null;\n  const usageRecord = usage as Record<string, unknown>;\n\n  const timestampMs = parseTimestampMs(record[\"timestamp\"]);\n  if (timestampMs === null) return null;\n\n  const model = typeof messageRecord[\"model\"] === \"string\" ? messageRecord[\"model\"] : \"\";\n  if (model.length === 0) return null;\n\n  const messageId = typeof messageRecord[\"id\"] === \"string\" ? messageRecord[\"id\"] : null;\n  const requestId = typeof record[\"requestId\"] === \"string\" ? record[\"requestId\"] : null;\n  // Matches ccusage: prefer the message/request pair, fall back to whichever\n  // half exists. Records with neither cannot be de-duplicated.\n  const dedupeKey =\n    messageId === null && requestId === null ? null : `${messageId ?? \"\"}:${requestId ?? \"\"}`;\n\n  const cost = record[\"costUSD\"];\n\n  return {\n    provider: \"claude\",\n    timestampMs,\n    model,\n    sessionId: typeof record[\"sessionId\"] === \"string\" ? record[\"sessionId\"] : \"\",\n    totals: {\n      uncachedInputTokens: int(usageRecord[\"input_tokens\"]),\n      cachedInputTokens: int(usageRecord[\"cache_read_input_tokens\"]),\n      cacheCreationTokens: int(usageRecord[\"cache_creation_input_tokens\"]),\n      outputTokens: int(usageRecord[\"output_tokens\"]),\n      // Anthropic folds thinking tokens into output and does not break them out.\n      reasoningTokens: 0,\n    },\n    reportedCostUsd: typeof cost === \"number\" && Number.isFinite(cost) ? cost : null,\n    dedupeKey,\n  };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Codex                                                                      */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Rolling state for a single Codex rollout file.\n *\n * Codex `token_count` events carry no model, so the model is carried forward\n * from the most recent `turn_context`. Sessions that switch models mid-run\n * attribute correctly from the switch onward.\n */\nexport interface CodexScanState {\n  model: string;\n  sessionId: string;\n  lastUsageSignature: string | null;\n}\n\nexport function initialCodexScanState(): CodexScanState {\n  return { model: \"\", sessionId: \"\", lastUsageSignature: null };\n}\n\n/**\n * Feeds one line of a Codex rollout into `state`, returning a record when the\n * line was a usage event.\n *\n * Deltas come from `last_token_usage`. Summing those across a session\n * reconciles with the session's final `total_token_usage`, provided\n * consecutive duplicate events are dropped, which this does.\n */\nexport function parseCodexLine(line: string, state: CodexScanState): UsageRecord | null {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(line);\n  } catch {\n    return null;\n  }\n  if (typeof parsed !== \"object\" || parsed === null) return null;\n\n  const record = parsed as Record<string, unknown>;\n  const payload = record[\"payload\"];\n  if (typeof payload !== \"object\" || payload === null) return null;\n  const payloadRecord = payload as Record<string, unknown>;\n  const payloadType = payloadRecord[\"type\"];\n\n  if (record[\"type\"] === \"session_meta\") {\n    const id = payloadRecord[\"id\"] ?? payloadRecord[\"session_id\"];\n    if (typeof id === \"string\") state.sessionId = id;\n    return null;\n  }\n\n  if (record[\"type\"] === \"turn_context\") {\n    if (typeof payloadRecord[\"model\"] === \"string\") state.model = payloadRecord[\"model\"];\n    return null;\n  }\n\n  if (payloadType !== \"token_count\") return null;\n\n  const info = payloadRecord[\"info\"];\n  if (typeof info !== \"object\" || info === null) return null;\n  const last = (info as Record<string, unknown>)[\"last_token_usage\"];\n  if (typeof last !== \"object\" || last === null) return null;\n  const lastRecord = last as Record<string, unknown>;\n\n  // Only an event that is otherwise eligible may consume the duplicate\n  // signature. A token_count arriving before its turn_context (no model yet)\n  // must not poison it, or the re-emitted copy after the model is known would\n  // be skipped as a duplicate and those tokens never counted.\n  const timestampMs = parseTimestampMs(record[\"timestamp\"]);\n  if (timestampMs === null) return null;\n  if (state.model.length === 0) return null;\n\n  // Codex re-emits an unchanged token_count on some stream boundaries. Summing\n  // those would double count, so identical consecutive payloads are skipped.\n  const signature = JSON.stringify(lastRecord);\n  if (signature === state.lastUsageSignature) return null;\n  state.lastUsageSignature = signature;\n\n  const inputTokens = int(lastRecord[\"input_tokens\"]);\n  const cachedInputTokens = int(lastRecord[\"cached_input_tokens\"]);\n  const cacheCreationTokens = int(lastRecord[\"cache_write_input_tokens\"]);\n  const outputTokens = int(lastRecord[\"output_tokens\"]);\n\n  const totals: UsageTokenTotals = {\n    // Codex reports `input_tokens` inclusive of the cached portion.\n    uncachedInputTokens: Math.max(0, inputTokens - cachedInputTokens - cacheCreationTokens),\n    cachedInputTokens,\n    cacheCreationTokens,\n    outputTokens,\n    // Reported inside output_tokens, surfaced separately for the token mix.\n    reasoningTokens: Math.min(outputTokens, int(lastRecord[\"reasoning_output_tokens\"])),\n  };\n\n  if (totalTokens(totals) === 0) return null;\n\n  return {\n    provider: \"codex\",\n    timestampMs,\n    model: state.model,\n    sessionId: state.sessionId,\n    totals,\n    // Codex does not report cost in the rollout.\n    reportedCostUsd: null,\n    // Rollout files are unique per session, so events need no global dedup.\n    dedupeKey: null,\n  };\n}\n\nexport { EMPTY_TOTALS };\n","/**\n * Model rate lookup and cost arithmetic.\n *\n * Rates come from LiteLLM's `model_prices_and_context_window.json`, the same\n * table `ccusage` prices against. Everything here is pure: fetching and caching\n * the table lives in `UsageService`.\n *\n * @module usagePricing\n */\nimport type { UsageCostSource, UsageTokenTotals } from \"@t3tools/contracts\";\n\n/**\n * The subset of a LiteLLM entry we price against. All values are USD per token.\n *\n * LiteLLM also publishes tiered variants (`*_above_272k_tokens`, `*_flex`,\n * `*_priority`, `*_batches`). We deliberately price at the base tier: the\n * transcripts don't record which tier served a request, so anything else would\n * be a guess dressed up as precision.\n */\nexport interface ModelRate {\n  readonly inputCostPerToken: number;\n  readonly outputCostPerToken: number;\n  readonly cacheReadCostPerToken: number;\n  readonly cacheCreationCostPerToken: number;\n}\n\nexport type RateTable = ReadonlyMap<string, ModelRate>;\n\n/** Raw shape of one LiteLLM entry, narrowed to the fields we read. */\ninterface LiteLlmEntry {\n  readonly input_cost_per_token?: unknown;\n  readonly output_cost_per_token?: unknown;\n  readonly cache_read_input_token_cost?: unknown;\n  readonly cache_creation_input_token_cost?: unknown;\n}\n\nfunction finiteNumber(value: unknown): number | null {\n  return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\n/**\n * Projects the LiteLLM document into a rate table.\n *\n * Entries without both an input and an output rate are dropped: a half-priced\n * model would silently under-report cost, which is worse than reporting the\n * model as unpriced.\n */\nexport function parseRateTable(document: unknown): RateTable {\n  const table = new Map<string, ModelRate>();\n  if (typeof document !== \"object\" || document === null) return table;\n\n  for (const [name, raw] of Object.entries(document as Record<string, unknown>)) {\n    if (typeof raw !== \"object\" || raw === null) continue;\n    const entry = raw as LiteLlmEntry;\n    const input = finiteNumber(entry.input_cost_per_token);\n    const output = finiteNumber(entry.output_cost_per_token);\n    if (input === null || output === null) continue;\n\n    table.set(normalizeModelName(name), {\n      inputCostPerToken: input,\n      outputCostPerToken: output,\n      // Anthropic bills cache reads at a discount and cache writes at a\n      // premium. When a model omits them, cached input is priced as plain\n      // input rather than as free.\n      cacheReadCostPerToken: finiteNumber(entry.cache_read_input_token_cost) ?? input,\n      cacheCreationCostPerToken: finiteNumber(entry.cache_creation_input_token_cost) ?? input,\n    });\n  }\n  return table;\n}\n\n/**\n * Canonicalises a model name for lookup.\n *\n * Strips a `provider/` prefix (LiteLLM publishes both `claude-opus-5` and\n * `anthropic/claude-opus-5`) and lowercases, since transcripts are inconsistent\n * about casing.\n */\nexport function normalizeModelName(model: string): string {\n  const trimmed = model.trim().toLowerCase();\n  const slash = trimmed.lastIndexOf(\"/\");\n  return slash === -1 ? trimmed : trimmed.slice(slash + 1);\n}\n\n/**\n * Models we never price, regardless of the table.\n *\n * `<synthetic>` marks locally generated messages that were never billed. Bare\n * family names (\"opus\", \"sonnet\") are genuinely ambiguous across generations,\n * so we report them as unpriced instead of guessing a generation.\n */\nconst UNPRICEABLE_MODELS = new Set([\n  \"<synthetic>\",\n  \"synthetic\",\n  \"opus\",\n  \"sonnet\",\n  \"haiku\",\n  \"fable\",\n]);\n\nexport function lookupRate(table: RateTable, model: string): ModelRate | null {\n  const normalized = normalizeModelName(model);\n  if (normalized.length === 0 || UNPRICEABLE_MODELS.has(normalized)) return null;\n  return table.get(normalized) ?? null;\n}\n\nexport interface PricedUsage {\n  readonly costUsd: number;\n  readonly costSource: UsageCostSource;\n}\n\n/**\n * Prices a bucket's tokens.\n *\n * `reasoningTokens` is intentionally not charged separately: it is already\n * counted inside `outputTokens`.\n */\nexport function priceUsage(\n  table: RateTable,\n  model: string,\n  totals: UsageTokenTotals,\n  reportedCostUsd: number | null,\n): PricedUsage {\n  if (reportedCostUsd !== null && Number.isFinite(reportedCostUsd)) {\n    return { costUsd: reportedCostUsd, costSource: \"providerReported\" };\n  }\n\n  const rate = lookupRate(table, model);\n  if (rate === null) return { costUsd: 0, costSource: \"unpriced\" };\n\n  const costUsd =\n    totals.uncachedInputTokens * rate.inputCostPerToken +\n    totals.cachedInputTokens * rate.cacheReadCostPerToken +\n    totals.cacheCreationTokens * rate.cacheCreationCostPerToken +\n    totals.outputTokens * rate.outputCostPerToken;\n\n  return { costUsd, costSource: \"modelPriced\" };\n}\n\n/**\n * What the cached input would have cost at full input rates, minus what it\n * actually cost. Drives the \"cache savings\" figure.\n */\nexport function cacheSavingsUsd(table: RateTable, model: string, totals: UsageTokenTotals): number {\n  const rate = lookupRate(table, model);\n  if (rate === null) return 0;\n  return totals.cachedInputTokens * (rate.inputCostPerToken - rate.cacheReadCostPerToken);\n}\n","// @effect-diagnostics globalDate:off\n/**\n * Folds parsed transcript records into `(day, provider, model)` buckets.\n *\n * `Intl.DateTimeFormat` is the only reliable way to resolve a wall-clock day in\n * an arbitrary IANA zone, and it takes a `Date`. That is why the raw `Date`\n * construction is allowed here; nothing in this module reads the clock.\n *\n * Pure, so the bucketing and de-duplication rules are testable without touching\n * the filesystem or the network.\n *\n * @module usageAggregation\n */\nimport type { UsageBucket, UsageDay, UsageTokenTotals } from \"@t3tools/contracts\";\n\nimport { addTotals, EMPTY_TOTALS, type UsageRecord } from \"./usageTranscripts.ts\";\nimport { cacheSavingsUsd, priceUsage, type RateTable } from \"./usagePricing.ts\";\n\n/**\n * Formats an instant as a `YYYY-MM-DD` day in `timeZone`.\n *\n * `en-CA` yields ISO-ordered parts, which is why it is used here rather than\n * assembling the day from `Date` getters (those are host-local only).\n */\nexport function makeDayFormatter(timeZone: string): (timestampMs: number) => string {\n  let format: Intl.DateTimeFormat;\n  try {\n    format = new Intl.DateTimeFormat(\"en-CA\", {\n      timeZone,\n      year: \"numeric\",\n      month: \"2-digit\",\n      day: \"2-digit\",\n    });\n  } catch {\n    // An unknown zone should degrade to UTC rather than fail the whole scan.\n    format = new Intl.DateTimeFormat(\"en-CA\", {\n      timeZone: \"UTC\",\n      year: \"numeric\",\n      month: \"2-digit\",\n      day: \"2-digit\",\n    });\n  }\n  return (timestampMs) => format.format(new Date(timestampMs));\n}\n\ninterface MutableBucket {\n  totals: UsageTokenTotals;\n  costUsd: number;\n  cacheSavingsUsd: number;\n  records: number;\n  unpricedRecords: number;\n  providerReportedRecords: number;\n  sessions: Set<string>;\n}\n\nexport interface AggregateOptions {\n  readonly timeZone: string;\n  readonly sinceDay: string;\n  readonly untilDay: string;\n  readonly rates: RateTable;\n}\n\nexport interface AggregateResult {\n  readonly buckets: readonly UsageBucket[];\n  /** Records dropped because an earlier record carried the same dedupe key. */\n  readonly duplicatesDropped: number;\n  /** Records whose day fell outside the requested window. */\n  readonly outOfWindow: number;\n}\n\n/**\n * Accumulates records across many files.\n *\n * De-duplication is global across the whole scan, not per file: Claude Code\n * copies a message's records forward when a session is resumed or forked, so\n * the same `dedupeKey` legitimately appears in several transcripts.\n */\nexport class UsageAggregator {\n  readonly #buckets = new Map<string, MutableBucket>();\n  readonly #seen = new Set<string>();\n  readonly #toDay: (timestampMs: number) => string;\n  readonly #options: AggregateOptions;\n  #duplicatesDropped = 0;\n  #outOfWindow = 0;\n\n  constructor(options: AggregateOptions) {\n    this.#options = options;\n    this.#toDay = makeDayFormatter(options.timeZone);\n  }\n\n  /**\n   * Folds one record in. Returns whether it actually contributed, so callers\n   * can derive per-window facts (distinct sessions, for one) from the records\n   * that landed rather than everything the mtime prefilter happened to admit.\n   */\n  add(record: UsageRecord): boolean {\n    if (record.dedupeKey !== null) {\n      if (this.#seen.has(record.dedupeKey)) {\n        this.#duplicatesDropped += 1;\n        return false;\n      }\n      this.#seen.add(record.dedupeKey);\n    }\n\n    const day = this.#toDay(record.timestampMs);\n    if (day < this.#options.sinceDay || day > this.#options.untilDay) {\n      this.#outOfWindow += 1;\n      return false;\n    }\n\n    const key = `${day}\u0000${record.provider}\u0000${record.model}`;\n    let bucket = this.#buckets.get(key);\n    if (bucket === undefined) {\n      bucket = {\n        totals: EMPTY_TOTALS,\n        costUsd: 0,\n        cacheSavingsUsd: 0,\n        records: 0,\n        unpricedRecords: 0,\n        providerReportedRecords: 0,\n        sessions: new Set<string>(),\n      };\n      this.#buckets.set(key, bucket);\n    }\n\n    const priced = priceUsage(\n      this.#options.rates,\n      record.model,\n      record.totals,\n      record.reportedCostUsd,\n    );\n\n    bucket.totals = addTotals(bucket.totals, record.totals);\n    bucket.costUsd += priced.costUsd;\n    bucket.cacheSavingsUsd += cacheSavingsUsd(this.#options.rates, record.model, record.totals);\n    bucket.records += 1;\n    if (priced.costSource === \"unpriced\") bucket.unpricedRecords += 1;\n    if (priced.costSource === \"providerReported\") bucket.providerReportedRecords += 1;\n    if (record.sessionId.length > 0) bucket.sessions.add(record.sessionId);\n    return true;\n  }\n\n  finish(): AggregateResult {\n    const buckets: UsageBucket[] = [];\n    for (const [key, bucket] of this.#buckets) {\n      const [day = \"\", provider = \"\", model = \"\"] = key.split(\"\u0000\");\n      buckets.push({\n        day: day as UsageDay,\n        provider: provider as UsageBucket[\"provider\"],\n        model,\n        totals: bucket.totals,\n        costUsd: bucket.costUsd,\n        cacheSavingsUsd: bucket.cacheSavingsUsd,\n        costSource: resolveCostSource(bucket),\n        records: bucket.records,\n        unpricedRecords: bucket.unpricedRecords,\n        sessions: bucket.sessions.size,\n      });\n    }\n    // Stable ordering keeps payloads diffable and snapshot tests meaningful.\n    buckets.sort(\n      (a, b) =>\n        a.day.localeCompare(b.day) ||\n        a.provider.localeCompare(b.provider) ||\n        a.model.localeCompare(b.model),\n    );\n\n    return {\n      buckets,\n      duplicatesDropped: this.#duplicatesDropped,\n      outOfWindow: this.#outOfWindow,\n    };\n  }\n}\n\n/**\n * A bucket mixes records from one model, but their cost provenance can differ\n * when only some records carried a reported cost. The weakest provenance in the\n * bucket wins so the UI never overstates confidence.\n */\nfunction resolveCostSource(bucket: MutableBucket): UsageBucket[\"costSource\"] {\n  if (bucket.unpricedRecords === bucket.records) return \"unpriced\";\n  if (bucket.providerReportedRecords === bucket.records) return \"providerReported\";\n  return \"modelPriced\";\n}\n","// @effect-diagnostics nodeBuiltinImport:off\n/**\n * Raw filesystem access for transcript scanning.\n *\n * Isolated here so the rest of the usage code stays on Effect's `FileSystem`.\n * The direct `node:fs` streaming is deliberate: a cold 30-day window is ~1.4 GB\n * across ~1,500 files, and `readline` over a read stream is roughly an order of\n * magnitude cheaper than materialising each file. The equivalent Effect stream\n * pipeline is idiomatic but not fast enough to sit behind a page load.\n *\n * @module usageTranscriptReader\n */\nimport * as NodeFS from \"node:fs\";\nimport * as NodeFSP from \"node:fs/promises\";\nimport * as NodePath from \"node:path\";\nimport * as NodeReadline from \"node:readline\";\n\nimport type { UsageProviderKind } from \"@t3tools/contracts\";\n\nimport {\n  initialCodexScanState,\n  mightCarryUsage,\n  parseClaudeLine,\n  parseCodexLine,\n  type UsageRecord,\n} from \"./usageTranscripts.ts\";\n\nexport interface TranscriptFile {\n  readonly path: string;\n  readonly size: number;\n  readonly mtimeMs: number;\n}\n\n/**\n * Lists `.jsonl` transcripts under `root` last modified at or after `sinceMs`.\n *\n * Errors on individual entries are swallowed: session files rotate and get\n * removed while the walk is in flight, and a partial listing is far better than\n * failing the page.\n */\nexport async function listTranscriptFiles(\n  root: string,\n  sinceMs: number,\n): Promise<readonly TranscriptFile[]> {\n  const found: TranscriptFile[] = [];\n\n  const walk = async (dir: string): Promise<void> => {\n    let entries;\n    try {\n      entries = await NodeFSP.readdir(dir, { withFileTypes: true });\n    } catch {\n      return;\n    }\n    for (const entry of entries) {\n      const child = NodePath.join(dir, entry.name);\n      if (entry.isDirectory()) {\n        await walk(child);\n        continue;\n      }\n      if (!entry.name.endsWith(\".jsonl\")) continue;\n      try {\n        const stats = await NodeFSP.stat(child);\n        if (stats.mtimeMs >= sinceMs) {\n          found.push({ path: child, size: stats.size, mtimeMs: stats.mtimeMs });\n        }\n      } catch {\n        // Vanished between readdir and stat.\n      }\n    }\n  };\n\n  await walk(root);\n  return found;\n}\n\n/**\n * Filesystem identity of a directory, as `device:inode`.\n *\n * Used to tell \"two servers reading the same transcript directory\" apart from\n * \"two machines whose hostname and home path happen to match\". Returns an empty\n * string when the directory cannot be stat'd.\n */\nexport async function readDirectoryVolumeId(path: string): Promise<string> {\n  try {\n    const stats = await NodeFSP.stat(path);\n    return `${stats.dev}:${stats.ino}`;\n  } catch {\n    return \"\";\n  }\n}\n\n/**\n * Streams one transcript and returns the usage records it contains, or `null`\n * when the file could not be read.\n *\n * The distinction matters to the caller's cache: a genuinely empty transcript\n * is a stable fact worth memoising, while a transient read failure memoised\n * under the same `(size, mtime)` key would silently drop that file's usage\n * until the file next changes.\n *\n * Codex carries the active model on `turn_context` lines that hold no usage of\n * their own, so those still have to pass through the reducer to keep model\n * attribution correct.\n */\nexport async function readTranscriptRecords(\n  filePath: string,\n  provider: UsageProviderKind,\n): Promise<readonly UsageRecord[] | null> {\n  const records: UsageRecord[] = [];\n  const codexState = initialCodexScanState();\n\n  try {\n    const lines = NodeReadline.createInterface({\n      input: NodeFS.createReadStream(filePath, { encoding: \"utf8\" }),\n      crlfDelay: Infinity,\n    });\n\n    for await (const line of lines) {\n      if (provider === \"codex\") {\n        if (\n          !mightCarryUsage(line, provider) &&\n          !line.includes('\"turn_context\"') &&\n          !line.includes('\"session_meta\"')\n        ) {\n          continue;\n        }\n        const record = parseCodexLine(line, codexState);\n        if (record !== null) records.push(record);\n        continue;\n      }\n\n      if (!mightCarryUsage(line, provider)) continue;\n      const record = parseClaudeLine(line);\n      if (record !== null) records.push(record);\n    }\n  } catch {\n    return null;\n  }\n\n  return records;\n}\n","/**\n * Durable per-file scan cache.\n *\n * Transcripts are append-only and a file that has not changed can never yield\n * different usage, so parsed records are keyed by `(size, mtime)` and reused.\n * Without this every server restart re-parses the whole window: roughly 3.5s\n * for a 30-day scan here, against ~11ms to reload this cache.\n *\n * Caching *per file* rather than per day is deliberate. It is timezone\n * independent, so changing the reporting zone does not invalidate anything, and\n * it keeps cross-file de-duplication exact: cached entries are de-duplicated\n * within their own file only, and the aggregator still applies the global\n * dedupe pass over the small surviving key set.\n *\n * @module usageScanCache\n */\nimport type { UsageProviderKind } from \"@t3tools/contracts\";\n\nimport type { UsageRecord } from \"./usageTranscripts.ts\";\n\nexport const USAGE_SCAN_CACHE_VERSION = 1 as const;\n\nexport interface CachedFile {\n  readonly size: number;\n  readonly mtimeMs: number;\n  readonly provider: UsageProviderKind;\n  readonly records: readonly UsageRecord[];\n}\n\nexport type ScanCache = Map<string, CachedFile>;\n\n/**\n * Row layout for the serialised form. Positional and interned rather than\n * object-per-record: on a 30-day window that is the difference between a file\n * measured in tens of megabytes and one under six.\n */\ntype SerializedRecord = readonly [\n  timestampMs: number,\n  modelIndex: number,\n  sessionIndex: number,\n  uncachedInputTokens: number,\n  cachedInputTokens: number,\n  cacheCreationTokens: number,\n  outputTokens: number,\n  reasoningTokens: number,\n  dedupeKey: string | null,\n  reportedCostUsd: number | null,\n];\n\ninterface SerializedFile {\n  readonly s: number;\n  readonly m: number;\n  readonly p: UsageProviderKind;\n  readonly r: readonly SerializedRecord[];\n}\n\ninterface SerializedCache {\n  readonly version: number;\n  readonly models: readonly string[];\n  readonly sessions: readonly string[];\n  readonly files: Readonly<Record<string, SerializedFile>>;\n}\n\n/** Serialises the cache, interning the repeated model and session strings. */\nexport function encodeScanCache(cache: ScanCache): SerializedCache {\n  const models: string[] = [];\n  const sessions: string[] = [];\n  const modelIndex = new Map<string, number>();\n  const sessionIndex = new Map<string, number>();\n\n  const intern = (table: string[], index: Map<string, number>, value: string): number => {\n    const existing = index.get(value);\n    if (existing !== undefined) return existing;\n    const next = table.length;\n    table.push(value);\n    index.set(value, next);\n    return next;\n  };\n\n  const files: Record<string, SerializedFile> = {};\n  for (const [path, entry] of cache) {\n    files[path] = {\n      s: entry.size,\n      m: entry.mtimeMs,\n      p: entry.provider,\n      r: entry.records.map((record) => [\n        record.timestampMs,\n        intern(models, modelIndex, record.model),\n        intern(sessions, sessionIndex, record.sessionId),\n        record.totals.uncachedInputTokens,\n        record.totals.cachedInputTokens,\n        record.totals.cacheCreationTokens,\n        record.totals.outputTokens,\n        record.totals.reasoningTokens,\n        record.dedupeKey,\n        record.reportedCostUsd,\n      ]),\n    };\n  }\n\n  return { version: USAGE_SCAN_CACHE_VERSION, models, sessions, files };\n}\n\nfunction isRecordArray(value: unknown): value is readonly unknown[] {\n  return Array.isArray(value);\n}\n\n/**\n * Rebuilds the cache from a parsed document.\n *\n * Anything malformed yields an empty cache rather than an error: a corrupt\n * cache should cost one cold scan, never a broken page.\n */\nexport function decodeScanCache(document: unknown): ScanCache {\n  const cache: ScanCache = new Map();\n  if (typeof document !== \"object\" || document === null) return cache;\n\n  const root = document as Partial<SerializedCache>;\n  if (root.version !== USAGE_SCAN_CACHE_VERSION) return cache;\n  if (!isRecordArray(root.models) || !isRecordArray(root.sessions)) return cache;\n  if (typeof root.files !== \"object\" || root.files === null) return cache;\n\n  // The intern tables must be all strings: a numeric entry would pass the\n  // undefined guard below, land in a record's model, and crash the aggregate\n  // at normalizeModelName. A corrupt table rejects the whole cache.\n  if (!root.models.every((value) => typeof value === \"string\")) return cache;\n  if (!root.sessions.every((value) => typeof value === \"string\")) return cache;\n  const models = root.models as readonly string[];\n  const sessions = root.sessions as readonly string[];\n\n  for (const [path, raw] of Object.entries(root.files)) {\n    if (typeof raw !== \"object\" || raw === null) continue;\n    const entry = raw as Partial<SerializedFile>;\n    if (typeof entry.s !== \"number\" || typeof entry.m !== \"number\") continue;\n    if (entry.p !== \"claude\" && entry.p !== \"codex\") continue;\n    if (!isRecordArray(entry.r)) continue;\n\n    const provider: UsageProviderKind = entry.p;\n    const records: UsageRecord[] = [];\n    // Any corrupt row disqualifies the whole entry. Keeping the survivors\n    // under the original (size, mtime) would read as a valid warm hit and the\n    // file would never be re-parsed, silently losing the dropped rows' usage.\n    let corrupt = false;\n    for (const row of entry.r) {\n      if (!isRecordArray(row) || row.length < 10) {\n        corrupt = true;\n        break;\n      }\n      const [\n        timestampMs,\n        modelIndex,\n        sessionIndex,\n        uncached,\n        cached,\n        cacheCreation,\n        output,\n        reasoning,\n        dedupeKey,\n        reportedCostUsd,\n      ] = row as SerializedRecord;\n\n      const model = typeof modelIndex === \"number\" ? models[modelIndex] : undefined;\n      if (\n        typeof timestampMs !== \"number\" ||\n        !Number.isFinite(timestampMs) ||\n        model === undefined ||\n        !Number.isFinite(uncached) ||\n        !Number.isFinite(cached) ||\n        !Number.isFinite(cacheCreation) ||\n        !Number.isFinite(output) ||\n        !Number.isFinite(reasoning)\n      ) {\n        corrupt = true;\n        break;\n      }\n\n      records.push({\n        provider,\n        timestampMs,\n        model,\n        sessionId: (typeof sessionIndex === \"number\" ? sessions[sessionIndex] : undefined) ?? \"\",\n        totals: {\n          uncachedInputTokens: uncached,\n          cachedInputTokens: cached,\n          cacheCreationTokens: cacheCreation,\n          outputTokens: output,\n          reasoningTokens: reasoning,\n        },\n        reportedCostUsd: typeof reportedCostUsd === \"number\" ? reportedCostUsd : null,\n        dedupeKey: typeof dedupeKey === \"string\" ? dedupeKey : null,\n      });\n    }\n\n    if (corrupt) continue;\n    cache.set(path, { size: entry.s, mtimeMs: entry.m, provider, records });\n  }\n\n  return cache;\n}\n\nexport interface PruneOptions {\n  /** Files the walk just saw. Only meaningful inside the walked window. */\n  readonly livePaths: ReadonlySet<string>;\n  /**\n   * Roots the walk actually completed. Absence from `livePaths` only proves a\n   * file is gone when its root was walked: a provider whose directory failed to\n   * resolve this pass must not have its warm entries purged.\n   */\n  readonly walkedRoots: readonly string[];\n  /** Start of the walked window; entries older than this were not looked for. */\n  readonly windowStartMs: number;\n  /** Entries older than this are dropped regardless. */\n  readonly retentionCutoffMs: number;\n}\n\n/**\n * Drops aged-out entries, and entries for files that have disappeared.\n *\n * The walk only covers the requested window, so absence from `livePaths` only\n * proves deletion for entries *inside* that window. Pruning everything the walk\n * missed would evict the 30-day entries every time someone looked at 7 days.\n *\n * Replaces an earlier record cap that cleared the whole cache once exceeded,\n * which meant a large enough window never warmed up at all.\n */\nexport function pruneScanCache(cache: ScanCache, options: PruneOptions): number {\n  let removed = 0;\n  for (const [path, entry] of cache) {\n    const agedOut = entry.mtimeMs < options.retentionCutoffMs;\n    const underWalkedRoot = options.walkedRoots.some((root) => path.startsWith(root));\n    const deleted =\n      underWalkedRoot && entry.mtimeMs >= options.windowStartMs && !options.livePaths.has(path);\n    if (agedOut || deleted) {\n      cache.delete(path);\n      removed += 1;\n    }\n  }\n  return removed;\n}\n\n/** Within-file de-duplication, applied before an entry is cached. */\nexport function dedupeWithinFile(records: readonly UsageRecord[]): readonly UsageRecord[] {\n  const seen = new Set<string>();\n  const kept: UsageRecord[] = [];\n  for (const record of records) {\n    if (record.dedupeKey !== null) {\n      if (seen.has(record.dedupeKey)) continue;\n      seen.add(record.dedupeKey);\n    }\n    kept.push(record);\n  }\n  return kept;\n}\n","/**\n * UsageService - scans provider transcripts and returns priced daily usage.\n *\n * The scan reads the provider CLIs' own session files rather than Synaptic\n * Code's orchestration projections, so usage covers turns driven outside\n * Synaptic Code too.\n * This is the approach `ccusage` takes.\n *\n * Transcripts are append-only, so parsed records are memoised per file by\n * `(size, mtime)`. A cold 30-day scan of ~1.4 GB lands around 2-3 seconds; warm\n * scans only reparse files that changed.\n *\n * @module UsageService\n */\nimport * as NodeOS from \"node:os\";\n\nimport {\n  USAGE_CONTRACT_VERSION,\n  type UsageProviderKind,\n  type UsageSource,\n  type UsageSummary,\n  type UsageSummaryInput,\n  UsageReadError,\n} from \"@t3tools/contracts\";\nimport * as Cause from \"effect/Cause\";\nimport * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient, HttpClientResponse } from \"effect/unstable/http\";\n\nimport { ServerConfig } from \"../config.ts\";\nimport * as ServerSettings from \"../serverSettings.ts\";\nimport { resolveClaudeHomePath } from \"../provider/Drivers/ClaudeHome.ts\";\nimport { resolveCodexHomeLayout } from \"../provider/Drivers/CodexHomeLayout.ts\";\nimport { UsageAggregator } from \"./usageAggregation.ts\";\nimport { parseRateTable, type RateTable } from \"./usagePricing.ts\";\nimport {\n  listTranscriptFiles,\n  readDirectoryVolumeId,\n  readTranscriptRecords,\n} from \"./usageTranscriptReader.ts\";\nimport {\n  decodeScanCache,\n  dedupeWithinFile,\n  encodeScanCache,\n  pruneScanCache,\n  type ScanCache,\n} from \"./usageScanCache.ts\";\nimport type { UsageRecord } from \"./usageTranscripts.ts\";\n\nconst LITELLM_RATES_URL =\n  \"https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json\";\n\n/** Rates move rarely; a day-old table keeps the page working offline. */\nconst RATES_TTL_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Files are filtered by mtime before opening. The slack covers a session whose\n * last write lands just before local midnight on the window's first day.\n */\nconst MTIME_SLACK_MS = 36 * 60 * 60 * 1000;\n\n/** Longest window the UI offers, plus slack. Older entries are pruned. */\nconst CACHE_RETENTION_DAYS = 90;\n\n/** On-disk shape of the rate snapshot. */\nconst RatesCacheFile = Schema.Struct({\n  fetchedAtMs: Schema.Number,\n  document: Schema.Unknown,\n});\nconst decodeRatesCache = Schema.decodeUnknownEffect(\n  Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),\n);\nconst encodeRatesCache = Schema.encodeEffect(\n  Schema.fromJsonString(RatesCacheFile as unknown as Schema.Codec<typeof RatesCacheFile.Type>),\n);\n\n/** The scan cache is narrowed by hand in `usageScanCache`, so JSON is enough here. */\nconst ScanCacheJson = Schema.fromJsonString(Schema.Unknown as unknown as Schema.Codec<unknown>);\nconst decodeScanCacheFile = Schema.decodeUnknownEffect(ScanCacheJson);\nconst encodeScanCacheFile = Schema.encodeEffect(ScanCacheJson);\n\nexport class UsageService extends Context.Service<\n  UsageService,\n  {\n    readonly readSummary: (input: UsageSummaryInput) => Effect.Effect<UsageSummary, UsageReadError>;\n  }\n>()(\"t3/usage/UsageService\") {}\n\n/** Empty summary, for suites that only need the RPC surface to resolve. */\nexport const layerTest = Layer.succeed(\n  UsageService,\n  UsageService.of({\n    readSummary: (input) =>\n      Effect.succeed({\n        contractVersion: USAGE_CONTRACT_VERSION,\n        readAt: \"1970-01-01T00:00:00.000Z\",\n        timeZone: input.timeZone,\n        sinceDay: input.sinceDay,\n        untilDay: input.untilDay,\n        buckets: [],\n        sources: [],\n        pricing: {\n          status: \"unavailable\",\n          source: LITELLM_RATES_URL,\n          fetchedAt: null,\n          knownModels: 0,\n        },\n        scanDurationMs: 0,\n      }),\n  }),\n);\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const config = yield* ServerConfig;\n  const settingsService = yield* ServerSettings.ServerSettingsService;\n  const httpClient = yield* HttpClient.HttpClient;\n\n  const fileCache: ScanCache = new Map();\n  let cacheDirty = false;\n\n  const ratesCachePath = path.join(config.stateDir, \"usage-model-rates.json\");\n  const scanCachePath = path.join(config.stateDir, \"usage-scan-cache.json\");\n  let rates: RateTable = new Map();\n  let ratesFetchedAtMs: number | null = null;\n  let ratesStatus: UsageSummary[\"pricing\"][\"status\"] = \"unavailable\";\n\n  /**\n   * Loads the LiteLLM rate table, preferring a fresh copy and falling back to\n   * the on-disk snapshot. With neither, every model reports as unpriced rather\n   * than the page failing.\n   */\n  const ensureRates = Effect.fn(\"UsageService.ensureRates\")(function* () {\n    const now = yield* Clock.currentTimeMillis;\n    if (ratesFetchedAtMs !== null && now - ratesFetchedAtMs < RATES_TTL_MS) return;\n\n    if (ratesFetchedAtMs === null) {\n      const fromDisk = yield* fileSystem.readFileString(ratesCachePath).pipe(\n        Effect.flatMap((raw) => decodeRatesCache(raw)),\n        Effect.catchCause(() => Effect.succeed(null)),\n      );\n      if (fromDisk !== null) {\n        const parsed = parseRateTable(fromDisk.document);\n        if (parsed.size > 0) {\n          rates = parsed;\n          ratesFetchedAtMs = fromDisk.fetchedAtMs;\n          ratesStatus = \"cached\";\n          if (now - fromDisk.fetchedAtMs < RATES_TTL_MS) return;\n        }\n      }\n    }\n\n    const fetched = yield* httpClient.get(LITELLM_RATES_URL).pipe(\n      Effect.flatMap(HttpClientResponse.filterStatusOk),\n      Effect.flatMap((response) => response.json),\n      Effect.timeout(10_000),\n      Effect.catchCause(() => Effect.succeed(null)),\n    );\n    if (fetched === null) {\n      // The refresh failed; whatever we are serving is now past its TTL and\n      // must not keep claiming to be fresh.\n      if (rates.size > 0) ratesStatus = \"cached\";\n      return;\n    }\n\n    const parsed = parseRateTable(fetched);\n    if (parsed.size === 0) return;\n\n    rates = parsed;\n    ratesFetchedAtMs = now;\n    ratesStatus = \"fresh\";\n\n    yield* encodeRatesCache({ fetchedAtMs: now, document: fetched }).pipe(\n      Effect.flatMap((serialized) => fileSystem.writeFileString(ratesCachePath, serialized)),\n      Effect.catchCause(() => Effect.void),\n    );\n  });\n\n  /**\n   * Claude's config dir is the home itself when overridden, but a default\n   * install nests transcripts under `~/.claude/projects`. Probe both.\n   */\n  const resolveClaudeTranscriptDir = (homePath: string) =>\n    Effect.gen(function* () {\n      const nested = path.join(homePath, \".claude\", \"projects\");\n      const nestedExists = yield* fileSystem\n        .exists(nested)\n        .pipe(Effect.catchCause(() => Effect.succeed(false)));\n      return nestedExists ? nested : path.join(homePath, \"projects\");\n    });\n\n  /** Resolves the transcript directory for each provider. */\n  const resolveTranscriptDirs = Effect.fn(\"UsageService.resolveTranscriptDirs\")(function* () {\n    // A settings failure must surface as an error: swallowing it here would\n    // present \"zero usage from every provider\" as a valid answer.\n    const settings = yield* settingsService.getSettings.pipe(\n      Effect.catchCause(\n        (cause) =>\n          new UsageReadError({\n            reason: \"scanFailed\",\n            // Bounded description; the squashed failure travels as the cause.\n            // Squashed, not the Cause tree: a full tree in a Defect field is\n            // the unbounded wire payload the bounded detail exists to avoid.\n            detail: \"Server settings could not be read.\",\n            cause: Cause.squash(cause),\n          }),\n      ),\n    );\n\n    const claudeHome = yield* resolveClaudeHomePath(settings.providers.claudeAgent);\n    const claudeDir = yield* resolveClaudeTranscriptDir(claudeHome);\n    const codexLayout = yield* resolveCodexHomeLayout(settings.providers.codex);\n\n    return [\n      { provider: \"claude\" as const, dir: claudeDir },\n      { provider: \"codex\" as const, dir: path.join(codexLayout.sharedHomePath, \"sessions\") },\n    ];\n  });\n\n  /**\n   * Loads the persisted scan cache exactly once per process.\n   *\n   * `Effect.cached` makes concurrent first readers await the same load rather\n   * than each seeing a \"loaded\" flag set before the read finished and cold\n   * scanning against an empty cache.\n   */\n  const ensureScanCacheLoaded = yield* Effect.cached(\n    Effect.gen(function* () {\n      const document = yield* fileSystem.readFileString(scanCachePath).pipe(\n        Effect.flatMap((raw) => decodeScanCacheFile(raw)),\n        Effect.catchCause(() => Effect.succeed(null)),\n      );\n      if (document === null) return;\n      for (const [path, entry] of decodeScanCache(document)) fileCache.set(path, entry);\n    }),\n  );\n\n  const persistScanCache = Effect.fn(\"UsageService.persistScanCache\")(function* () {\n    if (!cacheDirty) return;\n    // Cleared only after the write lands, so a failed persist is retried on\n    // the next scan instead of leaving disk permanently stale.\n    yield* encodeScanCacheFile(encodeScanCache(fileCache)).pipe(\n      Effect.flatMap((serialized) => fileSystem.writeFileString(scanCachePath, serialized)),\n      Effect.map(() => {\n        cacheDirty = false;\n      }),\n      // A cache we cannot write is a slower next start, not a failed read.\n      Effect.catchCause(() => Effect.void),\n    );\n  });\n\n  /** Parses one transcript, reusing the cached result when it is unchanged. */\n  const readFileRecords = (\n    filePath: string,\n    size: number,\n    mtimeMs: number,\n    provider: UsageProviderKind,\n  ): Effect.Effect<readonly UsageRecord[]> =>\n    Effect.gen(function* () {\n      const cached = fileCache.get(filePath);\n      // Provider is part of the identity: if both providers were ever pointed\n      // at one directory, a hit parsed by the other parser must not be reused.\n      if (\n        cached &&\n        cached.size === size &&\n        cached.mtimeMs === mtimeMs &&\n        cached.provider === provider\n      ) {\n        return cached.records;\n      }\n\n      const parsed = yield* Effect.promise(() => readTranscriptRecords(filePath, provider));\n      // A read failure is not an empty transcript: caching it under this\n      // (size, mtime) would silently drop the file's usage until it changes.\n      if (parsed === null) return [];\n      // Stored already de-duplicated within the file, which is 99% of all\n      // duplicates. The aggregator still runs the cross-file dedupe pass.\n      const records = dedupeWithinFile(parsed);\n\n      fileCache.set(filePath, { size, mtimeMs, provider, records });\n      cacheDirty = true;\n      return records;\n    });\n\n  const readSummary = Effect.fn(\"UsageService.readSummary\")(function* (input: UsageSummaryInput) {\n    if (input.sinceDay > input.untilDay) {\n      return yield* new UsageReadError({\n        reason: \"invalidWindow\",\n        detail: `sinceDay '${input.sinceDay}' is after untilDay '${input.untilDay}'`,\n      });\n    }\n\n    const startedAtMs = yield* Clock.currentTimeMillis;\n    yield* ensureRates();\n    yield* ensureScanCacheLoaded;\n\n    const hostId = NodeOS.hostname();\n    // The home resolvers ask for `Path` themselves; satisfy them from the\n    // instance we already hold so `readSummary` stays context-free.\n    const dirs = yield* resolveTranscriptDirs().pipe(Effect.provideService(Path.Path, path));\n    const windowStart = DateTime.make(`${input.sinceDay}T00:00:00Z`);\n    if (Option.isNone(windowStart)) {\n      return yield* new UsageReadError({\n        reason: \"invalidWindow\",\n        detail: `sinceDay '${input.sinceDay}' is not a valid date`,\n      });\n    }\n    const windowStartMs = DateTime.toEpochMillis(windowStart.value) - MTIME_SLACK_MS;\n\n    const aggregator = new UsageAggregator({\n      timeZone: input.timeZone,\n      sinceDay: input.sinceDay,\n      untilDay: input.untilDay,\n      rates,\n    });\n\n    const sources: UsageSource[] = [];\n    const livePaths = new Set<string>();\n    const walkedRoots: string[] = [];\n\n    for (const { provider, dir } of dirs) {\n      const volumeId = yield* Effect.promise(() => readDirectoryVolumeId(dir));\n      const exists = yield* fileSystem\n        .exists(dir)\n        .pipe(Effect.catchCause(() => Effect.succeed(false)));\n\n      if (!exists) {\n        sources.push({\n          fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },\n          status: \"missing\",\n          scannedFiles: 0,\n          skippedFiles: 0,\n          malformedRecords: 0,\n          distinctSessions: 0,\n          message: \"No transcript directory on this environment.\",\n        });\n        continue;\n      }\n\n      walkedRoots.push(dir);\n      const files = yield* Effect.promise(() => listTranscriptFiles(dir, windowStartMs));\n      let scannedFiles = 0;\n      let skippedFiles = 0;\n      // Distinct per directory. Buckets carry per-cell session counts, but a\n      // session spans days and models, so clients total this figure instead.\n      const sessionIds = new Set<string>();\n\n      for (const file of files) {\n        livePaths.add(file.path);\n        const records = yield* readFileRecords(file.path, file.size, file.mtimeMs, provider);\n        if (records.length === 0) {\n          skippedFiles += 1;\n          continue;\n        }\n        scannedFiles += 1;\n        for (const record of records) {\n          // Only sessions that contributed in-window count: the mtime slack\n          // admits boundary files whose records fall outside the range.\n          if (aggregator.add(record) && record.sessionId.length > 0) {\n            sessionIds.add(record.sessionId);\n          }\n        }\n      }\n\n      sources.push({\n        fingerprint: { hostId, provider, resolvedHomePath: dir, volumeId },\n        status: \"ok\",\n        scannedFiles,\n        skippedFiles,\n        malformedRecords: 0,\n        distinctSessions: sessionIds.size,\n        message: null,\n      });\n    }\n\n    const pruned = pruneScanCache(fileCache, {\n      livePaths,\n      walkedRoots,\n      windowStartMs,\n      retentionCutoffMs: startedAtMs - CACHE_RETENTION_DAYS * 24 * 60 * 60 * 1000,\n    });\n    if (pruned > 0) cacheDirty = true;\n    yield* persistScanCache();\n\n    const aggregated = aggregator.finish();\n    const readAt = yield* DateTime.now;\n    const finishedAtMs = yield* Clock.currentTimeMillis;\n\n    return {\n      contractVersion: USAGE_CONTRACT_VERSION,\n      readAt: DateTime.formatIso(readAt),\n      timeZone: input.timeZone,\n      sinceDay: input.sinceDay,\n      untilDay: input.untilDay,\n      buckets: aggregated.buckets,\n      sources,\n      pricing: {\n        status: ratesStatus,\n        source: LITELLM_RATES_URL,\n        fetchedAt:\n          ratesFetchedAtMs === null\n            ? null\n            : DateTime.formatIso(DateTime.makeUnsafe(ratesFetchedAtMs)),\n        knownModels: rates.size,\n      },\n      scanDurationMs: Math.max(0, finishedAtMs - startedAtMs),\n    } satisfies UsageSummary;\n  });\n\n  return { readSummary } as const;\n});\n\nexport const layer = Layer.effect(UsageService, make);\n","import type {\n  ServerTraceDiagnosticsErrorKind,\n  ServerTraceDiagnosticsFailureSummary,\n  ServerTraceDiagnosticsLogEvent,\n  ServerTraceDiagnosticsRecentFailure,\n  ServerTraceDiagnosticsResult,\n  ServerTraceDiagnosticsSpanOccurrence,\n  ServerTraceDiagnosticsSpanSummary,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\ninterface TraceRecordLike {\n  readonly name?: unknown;\n  readonly traceId?: unknown;\n  readonly spanId?: unknown;\n  readonly startTimeUnixNano?: unknown;\n  readonly endTimeUnixNano?: unknown;\n  readonly durationMs?: unknown;\n  readonly exit?: unknown;\n  readonly events?: unknown;\n}\n\ninterface TraceEventLike {\n  readonly name?: unknown;\n  readonly timeUnixNano?: unknown;\n  readonly attributes?: unknown;\n}\n\nexport interface TraceDiagnosticsOptions {\n  readonly traceFilePath: string;\n  readonly maxFiles: number;\n  readonly slowSpanThresholdMs?: number;\n  readonly readAt?: DateTime.Utc;\n}\n\nexport class TraceFileReadError extends Schema.TaggedErrorClass<TraceFileReadError>()(\n  \"TraceFileReadError\",\n  {\n    traceFilePath: Schema.String,\n    causeTag: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to read local trace file '${this.traceFilePath}'.`;\n  }\n}\n\nexport class TraceDiagnostics extends Context.Service<\n  TraceDiagnostics,\n  {\n    readonly read: (\n      options: TraceDiagnosticsOptions,\n    ) => Effect.Effect<ServerTraceDiagnosticsResult>;\n  }\n>()(\"t3/diagnostics/TraceDiagnostics\") {}\n\ninterface TraceDiagnosticsInput {\n  readonly traceFilePath: string;\n  readonly files: ReadonlyArray<{ readonly path: string; readonly text: string }>;\n  readonly scannedFilePaths?: ReadonlyArray<string>;\n  readonly slowSpanThresholdMs?: number;\n  readonly readAt: DateTime.Utc;\n  readonly error?: TraceDiagnosticsErrorSummary;\n  readonly partialFailure?: boolean;\n}\n\ninterface TraceDiagnosticsErrorSummary {\n  readonly kind: ServerTraceDiagnosticsErrorKind;\n  readonly message: string;\n}\n\nconst DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;\nconst TOP_LIMIT = 10;\nconst RECENT_LIMIT = 20;\nfunction toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {\n  const backupCount = Math.max(0, Math.floor(maxFiles));\n  const backups = Array.from(\n    { length: backupCount },\n    (_, index) => `${traceFilePath}.${backupCount - index}`,\n  );\n  return [...backups, traceFilePath];\n}\n\nfunction isRecordObject(value: unknown): value is TraceRecordLike {\n  return typeof value === \"object\" && value !== null;\n}\n\nfunction toStringValue(value: unknown): string | null {\n  return typeof value === \"string\" && value.trim().length > 0 ? value : null;\n}\n\nfunction toNumberValue(value: unknown): number | null {\n  return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction unixNanoToDateTime(value: unknown): DateTime.Utc | null {\n  const text = toStringValue(value);\n  if (!text) return null;\n  try {\n    const millis = Number(BigInt(text) / 1_000_000n);\n    return Option.getOrNull(DateTime.make(millis));\n  } catch {\n    return null;\n  }\n}\n\nfunction readExitTag(exit: unknown): string | null {\n  if (!isRecordObject(exit) || !(\"_tag\" in exit)) return null;\n  return toStringValue(exit._tag);\n}\n\nfunction readExitCause(exit: unknown): string {\n  if (!isRecordObject(exit) || !(\"cause\" in exit)) return \"Failure\";\n  return toStringValue(exit.cause)?.trim() ?? \"Failure\";\n}\n\nfunction isTraceEvent(value: unknown): value is TraceEventLike {\n  return typeof value === \"object\" && value !== null;\n}\n\nfunction readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {\n  return typeof event.attributes === \"object\" && event.attributes !== null\n    ? (event.attributes as Readonly<Record<string, unknown>>)\n    : {};\n}\n\nfunction makeEmptyDiagnostics(input: {\n  readonly traceFilePath: string;\n  readonly scannedFilePaths: ReadonlyArray<string>;\n  readonly readAt: DateTime.Utc;\n  readonly slowSpanThresholdMs: number;\n  readonly error?: TraceDiagnosticsErrorSummary;\n  readonly partialFailure?: boolean;\n}): ServerTraceDiagnosticsResult {\n  return {\n    traceFilePath: input.traceFilePath,\n    scannedFilePaths: [...input.scannedFilePaths],\n    readAt: input.readAt,\n    recordCount: 0,\n    parseErrorCount: 0,\n    firstSpanAt: Option.none(),\n    lastSpanAt: Option.none(),\n    failureCount: 0,\n    interruptionCount: 0,\n    slowSpanThresholdMs: input.slowSpanThresholdMs,\n    slowSpanCount: 0,\n    logLevelCounts: {},\n    topSpansByCount: [],\n    slowestSpans: [],\n    commonFailures: [],\n    latestFailures: [],\n    latestWarningAndErrorLogs: [],\n    partialFailure: input.partialFailure ? Option.some(true) : Option.none(),\n    error: Option.fromNullishOr(input.error),\n  };\n}\n\nfunction isNotFoundError(error: PlatformError.PlatformError): boolean {\n  return error.reason._tag === \"NotFound\";\n}\n\nfunction insertBoundedSlowestSpan(\n  slowestSpans: ServerTraceDiagnosticsSpanOccurrence[],\n  span: ServerTraceDiagnosticsSpanOccurrence,\n): void {\n  if (\n    slowestSpans.length >= TOP_LIMIT &&\n    span.durationMs <= slowestSpans[slowestSpans.length - 1]!.durationMs\n  ) {\n    return;\n  }\n\n  slowestSpans.push(span);\n  slowestSpans.sort((left, right) => right.durationMs - left.durationMs);\n  if (slowestSpans.length > TOP_LIMIT) {\n    slowestSpans.length = TOP_LIMIT;\n  }\n}\n\nexport function aggregateTraceDiagnostics(\n  input: TraceDiagnosticsInput,\n): ServerTraceDiagnosticsResult {\n  const readAt = input.readAt;\n  const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;\n  const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path);\n  if (input.files.length === 0) {\n    return makeEmptyDiagnostics({\n      traceFilePath: input.traceFilePath,\n      scannedFilePaths,\n      readAt,\n      slowSpanThresholdMs,\n      error: input.error ?? {\n        kind: \"trace-file-not-found\",\n        message: \"No local trace files were found.\",\n      },\n      ...(input.partialFailure ? { partialFailure: true } : {}),\n    });\n  }\n\n  let parseErrorCount = 0;\n  let recordCount = 0;\n  let failureCount = 0;\n  let interruptionCount = 0;\n  let slowSpanCount = 0;\n  let firstSpanAt: DateTime.Utc | null = null;\n  let lastSpanAt: DateTime.Utc | null = null;\n\n  const spansByName = new Map<\n    string,\n    { count: number; failureCount: number; totalDurationMs: number; maxDurationMs: number }\n  >();\n  const failuresByKey = new Map<string, ServerTraceDiagnosticsFailureSummary>();\n  const latestFailures: ServerTraceDiagnosticsRecentFailure[] = [];\n  const slowestSpans: ServerTraceDiagnosticsSpanOccurrence[] = [];\n  const latestWarningAndErrorLogs: ServerTraceDiagnosticsLogEvent[] = [];\n  const logLevelCounts: Record<string, number> = {};\n\n  for (const file of input.files) {\n    const lines = file.text.split(/\\r?\\n/);\n    for (const line of lines) {\n      if (line.trim().length === 0) continue;\n\n      let parsed: unknown;\n      try {\n        parsed = JSON.parse(line);\n      } catch {\n        parseErrorCount += 1;\n        continue;\n      }\n\n      if (!isRecordObject(parsed)) {\n        parseErrorCount += 1;\n        continue;\n      }\n\n      const name = toStringValue(parsed.name);\n      const traceId = toStringValue(parsed.traceId);\n      const spanId = toStringValue(parsed.spanId);\n      const durationMs = toNumberValue(parsed.durationMs);\n      const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);\n      const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);\n\n      if (!name || !traceId || !spanId || durationMs === null || !endedAt) {\n        parseErrorCount += 1;\n        continue;\n      }\n\n      recordCount += 1;\n      firstSpanAt =\n        startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))\n          ? startedAt\n          : firstSpanAt;\n      lastSpanAt =\n        lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;\n\n      const exitTag = readExitTag(parsed.exit);\n      const isFailure = exitTag === \"Failure\";\n      const isInterrupted = exitTag === \"Interrupted\";\n      if (isFailure) failureCount += 1;\n      if (isInterrupted) interruptionCount += 1;\n\n      const spanSummary = spansByName.get(name) ?? {\n        count: 0,\n        failureCount: 0,\n        totalDurationMs: 0,\n        maxDurationMs: 0,\n      };\n      spanSummary.count += 1;\n      spanSummary.totalDurationMs += durationMs;\n      spanSummary.maxDurationMs = Math.max(spanSummary.maxDurationMs, durationMs);\n      if (isFailure) spanSummary.failureCount += 1;\n      spansByName.set(name, spanSummary);\n\n      const spanItem = { name, durationMs, endedAt, traceId, spanId };\n      if (durationMs >= slowSpanThresholdMs) {\n        slowSpanCount += 1;\n      }\n      insertBoundedSlowestSpan(slowestSpans, spanItem);\n\n      if (isFailure) {\n        const cause = readExitCause(parsed.exit);\n        latestFailures.push({ ...spanItem, cause });\n\n        const failureKey = `${name}\\0${cause}`;\n        const existing = failuresByKey.get(failureKey);\n        const isLatestFailure = !existing || DateTime.isGreaterThan(endedAt, existing.lastSeenAt);\n        failuresByKey.set(failureKey, {\n          name,\n          cause,\n          count: (existing?.count ?? 0) + 1,\n          lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,\n          traceId: isLatestFailure ? traceId : existing!.traceId,\n          spanId: isLatestFailure ? spanId : existing!.spanId,\n        });\n      }\n\n      if (Array.isArray(parsed.events)) {\n        for (const rawEvent of parsed.events) {\n          if (!isTraceEvent(rawEvent)) continue;\n          const attributes = readEventAttributes(rawEvent);\n          const level = toStringValue(attributes[\"effect.logLevel\"]);\n          if (!level) continue;\n\n          logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;\n          const normalizedLevel = level.toLowerCase();\n          if (\n            normalizedLevel !== \"warning\" &&\n            normalizedLevel !== \"warn\" &&\n            normalizedLevel !== \"error\" &&\n            normalizedLevel !== \"fatal\"\n          ) {\n            continue;\n          }\n\n          const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;\n          const message = toStringValue(rawEvent.name)?.trim() ?? \"Log event\";\n          latestWarningAndErrorLogs.push({\n            spanName: name,\n            level,\n            message,\n            seenAt,\n            traceId,\n            spanId,\n          });\n        }\n      }\n    }\n  }\n\n  const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]\n    .map(([name, span]) => ({\n      name,\n      count: span.count,\n      failureCount: span.failureCount,\n      totalDurationMs: span.totalDurationMs,\n      averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,\n      maxDurationMs: span.maxDurationMs,\n    }))\n    .toSorted((left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs)\n    .slice(0, TOP_LIMIT);\n\n  return {\n    traceFilePath: input.traceFilePath,\n    scannedFilePaths,\n    readAt,\n    recordCount,\n    parseErrorCount,\n    firstSpanAt: Option.fromNullishOr(firstSpanAt),\n    lastSpanAt: Option.fromNullishOr(lastSpanAt),\n    failureCount,\n    interruptionCount,\n    slowSpanThresholdMs,\n    slowSpanCount,\n    logLevelCounts,\n    topSpansByCount,\n    slowestSpans,\n    commonFailures: [...failuresByKey.values()]\n      .toSorted(\n        (left, right) =>\n          right.count - left.count ||\n          DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),\n      )\n      .slice(0, TOP_LIMIT),\n    latestFailures: latestFailures\n      .toSorted(\n        (left, right) =>\n          DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt),\n      )\n      .slice(0, RECENT_LIMIT),\n    latestWarningAndErrorLogs: latestWarningAndErrorLogs\n      .toSorted(\n        (left, right) => DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt),\n      )\n      .slice(0, RECENT_LIMIT),\n    partialFailure: input.partialFailure ? Option.some(true) : Option.none(),\n    error: Option.fromNullishOr(input.error),\n  };\n}\n\ntype TraceFileReadResult =\n  | { readonly _tag: \"Loaded\"; readonly path: string; readonly text: string }\n  | { readonly _tag: \"Missing\"; readonly path: string };\n\nfunction readTraceFile(\n  fileSystem: FileSystem.FileSystem,\n  path: string,\n): Effect.Effect<TraceFileReadResult, TraceFileReadError> {\n  return fileSystem.readFileString(path).pipe(\n    Effect.map((text): TraceFileReadResult => ({ _tag: \"Loaded\", path, text })),\n    Effect.catchTags({\n      PlatformError: (cause) =>\n        isNotFoundError(cause)\n          ? Effect.succeed<TraceFileReadResult>({ _tag: \"Missing\", path })\n          : Effect.fail(\n              new TraceFileReadError({\n                traceFilePath: path,\n                causeTag: cause.reason._tag,\n                cause,\n              }),\n            ),\n    }),\n  );\n}\n\nexport const make = Effect.gen(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n\n  const read: TraceDiagnostics[\"Service\"][\"read\"] = Effect.fn(\"TraceDiagnostics.read\")(\n    function* (options) {\n      const readAt = options.readAt ?? (yield* DateTime.now);\n      const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;\n      const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);\n      const results = yield* Effect.all(\n        paths.map((path) =>\n          readTraceFile(fileSystem, path).pipe(\n            Effect.tapError((cause) =>\n              Effect.logWarning(\"Failed to read local trace file.\").pipe(\n                Effect.annotateLogs({\n                  traceFilePath: cause.traceFilePath,\n                  errorTag: cause._tag,\n                  causeTag: cause.causeTag,\n                }),\n              ),\n            ),\n            Effect.result,\n          ),\n        ),\n        {\n          concurrency: 1,\n        },\n      );\n      const files = results.flatMap((result) =>\n        Result.isSuccess(result) && result.success._tag === \"Loaded\"\n          ? [{ path: result.success.path, text: result.success.text }]\n          : [],\n      );\n      const readFailure = results.find(Result.isFailure);\n      const readFailureError = readFailure\n        ? ({\n            kind: \"trace-file-read-failed\",\n            message: readFailure.failure.message,\n          } satisfies TraceDiagnosticsErrorSummary)\n        : undefined;\n\n      if (files.length === 0) {\n        return makeEmptyDiagnostics({\n          traceFilePath: options.traceFilePath,\n          scannedFilePaths: paths,\n          readAt,\n          slowSpanThresholdMs,\n          error:\n            readFailureError ??\n            ({\n              kind: \"trace-file-not-found\",\n              message: \"No local trace files were found.\",\n            } satisfies TraceDiagnosticsErrorSummary),\n        });\n      }\n\n      return aggregateTraceDiagnostics({\n        traceFilePath: options.traceFilePath,\n        files,\n        scannedFilePaths: paths,\n        readAt,\n        slowSpanThresholdMs,\n        ...(readFailureError ? { partialFailure: true, error: readFailureError } : {}),\n      });\n    },\n  );\n\n  return TraceDiagnostics.of({ read });\n});\n\nexport const layer = Layer.effect(TraceDiagnostics, make);\n\nexport function readTraceDiagnostics(\n  options: TraceDiagnosticsOptions,\n): Effect.Effect<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {\n  return Effect.gen(function* () {\n    const diagnostics = yield* TraceDiagnostics;\n    return yield* diagnostics.read(options);\n  });\n}\n","import {\n  type SourceControlDiscoveryResult,\n  type VcsDiscoveryItem,\n  type VcsDriverKind,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\n\nimport { ServerConfig } from \"../config.ts\";\nimport * as VcsProcess from \"../vcs/VcsProcess.ts\";\nimport { detailFromCause, firstNonEmptyLine } from \"./SourceControlProviderDiscovery.ts\";\nimport * as SourceControlProviderRegistry from \"./SourceControlProviderRegistry.ts\";\n\ninterface DiscoveryProbe {\n  readonly label: string;\n  readonly executable?: string;\n  readonly versionArgs?: ReadonlyArray<string>;\n  readonly implemented: boolean;\n  readonly installHint: string;\n}\n\ntype VcsProbe = DiscoveryProbe & {\n  readonly kind: VcsDriverKind;\n  readonly executable: string;\n  readonly versionArgs: ReadonlyArray<string>;\n};\n\ninterface DiscoveryProbeResult<Kind extends string> {\n  readonly kind: Kind;\n  readonly label: string;\n  readonly executable?: string;\n  readonly implemented: boolean;\n  readonly status: \"available\" | \"missing\";\n  readonly version: Option.Option<string>;\n  readonly installHint: string;\n  readonly detail: Option.Option<string>;\n}\n\nconst VCS_PROBES: ReadonlyArray<VcsProbe> = [\n  {\n    kind: \"git\",\n    label: \"Git\",\n    executable: \"git\",\n    versionArgs: [\"--version\"],\n    implemented: true,\n    installHint: \"Install Git from https://git-scm.com/downloads or with your package manager.\",\n  },\n  {\n    kind: \"jj\",\n    label: \"Jujutsu\",\n    executable: \"jj\",\n    versionArgs: [\"--version\"],\n    implemented: false,\n    installHint: \"Install Jujutsu with `brew install jj` or from https://github.com/jj-vcs/jj.\",\n  },\n];\n\nexport class SourceControlDiscovery extends Context.Service<\n  SourceControlDiscovery,\n  {\n    readonly discover: Effect.Effect<SourceControlDiscoveryResult>;\n  }\n>()(\"t3/sourceControl/SourceControlDiscovery\") {}\n\nexport const make = Effect.gen(function* () {\n  const config = yield* ServerConfig;\n  const process = yield* VcsProcess.VcsProcess;\n  const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;\n\n  const probe = <Kind extends VcsDriverKind>(\n    input: DiscoveryProbe & { readonly kind: Kind },\n  ): Effect.Effect<DiscoveryProbeResult<Kind>> => {\n    const executable = input.executable;\n    const versionArgs = input.versionArgs;\n\n    if (!executable || !versionArgs) {\n      return Effect.succeed({\n        kind: input.kind,\n        label: input.label,\n        implemented: input.implemented,\n        status: \"missing\" as const,\n        version: Option.none<string>(),\n        installHint: input.installHint,\n        detail: Option.some(input.installHint),\n      } satisfies DiscoveryProbeResult<Kind>);\n    }\n\n    return process\n      .run({\n        operation: \"source-control.discovery.probe\",\n        command: executable,\n        args: versionArgs,\n        cwd: config.cwd,\n        timeoutMs: 5_000,\n        maxOutputBytes: 8_000,\n        appendTruncationMarker: true,\n      })\n      .pipe(\n        Effect.map(\n          (result) =>\n            ({\n              kind: input.kind,\n              label: input.label,\n              executable,\n              implemented: input.implemented,\n              status: \"available\" as const,\n              version: Option.orElse(firstNonEmptyLine(result.stdout), () =>\n                firstNonEmptyLine(result.stderr),\n              ),\n              installHint: input.installHint,\n              detail: Option.none<string>(),\n            }) satisfies DiscoveryProbeResult<Kind>,\n        ),\n        Effect.catch((cause) =>\n          Effect.succeed({\n            kind: input.kind,\n            label: input.label,\n            executable,\n            implemented: input.implemented,\n            status: \"missing\" as const,\n            version: Option.none<string>(),\n            installHint: input.installHint,\n            detail: detailFromCause(cause),\n          } satisfies DiscoveryProbeResult<Kind>),\n        ),\n      );\n  };\n\n  return SourceControlDiscovery.of({\n    discover: Effect.all({\n      versionControlSystems: Effect.all(\n        VCS_PROBES.map((entry) => probe(entry)) as ReadonlyArray<Effect.Effect<VcsDiscoveryItem>>,\n        { concurrency: \"unbounded\" },\n      ),\n      sourceControlProviders: sourceControlProviders.discover,\n    }),\n  });\n});\n\nexport const layer = Layer.effect(SourceControlDiscovery, make);\n","import * as NodeOS from \"node:os\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport {\n  SourceControlRepositoryError,\n  type SourceControlCloneRepositoryInput,\n  type SourceControlCloneRepositoryResult,\n  type SourceControlCloneProtocol,\n  type SourceControlProviderKind,\n  type SourceControlPublishRepositoryInput,\n  type SourceControlPublishRepositoryResult,\n  type SourceControlRepositoryCloneUrls,\n  type SourceControlRepositoryInfo,\n  type SourceControlRepositoryLookupInput,\n} from \"@t3tools/contracts\";\n\nimport { ServerConfig } from \"../config.ts\";\nimport * as GitVcsDriver from \"../vcs/GitVcsDriver.ts\";\nimport * as SourceControlProviderRegistry from \"./SourceControlProviderRegistry.ts\";\nconst isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);\n\nexport class SourceControlRepositoryService extends Context.Service<\n  SourceControlRepositoryService,\n  {\n    readonly lookupRepository: (\n      input: SourceControlRepositoryLookupInput,\n    ) => Effect.Effect<SourceControlRepositoryInfo, SourceControlRepositoryError>;\n    readonly cloneRepository: (\n      input: SourceControlCloneRepositoryInput,\n    ) => Effect.Effect<SourceControlCloneRepositoryResult, SourceControlRepositoryError>;\n    readonly publishRepository: (\n      input: SourceControlPublishRepositoryInput,\n    ) => Effect.Effect<SourceControlPublishRepositoryResult, SourceControlRepositoryError>;\n  }\n>()(\"t3/sourceControl/SourceControlRepositoryService\") {}\n\nfunction mapRepositoryError(operation: string, provider: SourceControlProviderKind) {\n  return Effect.mapError((cause: unknown) =>\n    isSourceControlRepositoryError(cause)\n      ? cause\n      : new SourceControlRepositoryError({\n          operation,\n          provider,\n          detail: \"The source control operation could not be completed.\",\n          cause,\n        }),\n  );\n}\n\nfunction toRepositoryInfo(\n  provider: SourceControlProviderKind,\n  urls: SourceControlRepositoryCloneUrls,\n): SourceControlRepositoryInfo {\n  return {\n    provider,\n    nameWithOwner: urls.nameWithOwner,\n    url: urls.url,\n    sshUrl: urls.sshUrl,\n  };\n}\n\nfunction selectRemoteUrl(\n  urls: SourceControlRepositoryCloneUrls,\n  protocol: SourceControlCloneProtocol | undefined,\n): string {\n  switch (protocol ?? \"auto\") {\n    case \"https\":\n      return urls.url;\n    case \"ssh\":\n    case \"auto\":\n      return urls.sshUrl;\n  }\n}\n\nfunction expandHomePath(input: string, path: Path.Path): string {\n  if (input === \"~\") {\n    return NodeOS.homedir();\n  }\n  if (input.startsWith(\"~/\") || input.startsWith(\"~\\\\\")) {\n    return path.join(NodeOS.homedir(), input.slice(2));\n  }\n  return input;\n}\n\nexport const make = Effect.gen(function* () {\n  const config = yield* ServerConfig;\n  const fileSystem = yield* FileSystem.FileSystem;\n  const git = yield* GitVcsDriver.GitVcsDriver;\n  const path = yield* Path.Path;\n  const providers = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;\n\n  const ensureConcreteProvider = (input: {\n    readonly operation: string;\n    readonly provider: SourceControlProviderKind;\n  }) => {\n    if (input.provider !== \"unknown\") {\n      return Effect.succeed(input.provider);\n    }\n\n    return Effect.fail(\n      new SourceControlRepositoryError({\n        operation: input.operation,\n        provider: input.provider,\n        detail: \"Choose a source control provider before continuing.\",\n      }),\n    );\n  };\n\n  const lookupRepository = Effect.fn(\"SourceControlRepositoryService.lookupRepository\")(function* (\n    input: SourceControlRepositoryLookupInput,\n  ) {\n    const providerKind = yield* ensureConcreteProvider({\n      operation: \"lookupRepository\",\n      provider: input.provider,\n    });\n    const provider = yield* providers.get(providerKind);\n    const urls = yield* provider.getRepositoryCloneUrls({\n      cwd: input.cwd ?? config.cwd,\n      repository: input.repository.trim(),\n    });\n    return toRepositoryInfo(providerKind, urls);\n  });\n\n  const normalizeDestinationPath = Effect.fn(\"SourceControlRepositoryService.normalizeDestination\")(\n    function* (destinationPath: string) {\n      const trimmed = destinationPath.trim();\n      if (trimmed.length === 0) {\n        return yield* new SourceControlRepositoryError({\n          operation: \"cloneRepository\",\n          provider: \"unknown\",\n          detail: \"Choose a destination path before cloning.\",\n        });\n      }\n\n      return path.resolve(expandHomePath(trimmed, path));\n    },\n  );\n\n  const prepareDestination = Effect.fn(\"SourceControlRepositoryService.prepareDestination\")(\n    function* (destinationPath: string) {\n      const normalizedDestination = yield* normalizeDestinationPath(destinationPath);\n      if (yield* fileSystem.exists(normalizedDestination)) {\n        const entries = yield* fileSystem\n          .readDirectory(normalizedDestination, { recursive: false })\n          .pipe(\n            Effect.mapError(\n              (cause) =>\n                new SourceControlRepositoryError({\n                  operation: \"cloneRepository\",\n                  provider: \"unknown\",\n                  detail: \"Destination path already exists and is not a directory.\",\n                  cause,\n                }),\n            ),\n          );\n        if (entries.length > 0) {\n          return yield* new SourceControlRepositoryError({\n            operation: \"cloneRepository\",\n            provider: \"unknown\",\n            detail: \"Destination path already exists and is not empty.\",\n          });\n        }\n      } else {\n        yield* fileSystem.makeDirectory(path.dirname(normalizedDestination), { recursive: true });\n      }\n\n      return {\n        destinationPath: normalizedDestination,\n        parentPath: path.dirname(normalizedDestination),\n        directoryName: path.basename(normalizedDestination),\n      };\n    },\n  );\n\n  const cloneRepository = Effect.fn(\"SourceControlRepositoryService.cloneRepository\")(function* (\n    input: SourceControlCloneRepositoryInput,\n  ) {\n    const preparedDestination = yield* prepareDestination(input.destinationPath);\n    let repository: SourceControlRepositoryInfo | null = null;\n    let remoteUrl = input.remoteUrl?.trim() ?? null;\n    let provider: SourceControlProviderKind = input.provider ?? \"unknown\";\n\n    if (input.provider && input.repository) {\n      repository = yield* lookupRepository({\n        provider: input.provider,\n        repository: input.repository,\n        cwd: preparedDestination.parentPath,\n      });\n      remoteUrl = selectRemoteUrl(repository, input.protocol);\n      provider = input.provider;\n    }\n\n    if (!remoteUrl) {\n      return yield* new SourceControlRepositoryError({\n        operation: \"cloneRepository\",\n        provider,\n        detail: \"Enter a repository path or clone URL before cloning.\",\n      });\n    }\n\n    yield* git.execute({\n      operation: \"SourceControlRepositoryService.cloneRepository\",\n      cwd: preparedDestination.parentPath,\n      args: [\"clone\", remoteUrl, preparedDestination.directoryName],\n      timeoutMs: 120_000,\n      maxOutputBytes: 256 * 1024,\n    });\n\n    return {\n      cwd: preparedDestination.destinationPath,\n      remoteUrl,\n      repository,\n    };\n  });\n\n  const publishRepository = Effect.fn(\"SourceControlRepositoryService.publishRepository\")(\n    function* (input: SourceControlPublishRepositoryInput) {\n      const providerKind = yield* ensureConcreteProvider({\n        operation: \"publishRepository\",\n        provider: input.provider,\n      });\n      const provider = yield* providers.get(providerKind);\n      const urls = yield* provider.createRepository({\n        cwd: input.cwd,\n        repository: input.repository.trim(),\n        visibility: input.visibility,\n      });\n      const remoteUrl = selectRemoteUrl(urls, input.protocol);\n      const remoteName = yield* git.ensureRemote({\n        cwd: input.cwd,\n        preferredName: input.remoteName?.trim() || \"origin\",\n        url: remoteUrl,\n      });\n\n      // An empty local repo (no commits) would make `git push HEAD:...` fail\n      // with an opaque \"src refspec HEAD does not match any\". Treat this as a\n      // partial success: the remote was created and wired up, but there is\n      // nothing to push yet.\n      const hasCommits = yield* git\n        .execute({\n          operation: \"SourceControlRepositoryService.publishRepository.headCheck\",\n          cwd: input.cwd,\n          args: [\"rev-parse\", \"--verify\", \"HEAD\"],\n        })\n        .pipe(\n          Effect.map(() => true),\n          Effect.orElseSucceed(() => false),\n        );\n      if (!hasCommits) {\n        const details = yield* git.statusDetails(input.cwd).pipe(Effect.orElseSucceed(() => null));\n        return {\n          repository: toRepositoryInfo(providerKind, urls),\n          remoteName,\n          remoteUrl,\n          branch: details?.branch ?? \"main\",\n          status: \"remote_added\" as const,\n        };\n      }\n\n      const pushResult = yield* git.pushCurrentBranch(input.cwd, null, { remoteName });\n\n      return {\n        repository: toRepositoryInfo(providerKind, urls),\n        remoteName,\n        remoteUrl,\n        branch: pushResult.branch,\n        ...(pushResult.upstreamBranch ? { upstreamBranch: pushResult.upstreamBranch } : {}),\n        status: \"pushed\" as const,\n      };\n    },\n  );\n\n  return SourceControlRepositoryService.of({\n    lookupRepository: (input) =>\n      lookupRepository(input).pipe(mapRepositoryError(\"lookupRepository\", input.provider)),\n    cloneRepository: (input) =>\n      cloneRepository(input).pipe(\n        mapRepositoryError(\"cloneRepository\", input.provider ?? \"unknown\"),\n      ),\n    publishRepository: (input) =>\n      publishRepository(input).pipe(mapRepositoryError(\"publishRepository\", input.provider)),\n  });\n});\n\nexport const layer = Layer.effect(SourceControlRepositoryService, make);\n","import * as Clock from \"effect/Clock\";\nimport type {\n  RelayClientInstallProgressEvent,\n  RelayClientInstallProgressStage,\n} from \"@t3tools/contracts\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/unstable/http\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { HostProcessArchitecture, HostProcessPlatform } from \"./hostProcess.ts\";\n\nexport const CLOUDFLARED_VERSION = \"2026.5.2\";\nexport const CLOUDFLARED_PATH_ENV_NAME = \"SYNAPTIC_CLOUDFLARED_PATH\";\n\nexport type RelayClientExecutableSource = \"override\" | \"managed\" | \"path\";\n\nexport type RelayClientStatus =\n  | {\n      readonly status: \"available\";\n      readonly executablePath: string;\n      readonly source: RelayClientExecutableSource;\n      readonly version: string;\n    }\n  | {\n      readonly status: \"missing\";\n      readonly version: string;\n    }\n  | {\n      readonly status: \"unsupported\";\n      readonly platform: NodeJS.Platform;\n      readonly arch: string;\n      readonly version: string;\n    };\n\nexport type AvailableRelayClient = Extract<RelayClientStatus, { readonly status: \"available\" }>;\n\nexport class RelayClientInstallError extends Data.TaggedError(\"RelayClientInstallError\")<{\n  readonly reason:\n    | \"download_failed\"\n    | \"invalid_checksum\"\n    | \"install_locked\"\n    | \"override_missing\"\n    | \"unsupported_platform\"\n    | \"validation_failed\"\n    | \"write_failed\";\n  readonly message: string;\n  readonly cause?: unknown;\n}> {}\n\nclass CloudflaredCommandError extends Data.TaggedError(\"CloudflaredCommandError\")<{\n  readonly command: string;\n  readonly exitCode: number;\n}> {}\n\nexport interface CloudflaredReleaseAsset {\n  readonly url: string;\n  readonly sha256: string;\n  readonly archive: \"binary\" | \"tgz\";\n}\n\nconst CLOUDFLARED_RELEASE_ASSETS: Readonly<\n  Partial<Record<`${NodeJS.Platform}-${string}`, CloudflaredReleaseAsset>>\n> = {\n  \"darwin-arm64\": {\n    url: \"https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-arm64.tgz\",\n    sha256: \"ba94054c9fd4297645093d59d51442e5e546d07bb0516120e694a13d5b216d38\",\n    archive: \"tgz\",\n  },\n  \"darwin-x64\": {\n    url: \"https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-darwin-amd64.tgz\",\n    sha256: \"7240f709506bc2c1eb9da4d89cf2555499c60280ecb854b7d80e8f17d4b7903d\",\n    archive: \"tgz\",\n  },\n  \"linux-arm64\": {\n    url: \"https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-arm64\",\n    sha256: \"5a4e8ce2701105271412059f44b6a0bf1ae4542b4d98ff3180c0c019443a5815\",\n    archive: \"binary\",\n  },\n  \"linux-x64\": {\n    url: \"https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-linux-amd64\",\n    sha256: \"5286698547f03df745adb2355f04c12dde52ef425491e81f433642d695521886\",\n    archive: \"binary\",\n  },\n  \"win32-x64\": {\n    url: \"https://github.com/cloudflare/cloudflared/releases/download/2026.5.2/cloudflared-windows-amd64.exe\",\n    sha256: \"20b9638f685333d623798e733effbad2487093f15ba592f6c7752360ff3b7ab7\",\n    archive: \"binary\",\n  },\n};\n\nconst INSTALL_LOCK_RETRY_COUNT = 100;\nconst INSTALL_LOCK_RETRY_DELAY = \"100 millis\";\nconst INSTALL_LOCK_STALE_MS = 5 * 60 * 1_000;\n\nconst trimmedString = (name: string) =>\n  Config.string(name).pipe(\n    Config.option,\n    Config.map(\n      Option.flatMap((value) => {\n        const trimmed = value.trim();\n        return trimmed.length > 0 ? Option.some(trimmed) : Option.none();\n      }),\n    ),\n  );\n\nconst CloudflaredConfig = Config.all({\n  executableOverride: trimmedString(CLOUDFLARED_PATH_ENV_NAME),\n  path: trimmedString(\"PATH\"),\n});\n\nexport interface CloudflaredRelayClientOptions {\n  readonly baseDir: string;\n  readonly releaseAsset?: CloudflaredReleaseAsset;\n}\n\nexport interface RelayClientShape {\n  readonly resolve: Effect.Effect<RelayClientStatus>;\n  readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;\n  readonly installWithProgress: (\n    report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,\n  ) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;\n}\n\nexport class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(\n  \"@t3tools/shared/relayClient\",\n) {}\n\nfunction executableFileName(platform: NodeJS.Platform): string {\n  return platform === \"win32\" ? \"cloudflared.exe\" : \"cloudflared\";\n}\n\nfunction resolveReleaseAsset(\n  platform: NodeJS.Platform,\n  arch: string,\n): CloudflaredReleaseAsset | null {\n  return CLOUDFLARED_RELEASE_ASSETS[`${platform}-${arch}`] ?? null;\n}\n\nfunction isAlreadyExists(error: PlatformError.PlatformError): boolean {\n  return error.reason._tag === \"AlreadyExists\";\n}\n\nconst wrapInstallFailure =\n  (\n    reason: RelayClientInstallError[\"reason\"],\n    message: string,\n  ): (<E, R>(\n    effect: Effect.Effect<void, E, R>,\n  ) => Effect.Effect<void, RelayClientInstallError, R>) =>\n  (effect) =>\n    effect.pipe(\n      Effect.mapError(\n        (cause) =>\n          new RelayClientInstallError({\n            reason,\n            message,\n            cause,\n          }),\n      ),\n    );\n\nexport const makeCloudflaredRelayClient = Effect.fn(\"cloudflared.make\")(function* (\n  options: CloudflaredRelayClientOptions,\n): Effect.fn.Return<\n  RelayClientShape,\n  never,\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | HttpClient.HttpClient\n  | Path.Path\n> {\n  const crypto = yield* Crypto.Crypto;\n  const fileSystem = yield* FileSystem.FileSystem;\n  const httpClient = yield* HttpClient.HttpClient;\n  const path = yield* Path.Path;\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const installSemaphore = yield* Semaphore.make(1);\n  const platform = yield* HostProcessPlatform;\n  const arch = yield* HostProcessArchitecture;\n  const releaseAsset = options.releaseAsset ?? resolveReleaseAsset(platform, arch);\n  const loadCloudflaredConfig = Effect.suspend(() => CloudflaredConfig).pipe(Effect.orDie);\n  const managedPath = path.join(\n    options.baseDir,\n    \"tools\",\n    \"cloudflared\",\n    CLOUDFLARED_VERSION,\n    `${platform}-${arch}`,\n    executableFileName(platform),\n  );\n\n  const isExecutableFile = Effect.fn(\"cloudflared.isExecutableFile\")(function* (\n    executablePath: string,\n  ) {\n    const info = yield* fileSystem.stat(executablePath).pipe(Effect.option);\n    if (Option.isNone(info) || info.value.type !== \"File\") return false;\n    return platform === \"win32\" || (info.value.mode & 0o111) !== 0;\n  });\n\n  const resolvePathExecutable = Effect.gen(function* () {\n    const config = yield* loadCloudflaredConfig;\n    const pathValue = Option.getOrUndefined(config.path);\n    if (!pathValue) return null;\n    const delimiter = platform === \"win32\" ? \";\" : \":\";\n    for (const directory of pathValue.split(delimiter)) {\n      const trimmed = directory.trim().replace(/^\"|\"$/gu, \"\");\n      if (trimmed.length === 0) continue;\n      const candidate = path.join(trimmed, executableFileName(platform));\n      if (yield* isExecutableFile(candidate)) return candidate;\n    }\n    return null;\n  });\n\n  const resolve: RelayClientShape[\"resolve\"] = Effect.gen(function* () {\n    const config = yield* loadCloudflaredConfig;\n    if (Option.isSome(config.executableOverride)) {\n      return (yield* isExecutableFile(config.executableOverride.value))\n        ? {\n            status: \"available\",\n            executablePath: config.executableOverride.value,\n            source: \"override\",\n            version: CLOUDFLARED_VERSION,\n          }\n        : { status: \"missing\", version: CLOUDFLARED_VERSION };\n    }\n    if (yield* isExecutableFile(managedPath)) {\n      return {\n        status: \"available\",\n        executablePath: managedPath,\n        source: \"managed\",\n        version: CLOUDFLARED_VERSION,\n      };\n    }\n    const pathExecutable = yield* resolvePathExecutable;\n    if (pathExecutable) {\n      return {\n        status: \"available\",\n        executablePath: pathExecutable,\n        source: \"path\",\n        version: CLOUDFLARED_VERSION,\n      };\n    }\n    return releaseAsset\n      ? { status: \"missing\", version: CLOUDFLARED_VERSION }\n      : {\n          status: \"unsupported\",\n          platform,\n          arch,\n          version: CLOUDFLARED_VERSION,\n        };\n  });\n\n  const runCommand = Effect.fn(\"cloudflared.runCommand\")(function* (\n    command: string,\n    args: ReadonlyArray<string>,\n  ) {\n    const child = yield* spawner.spawn(\n      ChildProcess.make(command, args, {\n        shell: false,\n        stdout: \"ignore\",\n        stderr: \"ignore\",\n      }),\n    );\n    const exitCode = Number(yield* child.exitCode);\n    if (exitCode !== 0) {\n      return yield* new CloudflaredCommandError({ command, exitCode });\n    }\n  });\n\n  const downloadAsset = Effect.fn(\"cloudflared.downloadAsset\")(function* (\n    asset: CloudflaredReleaseAsset,\n    report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,\n  ) {\n    yield* report(\"downloading\");\n    const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe(\n      Effect.flatMap(HttpClientResponse.filterStatusOk),\n      Effect.mapError(\n        (cause) =>\n          new RelayClientInstallError({\n            reason: \"download_failed\",\n            message: \"Could not download the relay client.\",\n            cause,\n          }),\n      ),\n    );\n    const bytes = new Uint8Array(\n      yield* response.arrayBuffer.pipe(\n        Effect.mapError(\n          (cause) =>\n            new RelayClientInstallError({\n              reason: \"download_failed\",\n              message: \"Could not read the downloaded relay client binary.\",\n              cause,\n            }),\n        ),\n      ),\n    );\n    yield* report(\"verifying\");\n    const checksum = yield* crypto.digest(\"SHA-256\", bytes).pipe(\n      Effect.mapError(\n        (cause) =>\n          new RelayClientInstallError({\n            reason: \"validation_failed\",\n            message: \"Could not verify the downloaded relay client checksum.\",\n            cause,\n          }),\n      ),\n    );\n    if (Encoding.encodeHex(checksum) !== asset.sha256) {\n      return yield* new RelayClientInstallError({\n        reason: \"invalid_checksum\",\n        message: \"Downloaded relay client checksum did not match the pinned release.\",\n      });\n    }\n    return bytes;\n  });\n\n  const acquireInstallLock = Effect.fn(\"cloudflared.acquireInstallLock\")(function* (\n    lockPath: string,\n  ) {\n    for (let attempt = 0; attempt < INSTALL_LOCK_RETRY_COUNT; attempt += 1) {\n      const acquired = yield* fileSystem.writeFileString(lockPath, \"\", { flag: \"wx\" }).pipe(\n        Effect.as(true),\n        Effect.catch((error) =>\n          isAlreadyExists(error) ? Effect.succeed(false) : Effect.fail(error),\n        ),\n      );\n      if (acquired) return;\n\n      const now = yield* Clock.currentTimeMillis;\n      const lockInfo = yield* fileSystem.stat(lockPath).pipe(Effect.option);\n      const mtime = Option.flatMap(lockInfo, (info) => info.mtime);\n      if (Option.isSome(mtime) && now - mtime.value.getTime() > INSTALL_LOCK_STALE_MS) {\n        yield* fileSystem.remove(lockPath, { force: true });\n        continue;\n      }\n      yield* Effect.sleep(INSTALL_LOCK_RETRY_DELAY);\n    }\n    return yield* new RelayClientInstallError({\n      reason: \"install_locked\",\n      message: \"Another relay client installation is still in progress.\",\n    });\n  });\n\n  const installUnlocked = Effect.fn(\"cloudflared.installUnlocked\")(function* (\n    report: (stage: RelayClientInstallProgressStage) => Effect.Effect<void>,\n  ) {\n    yield* report(\"checking\");\n    const existing = yield* resolve;\n    if (existing.status === \"available\") return existing;\n    const config = yield* loadCloudflaredConfig;\n    if (Option.isSome(config.executableOverride)) {\n      return yield* new RelayClientInstallError({\n        reason: \"override_missing\",\n        message: `${CLOUDFLARED_PATH_ENV_NAME} does not point to an executable file.`,\n      });\n    }\n    if (!releaseAsset) {\n      return yield* new RelayClientInstallError({\n        reason: \"unsupported_platform\",\n        message: `Synaptic Code does not provide a managed relay client binary for ${platform}-${arch}.`,\n      });\n    }\n\n    const managedDirectory = path.dirname(managedPath);\n    const lockPath = `${managedPath}.lock`;\n    yield* fileSystem\n      .makeDirectory(managedDirectory, { recursive: true })\n      .pipe(\n        wrapInstallFailure(\"write_failed\", \"Could not create the relay client tool directory.\"),\n      );\n    yield* report(\"waiting_for_lock\");\n    yield* acquireInstallLock(lockPath).pipe(\n      Effect.catchTag(\"PlatformError\", (cause) =>\n        Effect.fail(\n          new RelayClientInstallError({\n            reason: \"write_failed\",\n            message: \"Could not acquire the relay client installation lock.\",\n            cause,\n          }),\n        ),\n      ),\n    );\n    return yield* Effect.gen(function* () {\n      const afterLock = yield* resolve;\n      if (afterLock.status === \"available\") return afterLock;\n\n      const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({\n        directory: managedDirectory,\n        prefix: \".install-\",\n      });\n      const archivePath = path.join(\n        tempDirectory,\n        releaseAsset.archive === \"tgz\" ? \"cloudflared.tgz\" : executableFileName(platform),\n      );\n      const download = yield* downloadAsset(releaseAsset, report);\n      yield* report(\"installing\");\n      yield* fileSystem\n        .writeFile(archivePath, download)\n        .pipe(wrapInstallFailure(\"write_failed\", \"Could not write the relay client download.\"));\n\n      const executablePath = path.join(tempDirectory, executableFileName(platform));\n      if (releaseAsset.archive === \"tgz\") {\n        yield* runCommand(\"tar\", [\"-xzf\", archivePath, \"-C\", tempDirectory]).pipe(\n          wrapInstallFailure(\"write_failed\", \"Could not extract the relay client.\"),\n        );\n      }\n      if (platform !== \"win32\") {\n        yield* fileSystem\n          .chmod(executablePath, 0o755)\n          .pipe(wrapInstallFailure(\"write_failed\", \"Could not make the relay client executable.\"));\n      }\n      yield* report(\"validating\");\n      yield* runCommand(executablePath, [\"--version\"]).pipe(\n        wrapInstallFailure(\"validation_failed\", \"The downloaded relay client binary did not run.\"),\n      );\n\n      const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4}.tmp`;\n      yield* report(\"activating\");\n      yield* fileSystem\n        .rename(executablePath, stagedPath)\n        .pipe(wrapInstallFailure(\"write_failed\", \"Could not stage the relay client.\"));\n      yield* fileSystem\n        .rename(stagedPath, managedPath)\n        .pipe(\n          wrapInstallFailure(\"write_failed\", \"Could not activate the relay client.\"),\n          Effect.ensuring(fileSystem.remove(stagedPath, { force: true }).pipe(Effect.ignore)),\n        );\n      return {\n        status: \"available\",\n        executablePath: managedPath,\n        source: \"managed\",\n        version: CLOUDFLARED_VERSION,\n      } satisfies AvailableRelayClient;\n    }).pipe(\n      Effect.scoped,\n      Effect.ensuring(fileSystem.remove(lockPath, { force: true }).pipe(Effect.ignore)),\n      Effect.catch((cause) =>\n        cause instanceof RelayClientInstallError\n          ? Effect.fail(cause)\n          : Effect.fail(\n              new RelayClientInstallError({\n                reason: \"write_failed\",\n                message: \"Could not install the relay client.\",\n                cause,\n              }),\n            ),\n      ),\n    );\n  });\n  const installWithProgress: RelayClientShape[\"installWithProgress\"] = (report) =>\n    installSemaphore.withPermit(\n      installUnlocked((stage) =>\n        report({\n          type: \"progress\",\n          stage,\n        }),\n      ),\n    );\n  const install = installWithProgress(() => Effect.void);\n\n  return RelayClient.of({ resolve, install, installWithProgress });\n});\n\nexport const layerCloudflared = (options: CloudflaredRelayClientOptions) =>\n  Layer.effect(RelayClient, makeCloudflaredRelayClient(options));\n","import * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport {\n  DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL,\n  AuthAccessStreamError,\n  type AuthAccessStreamEvent,\n  type AuthEnvironmentScope,\n  AuthSessionId,\n  CommandId,\n  type DiscoveredLocalServerList,\n  EventId,\n  type OrchestrationCommand,\n  type GitActionProgressEvent,\n  type GitManagerServiceError,\n  OrchestrationDispatchCommandError,\n  type OrchestrationEvent,\n  type OrchestrationShellStreamEvent,\n  type OrchestrationShellStreamItem,\n  type OrchestrationThreadStreamItem,\n  OrchestrationGetFullThreadDiffError,\n  OrchestrationGetSnapshotError,\n  OrchestrationSearchThreadsError,\n  OrchestrationGetTurnDiffError,\n  ORCHESTRATION_WS_METHODS,\n  type ProjectId,\n  type ProjectEntriesFailure,\n  type ProjectFileFailure,\n  type ProjectFileOperation,\n  ProjectListEntriesError,\n  ProjectReadFileError,\n  ProjectSearchContentsError,\n  ProjectSearchEntriesError,\n  ProjectWriteFileError,\n  RelayClientInstallFailedError,\n  type RelayClientInstallProgressEvent,\n  type ServerSelfUpdateError,\n  type ServerSelfUpdateProgressEvent,\n  type FilesystemBrowseFailure,\n  FilesystemBrowseError,\n  AssetWorkspaceContextNotFoundError,\n  AssetWorkspaceContextResolutionError,\n  RpcClientId,\n  EnvironmentAuthorizationError,\n  ThreadId,\n  type TerminalAttachStreamEvent,\n  type TerminalError,\n  type TerminalEvent,\n  type TerminalMetadataStreamEvent,\n  WS_METHODS,\n  WsRpcGroup,\n} from \"@t3tools/contracts\";\nimport { resolveServerBackgroundActivitySettings } from \"@t3tools/shared/backgroundActivitySettings\";\nimport { HttpRouter, HttpServerRequest, HttpServerRespondable } from \"effect/unstable/http\";\nimport { RpcSerialization, RpcServer } from \"effect/unstable/rpc\";\n\nimport * as CheckpointDiffQuery from \"./checkpointing/CheckpointDiffQuery.ts\";\nimport * as ServerConfig from \"./config.ts\";\nimport * as Keybindings from \"./keybindings.ts\";\nimport * as ExternalLauncher from \"./process/externalLauncher.ts\";\nimport {\n  projectActivityEvent,\n  projectThreadDetailSnapshot,\n} from \"./orchestration/ActivityPayloadProjection.ts\";\nimport { normalizeDispatchCommand } from \"./orchestration/Normalizer.ts\";\nimport * as OrchestrationEngine from \"./orchestration/Services/OrchestrationEngine.ts\";\nimport * as ProjectionSnapshotQuery from \"./orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport {\n  observeRpcEffect as instrumentRpcEffect,\n  observeRpcStream as instrumentRpcStream,\n  observeRpcStreamEffect as instrumentRpcStreamEffect,\n} from \"./observability/RpcInstrumentation.ts\";\nimport * as ProviderRegistry from \"./provider/Services/ProviderRegistry.ts\";\nimport * as ProviderMaintenanceRunner from \"./provider/providerMaintenanceRunner.ts\";\nimport * as ServerSelfUpdate from \"./cloud/selfUpdate.ts\";\nimport * as ServerLifecycleEvents from \"./serverLifecycleEvents.ts\";\nimport * as ServerRuntimeStartup from \"./serverRuntimeStartup.ts\";\nimport * as ServerSettings from \"./serverSettings.ts\";\nimport * as TerminalManager from \"./terminal/Manager.ts\";\nimport * as PreviewAutomationBroker from \"./mcp/PreviewAutomationBroker.ts\";\nimport * as PreviewManager from \"./preview/Manager.ts\";\nimport { issueAssetUrl } from \"./assets/AssetAccess.ts\";\nimport * as PortScanner from \"./preview/PortScanner.ts\";\nimport * as WorkspaceEntries from \"./workspace/WorkspaceEntries.ts\";\nimport * as WorkspaceFileSystem from \"./workspace/WorkspaceFileSystem.ts\";\nimport { readWorkflowScript } from \"./orchestration/workflowScriptQuery.ts\";\nimport * as WorkspacePaths from \"./workspace/WorkspacePaths.ts\";\nimport * as VcsStatusBroadcaster from \"./vcs/VcsStatusBroadcaster.ts\";\nimport * as VcsProvisioningService from \"./vcs/VcsProvisioningService.ts\";\nimport * as GitWorkflowService from \"./git/GitWorkflowService.ts\";\nimport * as ReviewService from \"./review/ReviewService.ts\";\nimport * as ProjectSetupScriptRunner from \"./project/ProjectSetupScriptRunner.ts\";\nimport * as ServerEnvironment from \"./environment/ServerEnvironment.ts\";\nimport * as BackgroundPolicy from \"./background/BackgroundPolicy.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\nimport { requiredScopeForRpcMethod } from \"./auth/RpcAuthorization.ts\";\nimport * as ProcessDiagnostics from \"./diagnostics/ProcessDiagnostics.ts\";\nimport * as ProcessResourceMonitor from \"./diagnostics/ProcessResourceMonitor.ts\";\nimport * as ResourceTelemetry from \"./resourceTelemetry/ResourceTelemetry.ts\";\nimport * as UsageService from \"./usage/UsageService.ts\";\nimport * as TraceDiagnostics from \"./diagnostics/TraceDiagnostics.ts\";\nimport * as SourceControlDiscovery from \"./sourceControl/SourceControlDiscovery.ts\";\nimport * as SourceControlRepositoryService from \"./sourceControl/SourceControlRepositoryService.ts\";\nimport * as AzureDevOpsCli from \"./sourceControl/AzureDevOpsCli.ts\";\nimport * as BitbucketApi from \"./sourceControl/BitbucketApi.ts\";\nimport * as GitHubCli from \"./sourceControl/GitHubCli.ts\";\nimport * as GitLabCli from \"./sourceControl/GitLabCli.ts\";\nimport * as SourceControlProviderRegistry from \"./sourceControl/SourceControlProviderRegistry.ts\";\nimport * as GitVcsDriver from \"./vcs/GitVcsDriver.ts\";\nimport * as VcsDriverRegistry from \"./vcs/VcsDriverRegistry.ts\";\nimport * as VcsProjectConfig from \"./vcs/VcsProjectConfig.ts\";\nimport * as VcsProcess from \"./vcs/VcsProcess.ts\";\nimport * as PairingGrantStore from \"./auth/PairingGrantStore.ts\";\nimport * as SessionStore from \"./auth/SessionStore.ts\";\nimport { failEnvironmentAuthInvalid, failEnvironmentInternal } from \"./auth/http.ts\";\nimport * as RelayClient from \"@t3tools/shared/relayClient\";\nconst isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError);\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\nconst EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5);\n\nexport const resolveAvailableEditorsForConfig = <A, E, R>(\n  discovery: Effect.Effect<ReadonlyArray<A>, E, R>,\n) =>\n  discovery.pipe(\n    Effect.timeoutOption(EDITOR_DISCOVERY_TIMEOUT),\n    Effect.map(Option.getOrElse(() => [])),\n  );\n\nfunction unexpectedCompatibilityError(error: never): never {\n  throw new Error(`Unhandled compatibility error: ${String(error)}`);\n}\n\n/** Preserve the setup runner's broader pre-refactor message normalization. */\nfunction legacySetupFailureDescription(cause: unknown): string {\n  if (\n    typeof cause === \"object\" &&\n    cause !== null &&\n    \"message\" in cause &&\n    typeof cause.message === \"string\"\n  ) {\n    return cause.message;\n  }\n  return String(cause);\n}\n\nfunction projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): {\n  readonly failure: ProjectEntriesFailure;\n  readonly normalizedCwd?: string;\n  readonly timeout?: string;\n  readonly detail?: string;\n} {\n  switch (error._tag) {\n    case \"WorkspaceRootNotExistsError\":\n      return {\n        failure: \"workspace_root_not_found\",\n        normalizedCwd: error.normalizedWorkspaceRoot,\n      };\n    case \"WorkspaceRootCreateFailedError\":\n      return {\n        failure: \"workspace_root_create_failed\",\n        normalizedCwd: error.normalizedWorkspaceRoot,\n      };\n    case \"WorkspaceRootStatFailedError\":\n      return {\n        failure: \"workspace_root_stat_failed\",\n        normalizedCwd: error.normalizedWorkspaceRoot,\n        detail: error.phase,\n      };\n    case \"WorkspaceRootNotDirectoryError\":\n      return {\n        failure: \"workspace_root_not_directory\",\n        normalizedCwd: error.normalizedWorkspaceRoot,\n      };\n    case \"WorkspaceSearchIndexCreateFailed\":\n      return {\n        failure: \"search_index_create_failed\",\n        normalizedCwd: error.cwd,\n        detail: error.reason,\n      };\n    case \"WorkspaceSearchIndexScanTimedOut\":\n      return {\n        failure: \"search_index_scan_timed_out\",\n        normalizedCwd: error.cwd,\n        timeout: error.timeout,\n      };\n    case \"WorkspaceSearchIndexSearchFailed\":\n      return {\n        failure: \"search_index_search_failed\",\n        normalizedCwd: error.cwd,\n        detail: error.reason,\n      };\n    default:\n      return unexpectedCompatibilityError(error);\n  }\n}\n\nfunction filesystemBrowseFailureContext(error: WorkspaceEntries.WorkspaceEntriesBrowseError): {\n  readonly failure: FilesystemBrowseFailure;\n  readonly parentPath?: string;\n  readonly platform?: string;\n} {\n  switch (error._tag) {\n    case \"WorkspaceEntriesWindowsPathUnsupportedError\":\n      return { failure: \"windows_path_unsupported\", platform: error.platform };\n    case \"WorkspaceEntriesCurrentProjectRequiredError\":\n      return { failure: \"current_project_required\" };\n    case \"WorkspaceEntriesReadDirectoryError\":\n      return { failure: \"read_directory_failed\", parentPath: error.parentPath };\n    default:\n      return unexpectedCompatibilityError(error);\n  }\n}\n\nfunction projectFileFailureContext(\n  error:\n    | WorkspaceFileSystem.WorkspaceFileSystemError\n    | WorkspacePaths.WorkspacePathOutsideRootError,\n): {\n  readonly failure: ProjectFileFailure;\n  readonly resolvedPath?: string;\n  readonly resolvedWorkspaceRoot?: string;\n  readonly operation?: ProjectFileOperation;\n  readonly operationPath?: string;\n} {\n  switch (error._tag) {\n    case \"WorkspacePathOutsideRootError\":\n      return { failure: \"workspace_path_outside_root\" };\n    case \"WorkspaceFileSystemOperationError\":\n      return {\n        failure: \"operation_failed\",\n        resolvedPath: error.resolvedPath,\n        operation: error.operation,\n        operationPath: error.operationPath,\n      };\n    case \"WorkspaceFilePathEscapeError\":\n      return {\n        failure: \"resolved_path_outside_root\",\n        resolvedPath: error.resolvedPath,\n        resolvedWorkspaceRoot: error.resolvedWorkspaceRoot,\n      };\n    case \"WorkspacePathNotFileError\":\n      return { failure: \"path_not_file\", resolvedPath: error.resolvedPath };\n    case \"WorkspaceBinaryFileError\":\n      return { failure: \"binary_file\", resolvedPath: error.resolvedPath };\n    default:\n      return unexpectedCompatibilityError(error);\n  }\n}\n\nfunction projectSetupScriptCompatibilityDetail(\n  error: ProjectSetupScriptRunner.ProjectSetupScriptRunnerError,\n): string {\n  switch (error._tag) {\n    case \"ProjectSetupScriptOperationError\":\n      return legacySetupFailureDescription(error.cause);\n    case \"ProjectSetupScriptProjectNotFoundError\":\n      return \"Project was not found for setup script execution.\";\n    default:\n      return unexpectedCompatibilityError(error);\n  }\n}\n\nexport function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<\n  OrchestrationEvent,\n  {\n    type:\n      | \"thread.message-sent\"\n      | \"thread.proposed-plan-upserted\"\n      | \"thread.activity-appended\"\n      | \"thread.turn-diff-completed\"\n      | \"thread.reverted\"\n      | \"thread.session-set\";\n  }\n> {\n  return (\n    event.type === \"thread.message-sent\" ||\n    event.type === \"thread.proposed-plan-upserted\" ||\n    event.type === \"thread.activity-appended\" ||\n    event.type === \"thread.turn-diff-completed\" ||\n    event.type === \"thread.reverted\" ||\n    event.type === \"thread.session-set\"\n  );\n}\n\nconst PROVIDER_STATUS_DEBOUNCE_MS = 200;\n\n// When a resuming client's cursor is more than this many events behind the\n// current head, skip the per-event catch-up replay and send a fresh shell\n// snapshot instead. Replaying each intervening event costs a shell refetch;\n// past this gap a single O(active-threads) snapshot is cheaper and bounded.\n// Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT).\nconst SHELL_RESUME_MAX_GAP = 1_000;\n\n// Same bound for thread resume. The replay reads the *global* event range and\n// filters per-thread afterwards, so a stale cursor far behind the head would\n// otherwise decode every intervening event's payload — reconnects with cursors\n// hundreds of thousands of events behind have OOM-killed servers on large\n// databases. Past this gap the client is reset with a fresh thread snapshot.\nconst THREAD_RESUME_MAX_GAP = 1_000;\n\nfunction toAuthAccessStreamEvent(\n  change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange,\n  revision: number,\n  currentSessionId: AuthSessionId,\n): AuthAccessStreamEvent {\n  switch (change.type) {\n    case \"pairingLinkUpserted\":\n      return {\n        version: 1,\n        revision,\n        type: \"pairingLinkUpserted\",\n        payload: change.pairingLink,\n      };\n    case \"pairingLinkRemoved\":\n      return {\n        version: 1,\n        revision,\n        type: \"pairingLinkRemoved\",\n        payload: { id: change.id },\n      };\n    case \"clientUpserted\":\n      return {\n        version: 1,\n        revision,\n        type: \"clientUpserted\",\n        payload: {\n          ...change.clientSession,\n          current: change.clientSession.sessionId === currentSessionId,\n        },\n      };\n    case \"clientRemoved\":\n      return {\n        version: 1,\n        revision,\n        type: \"clientRemoved\",\n        payload: { sessionId: change.sessionId },\n      };\n  }\n}\n\nconst makeWsRpcLayer = (\n  currentSession: EnvironmentAuth.AuthenticatedSession,\n  previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker[\"Service\"],\n) =>\n  WsRpcGroup.toLayer(\n    Effect.gen(function* () {\n      const currentSessionId = currentSession.sessionId;\n      const crypto = yield* Crypto.Crypto;\n      const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n      const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;\n      const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;\n      const keybindings = yield* Keybindings.Keybindings;\n      const externalLauncher = yield* ExternalLauncher.ExternalLauncher;\n      const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;\n      const review = yield* ReviewService.ReviewService;\n      const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;\n      const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;\n      const terminalManager = yield* TerminalManager.TerminalManager;\n      const previewManager = yield* PreviewManager.PreviewManager;\n      const portDiscovery = yield* PortScanner.PortDiscovery;\n      const providerRegistry = yield* ProviderRegistry.ProviderRegistry;\n      const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;\n      const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;\n      const config = yield* ServerConfig.ServerConfig;\n      const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;\n      const serverSettings = yield* ServerSettings.ServerSettingsService;\n      const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;\n      const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;\n      const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;\n      const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;\n      const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;\n      const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;\n      const rpcClientIds = yield* Ref.make(new Set<RpcClientId>());\n      yield* Effect.addFinalizer(() =>\n        Ref.get(rpcClientIds).pipe(\n          Effect.flatMap((clientIds) =>\n            Effect.forEach(\n              clientIds,\n              (clientId) => backgroundPolicy.removeRpcClient(currentSessionId, clientId),\n              {\n                discard: true,\n              },\n            ),\n          ),\n          Effect.ignore,\n        ),\n      );\n      const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n      const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery;\n      const automaticGitFetchInterval = serverSettings.getSettings.pipe(\n        Effect.map(\n          (settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,\n        ),\n        Effect.catch((cause) =>\n          Effect.logWarning(\"Failed to read automatic Git fetch interval setting\", {\n            detail: cause.message,\n          }).pipe(Effect.as(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),\n        ),\n      );\n      const sourceControlRepositories =\n        yield* SourceControlRepositoryService.SourceControlRepositoryService;\n      const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;\n      const sessions = yield* SessionStore.SessionStore;\n      const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics;\n      const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor;\n      const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry;\n      const usage = yield* UsageService.UsageService;\n      const relayClient = yield* RelayClient.RelayClient;\n      const authorizationError = (requiredScope: AuthEnvironmentScope) =>\n        new EnvironmentAuthorizationError({\n          message: `The authenticated token is missing required scope: ${requiredScope}.`,\n          requiredScope,\n        });\n      const authorizeEffect = <A, E, R>(\n        requiredScope: AuthEnvironmentScope,\n        effect: Effect.Effect<A, E, R>,\n      ): Effect.Effect<A, E | EnvironmentAuthorizationError, R> =>\n        currentSession.scopes.includes(requiredScope)\n          ? effect\n          : Effect.fail(authorizationError(requiredScope));\n      const authorizeStream = <A, E, R>(\n        requiredScope: AuthEnvironmentScope,\n        stream: Stream.Stream<A, E, R>,\n      ): Stream.Stream<A, E | EnvironmentAuthorizationError, R> =>\n        currentSession.scopes.includes(requiredScope)\n          ? stream\n          : Stream.fail(authorizationError(requiredScope));\n      const observeRpcEffect = <A, E, R>(\n        method: string,\n        effect: Effect.Effect<A, E, R>,\n        traceAttributes?: Readonly<Record<string, unknown>>,\n      ) =>\n        instrumentRpcEffect(\n          method,\n          authorizeEffect(requiredScopeForRpcMethod(method), effect),\n          traceAttributes,\n        );\n      const observeRpcStream = <A, E, R>(\n        method: string,\n        stream: Stream.Stream<A, E, R>,\n        traceAttributes?: Readonly<Record<string, unknown>>,\n      ) =>\n        instrumentRpcStream(\n          method,\n          authorizeStream(requiredScopeForRpcMethod(method), stream),\n          traceAttributes,\n        );\n      const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(\n        method: string,\n        effect: Effect.Effect<\n          Stream.Stream<A, StreamError, StreamContext>,\n          EffectError,\n          EffectContext\n        >,\n        traceAttributes?: Readonly<Record<string, unknown>>,\n      ) =>\n        instrumentRpcStreamEffect(\n          method,\n          authorizeEffect(requiredScopeForRpcMethod(method), effect),\n          traceAttributes,\n        );\n      const toDispatchCommandError = (cause: unknown, fallbackMessage: string) =>\n        isOrchestrationDispatchCommandError(cause)\n          ? cause\n          : new OrchestrationDispatchCommandError({\n              message: cause instanceof Error ? cause.message : fallbackMessage,\n              cause,\n            });\n      const randomUUID = crypto.randomUUIDv4.pipe(\n        Effect.mapError((cause) =>\n          toDispatchCommandError(cause, \"Failed to generate orchestration command identifier.\"),\n        ),\n      );\n      const serverEventId = randomUUID.pipe(Effect.map(EventId.make));\n      const serverCommandId = (tag: string) =>\n        randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));\n\n      const loadAuthAccessSnapshot = () =>\n        Effect.all({\n          pairingLinks: serverAuth.listPairingLinks(),\n          clientSessions: serverAuth.listClientSessions(currentSessionId),\n        }).pipe(\n          Effect.mapError(\n            (error) =>\n              new AuthAccessStreamError({\n                message: error.message,\n              }),\n          ),\n        );\n\n      const appendSetupScriptActivity = (input: {\n        readonly threadId: ThreadId;\n        readonly kind: \"setup-script.requested\" | \"setup-script.started\" | \"setup-script.failed\";\n        readonly summary: string;\n        readonly createdAt: string;\n        readonly payload: Record<string, unknown>;\n        readonly tone: \"info\" | \"error\";\n      }) =>\n        Effect.all({\n          commandId: serverCommandId(\"setup-script-activity\"),\n          activityId: serverEventId,\n        }).pipe(\n          Effect.flatMap(({ commandId, activityId }) =>\n            orchestrationEngine.dispatch({\n              type: \"thread.activity.append\",\n              commandId,\n              threadId: input.threadId,\n              activity: {\n                id: activityId,\n                tone: input.tone,\n                kind: input.kind,\n                summary: input.summary,\n                payload: input.payload,\n                turnId: null,\n                createdAt: input.createdAt,\n              },\n              createdAt: input.createdAt,\n            }),\n          ),\n        );\n\n      const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause<unknown>) => {\n        const error = Cause.squash(cause);\n        return isOrchestrationDispatchCommandError(error)\n          ? error\n          : new OrchestrationDispatchCommandError({\n              message:\n                error instanceof Error ? error.message : \"Failed to bootstrap thread turn start.\",\n              cause,\n            });\n      };\n\n      const toShellStreamEvent = (\n        event: OrchestrationEvent,\n      ): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {\n        switch (event.type) {\n          case \"project.created\":\n          case \"project.meta-updated\":\n            return projectUpsertOrRemove(event.payload.projectId, event.sequence);\n          case \"project.deleted\":\n            return Effect.succeed(\n              Option.some({\n                kind: \"project-removed\" as const,\n                sequence: event.sequence,\n                projectId: event.payload.projectId,\n              }),\n            );\n          case \"thread.deleted\":\n          case \"thread.archived\":\n            return Effect.succeed(\n              Option.some({\n                kind: \"thread-removed\" as const,\n                sequence: event.sequence,\n                threadId: event.payload.threadId,\n              }),\n            );\n          case \"thread.unarchived\":\n            return threadUpsertOrRemove(event.payload.threadId, event.sequence);\n          default:\n            if (event.aggregateKind !== \"thread\") {\n              return Effect.succeed(Option.none());\n            }\n            return threadUpsertOrRemove(ThreadId.make(event.aggregateId), event.sequence);\n        }\n      };\n\n      // Coalescing makes each projection read represent every event for that\n      // aggregate in the current window. Retry a typed persistence failure once\n      // so a brief read failure cannot strand the shell at its previous state.\n      // If both attempts fail, log and drop the stream item; treating an error as\n      // a missing row would incorrectly remove a still-active aggregate.\n      const retryShellProjectionRead = <A, E>(\n        aggregateKind: \"project\" | \"thread\",\n        aggregateId: string,\n        read: Effect.Effect<A, E>,\n      ): Effect.Effect<Option.Option<A>, never, never> =>\n        read.pipe(\n          Effect.retry({ times: 1 }),\n          Effect.map(Option.some),\n          Effect.tapError((error) =>\n            Effect.logWarning(\"orchestration shell projection refetch failed\", {\n              aggregateKind,\n              aggregateId,\n              error,\n            }),\n          ),\n          Effect.orElseSucceed(() => Option.none()),\n        );\n\n      const projectUpsertOrRemove = (\n        projectId: ProjectId,\n        sequence: number,\n      ): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> =>\n        retryShellProjectionRead(\n          \"project\",\n          projectId,\n          projectionSnapshotQuery.getProjectShellById(projectId),\n        ).pipe(\n          Effect.map(\n            Option.flatMap((project) =>\n              Option.match(project, {\n                onNone: () =>\n                  Option.some<OrchestrationShellStreamEvent>({\n                    kind: \"project-removed\" as const,\n                    sequence,\n                    projectId,\n                  }),\n                onSome: (nextProject) =>\n                  Option.some<OrchestrationShellStreamEvent>({\n                    kind: \"project-upserted\" as const,\n                    sequence,\n                    project: nextProject,\n                  }),\n              }),\n            ),\n          ),\n        );\n\n      // Refetch a thread's shell and emit an upsert if it is still active, or a\n      // `thread-removed` if the projection has no active row for it. Emitting a\n      // removal on a `none` (rather than dropping the event) is what keeps\n      // coalescing correct: when a burst collapses a `thread.deleted`/`archived`\n      // into a later refetchable event for the same thread, the refetch returns\n      // `none` for the now-inactive row and this still tells the sidebar to drop\n      // it. A `thread-removed` the client does not have is a harmless no-op. The\n      // projection commits in the same transaction before the event publishes,\n      // so a `none` reliably means the thread is deleted or archived, not\n      // not-yet-persisted.\n      const threadUpsertOrRemove = (\n        threadId: ThreadId,\n        sequence: number,\n      ): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> =>\n        retryShellProjectionRead(\n          \"thread\",\n          threadId,\n          projectionSnapshotQuery.getThreadShellById(threadId),\n        ).pipe(\n          Effect.map(\n            Option.flatMap((thread) =>\n              Option.match(thread, {\n                onNone: () =>\n                  Option.some<OrchestrationShellStreamEvent>({\n                    kind: \"thread-removed\" as const,\n                    sequence,\n                    threadId,\n                  }),\n                onSome: (nextThread) =>\n                  Option.some<OrchestrationShellStreamEvent>({\n                    kind: \"thread-upserted\" as const,\n                    sequence,\n                    thread: nextThread,\n                  }),\n              }),\n            ),\n          ),\n        );\n\n      // Turn a batch of domain events into shell stream items, coalescing by\n      // aggregate first. `toShellStreamEvent` re-reads the *current* projected\n      // shell for an aggregate, so within a batch only the latest event per\n      // aggregate matters: a burst of streaming `thread.message-sent` deltas for\n      // one thread collapses into a single shell refetch, and an unrelated\n      // `thread.created` in the same batch is never stuck behind those DB reads.\n      //\n      // Input events arrive in ascending sequence; we keep the last (highest\n      // sequence) event per aggregate, then re-sort ascending before emitting so\n      // the client — which applies shell items strictly by increasing sequence\n      // and drops any `sequence <= snapshotSequence` — never skips a coalesced\n      // item. The refetch runs with bounded concurrency (order-preserving).\n      const SHELL_REFETCH_CONCURRENCY = 8;\n      const coalesceShellEvents = (\n        events: ReadonlyArray<OrchestrationEvent>,\n      ): Effect.Effect<ReadonlyArray<OrchestrationShellStreamEvent>, never, never> =>\n        Effect.gen(function* () {\n          if (events.length === 0) {\n            return [];\n          }\n          const latestByAggregate = new Map<string, OrchestrationEvent>();\n          for (const event of events) {\n            latestByAggregate.set(`${event.aggregateKind}:${event.aggregateId}`, event);\n          }\n          const survivors = Array.from(latestByAggregate.values()).sort(\n            (left, right) => left.sequence - right.sequence,\n          );\n          const shellEvents = yield* Effect.forEach(survivors, toShellStreamEvent, {\n            concurrency: SHELL_REFETCH_CONCURRENCY,\n          });\n          return shellEvents.flatMap((option) => (Option.isSome(option) ? [option.value] : []));\n        });\n\n      // Small time/size window over which to coalesce shell events. The window\n      // bounds the worst-case added latency for a brand-new thread to appear in\n      // the sidebar (imperceptible), while collapsing high-frequency streaming\n      // traffic so it can't serialize the shell stream behind per-event DB reads.\n      const SHELL_COALESCE_WINDOW = Duration.millis(50);\n      const SHELL_COALESCE_MAX_CHUNK = 512;\n      const coalesceShellStream = <E, R>(\n        stream: Stream.Stream<OrchestrationEvent, E, R>,\n      ): Stream.Stream<OrchestrationShellStreamEvent, E, R> =>\n        stream.pipe(\n          Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),\n          Stream.mapEffect(coalesceShellEvents),\n          Stream.flatMap((items) => Stream.fromIterable(items)),\n        );\n\n      type ShellLiveInput =\n        | { readonly kind: \"event\"; readonly event: OrchestrationEvent }\n        | { readonly kind: \"synchronized\" };\n\n      // A completion marker is queued alongside raw live events so it cannot\n      // overtake an event still waiting in the coalescing window. Split each\n      // batch at markers and coalesce only the event segments on either side.\n      const coalesceShellLiveInputs = (\n        inputs: ReadonlyArray<ShellLiveInput>,\n      ): Effect.Effect<ReadonlyArray<OrchestrationShellStreamItem>, never, never> =>\n        Effect.gen(function* () {\n          const output: Array<OrchestrationShellStreamItem> = [];\n          let pendingEvents: Array<OrchestrationEvent> = [];\n\n          for (const input of inputs) {\n            if (input.kind === \"event\") {\n              pendingEvents.push(input.event);\n              continue;\n            }\n\n            output.push(...(yield* coalesceShellEvents(pendingEvents)));\n            pendingEvents = [];\n            output.push({ kind: \"synchronized\" });\n          }\n\n          output.push(...(yield* coalesceShellEvents(pendingEvents)));\n          return output;\n        });\n\n      const coalesceShellLiveStream = <E, R>(\n        stream: Stream.Stream<ShellLiveInput, E, R>,\n      ): Stream.Stream<OrchestrationShellStreamItem, E, R> =>\n        stream.pipe(\n          Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),\n          Stream.mapEffect(coalesceShellLiveInputs),\n          Stream.flatMap((items) => Stream.fromIterable(items)),\n        );\n\n      const dispatchBootstrapTurnStart = (\n        command: Extract<OrchestrationCommand, { type: \"thread.turn.start\" }>,\n      ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> =>\n        Effect.gen(function* () {\n          const bootstrap = command.bootstrap;\n          const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command;\n          let createdThread = false;\n          let targetProjectId = bootstrap?.createThread?.projectId;\n          let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd;\n          let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null;\n\n          const cleanupCreatedThread = () =>\n            createdThread\n              ? serverCommandId(\"bootstrap-thread-delete\").pipe(\n                  Effect.flatMap((commandId) =>\n                    orchestrationEngine.dispatch({\n                      type: \"thread.delete\",\n                      commandId,\n                      threadId: command.threadId,\n                    }),\n                  ),\n                  Effect.ignoreCause({ log: true }),\n                )\n              : Effect.void;\n\n          const recordSetupScriptLaunchFailure = (input: {\n            readonly error: ProjectSetupScriptRunner.ProjectSetupScriptRunnerError;\n            readonly requestedAt: string;\n            readonly worktreePath: string;\n          }) => {\n            const detail = projectSetupScriptCompatibilityDetail(input.error);\n            return appendSetupScriptActivity({\n              threadId: command.threadId,\n              kind: \"setup-script.failed\",\n              summary: \"Setup script failed to start\",\n              createdAt: input.requestedAt,\n              payload: {\n                detail,\n                worktreePath: input.worktreePath,\n              },\n              tone: \"error\",\n            }).pipe(\n              Effect.ignoreCause({ log: false }),\n              Effect.flatMap(() =>\n                Effect.logWarning(\"bootstrap turn start failed to launch setup script\", {\n                  threadId: command.threadId,\n                  worktreePath: input.worktreePath,\n                  detail,\n                }),\n              ),\n            );\n          };\n\n          const recordSetupScriptStarted = (input: {\n            readonly requestedAt: string;\n            readonly worktreePath: string;\n            readonly scriptId: string;\n            readonly scriptName: string;\n            readonly terminalId: string;\n          }) =>\n            Effect.gen(function* () {\n              const startedAt = yield* nowIso;\n              const payload = {\n                scriptId: input.scriptId,\n                scriptName: input.scriptName,\n                terminalId: input.terminalId,\n                worktreePath: input.worktreePath,\n              };\n              yield* Effect.all([\n                appendSetupScriptActivity({\n                  threadId: command.threadId,\n                  kind: \"setup-script.requested\",\n                  summary: \"Starting setup script\",\n                  createdAt: input.requestedAt,\n                  payload,\n                  tone: \"info\",\n                }),\n                appendSetupScriptActivity({\n                  threadId: command.threadId,\n                  kind: \"setup-script.started\",\n                  summary: \"Setup script started\",\n                  createdAt: startedAt,\n                  payload,\n                  tone: \"info\",\n                }),\n              ]).pipe(\n                Effect.asVoid,\n                Effect.catch((error) =>\n                  Effect.logWarning(\n                    \"bootstrap turn start launched setup script but failed to record setup activity\",\n                    {\n                      threadId: command.threadId,\n                      worktreePath: input.worktreePath,\n                      scriptId: input.scriptId,\n                      terminalId: input.terminalId,\n                      detail: error.message,\n                    },\n                  ),\n                ),\n              );\n            });\n\n          const runSetupProgram = () =>\n            Effect.gen(function* () {\n              if (!bootstrap?.runSetupScript || !targetWorktreePath) {\n                return;\n              }\n              const worktreePath = targetWorktreePath;\n              const requestedAt = yield* nowIso;\n              yield* projectSetupScriptRunner\n                .runForThread({\n                  threadId: command.threadId,\n                  ...(targetProjectId ? { projectId: targetProjectId } : {}),\n                  ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}),\n                  worktreePath,\n                })\n                .pipe(\n                  Effect.matchEffect({\n                    onFailure: (error) =>\n                      recordSetupScriptLaunchFailure({\n                        error,\n                        requestedAt,\n                        worktreePath,\n                      }),\n                    onSuccess: (setupResult) => {\n                      if (setupResult.status !== \"started\") {\n                        return Effect.void;\n                      }\n                      return recordSetupScriptStarted({\n                        requestedAt,\n                        worktreePath,\n                        scriptId: setupResult.scriptId,\n                        scriptName: setupResult.scriptName,\n                        terminalId: setupResult.terminalId,\n                      });\n                    },\n                  }),\n                );\n            });\n\n          const bootstrapProgram = Effect.gen(function* () {\n            if (bootstrap?.createThread) {\n              yield* orchestrationEngine.dispatch({\n                type: \"thread.create\",\n                commandId: yield* serverCommandId(\"bootstrap-thread-create\"),\n                threadId: command.threadId,\n                projectId: bootstrap.createThread.projectId,\n                title: bootstrap.createThread.title,\n                modelSelection: bootstrap.createThread.modelSelection,\n                runtimeMode: bootstrap.createThread.runtimeMode,\n                interactionMode: bootstrap.createThread.interactionMode,\n                branch: bootstrap.createThread.branch,\n                worktreePath: bootstrap.createThread.worktreePath,\n                createdAt: bootstrap.createThread.createdAt,\n              });\n              createdThread = true;\n            }\n\n            if (bootstrap?.prepareWorktree) {\n              let worktreeBaseRef = bootstrap.prepareWorktree.baseBranch;\n              // \"Start from origin\" is a stored default; repos without an\n              // origin remote fall back to the local base branch instead of\n              // failing the whole bootstrap on `git fetch origin`.\n              const startFromOrigin =\n                bootstrap.prepareWorktree.startFromOrigin === true &&\n                (yield* gitWorkflow.remoteExists({\n                  cwd: bootstrap.prepareWorktree.projectCwd,\n                  remoteName: \"origin\",\n                }));\n              if (startFromOrigin) {\n                yield* gitWorkflow.fetchRemote({\n                  cwd: bootstrap.prepareWorktree.projectCwd,\n                  remoteName: \"origin\",\n                });\n                const resolvedRemoteBase = yield* gitWorkflow.resolveRemoteTrackingCommit({\n                  cwd: bootstrap.prepareWorktree.projectCwd,\n                  refName: bootstrap.prepareWorktree.baseBranch,\n                  fallbackRemoteName: \"origin\",\n                });\n                worktreeBaseRef = resolvedRemoteBase.commitSha;\n              }\n              const worktree = yield* gitWorkflow.createWorktree({\n                cwd: bootstrap.prepareWorktree.projectCwd,\n                refName: worktreeBaseRef,\n                newRefName: bootstrap.prepareWorktree.branch,\n                baseRefName: bootstrap.prepareWorktree.baseBranch,\n                path: null,\n              });\n              targetWorktreePath = worktree.worktree.path;\n              yield* orchestrationEngine.dispatch({\n                type: \"thread.meta.update\",\n                commandId: yield* serverCommandId(\"bootstrap-thread-meta-update\"),\n                threadId: command.threadId,\n                branch: worktree.worktree.refName,\n                worktreePath: targetWorktreePath,\n              });\n              yield* refreshGitStatus(targetWorktreePath);\n            }\n\n            yield* runSetupProgram();\n\n            return yield* orchestrationEngine.dispatch(finalTurnStartCommand);\n          });\n\n          return yield* bootstrapProgram.pipe(\n            Effect.catchCause((cause) => {\n              const dispatchError = toBootstrapDispatchCommandCauseError(cause);\n              if (Cause.hasInterruptsOnly(cause)) {\n                return Effect.fail(dispatchError);\n              }\n              return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError)));\n            }),\n          );\n        });\n\n      const dispatchNormalizedCommand = (\n        normalizedCommand: OrchestrationCommand,\n      ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => {\n        const dispatchEffect =\n          normalizedCommand.type === \"thread.turn.start\" && normalizedCommand.bootstrap\n            ? dispatchBootstrapTurnStart(normalizedCommand)\n            : orchestrationEngine\n                .dispatch(normalizedCommand)\n                .pipe(\n                  Effect.mapError((cause) =>\n                    toDispatchCommandError(cause, \"Failed to dispatch orchestration command\"),\n                  ),\n                );\n\n        return startup\n          .enqueueCommand(dispatchEffect)\n          .pipe(\n            Effect.mapError((cause) =>\n              toDispatchCommandError(cause, \"Failed to dispatch orchestration command\"),\n            ),\n          );\n      };\n\n      const loadServerConfig = Effect.gen(function* () {\n        const keybindingsConfig = yield* keybindings.loadConfigState;\n        const providers = yield* providerRegistry.getProviders;\n        const settings = ServerSettings.redactServerSettingsForClient(\n          yield* serverSettings.getSettings,\n        );\n        const environment = yield* serverEnvironment.getDescriptor;\n        const auth = yield* serverAuth.getDescriptor();\n\n        return {\n          environment,\n          auth,\n          cwd: config.cwd,\n          keybindingsConfigPath: config.keybindingsConfigPath,\n          keybindings: keybindingsConfig.keybindings,\n          issues: keybindingsConfig.issues,\n          providers,\n          availableEditors: yield* resolveAvailableEditorsForConfig(\n            externalLauncher.resolveAvailableEditors(),\n          ),\n          observability: {\n            logsDirectoryPath: config.logsDir,\n            localTracingEnabled: true,\n            ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}),\n            otlpTracesEnabled: config.otlpTracesUrl !== undefined,\n            ...(config.otlpMetricsUrl !== undefined\n              ? { otlpMetricsUrl: config.otlpMetricsUrl }\n              : {}),\n            otlpMetricsEnabled: config.otlpMetricsUrl !== undefined,\n          },\n          settings,\n          shellResumeCompletionMarker: true,\n          threadResumeCompletionMarker: true,\n          threadSnapshotPagination: true,\n        };\n      });\n\n      const refreshGitStatus = (cwd: string) =>\n        vcsStatusBroadcaster\n          .refreshStatus(cwd)\n          .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);\n\n      return WsRpcGroup.of({\n        [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) =>\n          observeRpcEffect(\n            ORCHESTRATION_WS_METHODS.dispatchCommand,\n            Effect.gen(function* () {\n              const normalizedCommand = yield* normalizeDispatchCommand(command);\n              const shouldStopSessionAfterArchive =\n                normalizedCommand.type === \"thread.archive\"\n                  ? yield* projectionSnapshotQuery\n                      .getThreadShellById(normalizedCommand.threadId)\n                      .pipe(\n                        Effect.map(\n                          Option.match({\n                            onNone: () => false,\n                            onSome: (thread) =>\n                              thread.session !== null && thread.session.status !== \"stopped\",\n                          }),\n                        ),\n                        Effect.orElseSucceed(() => false),\n                      )\n                  : false;\n              const result = yield* dispatchNormalizedCommand(normalizedCommand);\n              if (normalizedCommand.type === \"thread.archive\") {\n                if (shouldStopSessionAfterArchive) {\n                  yield* Effect.gen(function* () {\n                    const stopCommand = yield* normalizeDispatchCommand({\n                      type: \"thread.session.stop\",\n                      commandId: CommandId.make(\n                        `session-stop-for-archive:${normalizedCommand.commandId}`,\n                      ),\n                      threadId: normalizedCommand.threadId,\n                      createdAt: yield* nowIso,\n                    });\n\n                    yield* dispatchNormalizedCommand(stopCommand);\n                  }).pipe(\n                    Effect.catchCause((cause) =>\n                      Effect.logWarning(\"failed to stop provider session during archive\", {\n                        threadId: normalizedCommand.threadId,\n                        cause,\n                      }),\n                    ),\n                  );\n                }\n\n                yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe(\n                  Effect.catch((error) =>\n                    Effect.logWarning(\"failed to close thread terminals after archive\", {\n                      threadId: normalizedCommand.threadId,\n                      error: error.message,\n                    }),\n                  ),\n                );\n              }\n              return result;\n            }).pipe(\n              Effect.mapError((cause) =>\n                isOrchestrationDispatchCommandError(cause)\n                  ? cause\n                  : new OrchestrationDispatchCommandError({\n                      message: \"Failed to dispatch orchestration command\",\n                      cause,\n                    }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.getWorkflowScript]: (input) =>\n          observeRpcEffect(\n            ORCHESTRATION_WS_METHODS.getWorkflowScript,\n            readWorkflowScript({ scriptPath: input.scriptPath }),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) =>\n          observeRpcEffect(\n            ORCHESTRATION_WS_METHODS.getTurnDiff,\n            checkpointDiffQuery.getTurnDiff(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new OrchestrationGetTurnDiffError({\n                    message: \"Failed to load turn diff\",\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) =>\n          observeRpcEffect(\n            ORCHESTRATION_WS_METHODS.getFullThreadDiff,\n            checkpointDiffQuery.getFullThreadDiff(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new OrchestrationGetFullThreadDiffError({\n                    message: \"Failed to load full thread diff\",\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.searchThreads]: (input) =>\n          observeRpcEffect(\n            ORCHESTRATION_WS_METHODS.searchThreads,\n            projectionSnapshotQuery.searchThreads(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new OrchestrationSearchThreadsError({\n                    message: \"Failed to search threads\",\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.subscribeShell]: (input) =>\n          observeRpcStreamEffect(\n            ORCHESTRATION_WS_METHODS.subscribeShell,\n            Effect.gen(function* () {\n              // Coalesce the live shell stream per aggregate over a small window\n              // so bursts of high-frequency events (streaming message deltas,\n              // activity appends) collapse into a single shell refetch and never\n              // serialize a brand-new thread's `thread.created` behind hundreds\n              // of per-event DB reads. See coalesceShellStream.\n              // Attach live delivery into a scope-bound buffer BEFORE loading any\n              // snapshot or draining catch-up, otherwise an event published while\n              // the snapshot query is in flight is lost (it is past the snapshot's\n              // sequence but the live subscription is not attached yet). Every\n              // path below emits from this same buffered live tail. Overlapping\n              // events are deduped by sequence on the client.\n              const liveBuffer = yield* Queue.unbounded<ShellLiveInput>();\n              yield* Effect.forkScoped(\n                orchestrationEngine.streamDomainEvents.pipe(\n                  Stream.runForEach((event) =>\n                    Queue.offer(liveBuffer, { kind: \"event\" as const, event }),\n                  ),\n                ),\n                { startImmediately: true },\n              );\n              const bufferedLiveStream = coalesceShellLiveStream(Stream.fromQueue(liveBuffer));\n\n              const loadSnapshot = projectionSnapshotQuery.getShellSnapshot().pipe(\n                Effect.tapError((cause) =>\n                  Effect.logError(\"orchestration shell snapshot load failed\", { cause }),\n                ),\n                Effect.mapError(\n                  (cause) =>\n                    new OrchestrationGetSnapshotError({\n                      message: \"Failed to load orchestration shell snapshot\",\n                      cause,\n                    }),\n                ),\n              );\n\n              // Offer the completion marker into the same queue as live events.\n              // Anything buffered while snapshot/replay work was in flight is\n              // therefore delivered before the client is told it is synchronized.\n              const synchronizedThenLive =\n                input.requestCompletionMarker === true\n                  ? Stream.concat(\n                      Stream.fromEffect(\n                        Queue.offer(liveBuffer, { kind: \"synchronized\" as const }).pipe(\n                          Effect.andThen(Queue.takeAll(liveBuffer)),\n                          Effect.flatMap(coalesceShellLiveInputs),\n                        ),\n                      ).pipe(Stream.flatMap((items) => Stream.fromIterable(items))),\n                      bufferedLiveStream,\n                    )\n                  : bufferedLiveStream;\n\n              // When the client already holds a shell snapshot (cached, or loaded\n              // over HTTP) it passes that snapshot's sequence, and we resume by\n              // replaying shell events after it instead of re-sending the whole\n              // projects/threads list over the socket. If the client is too far\n              // behind, we fall back to a fresh snapshot instead of an unbounded\n              // replay (see below).\n              if (input.afterSequence !== undefined) {\n                const afterSequence = input.afterSequence;\n                const headSequence = yield* orchestrationEngine.latestSequence;\n                const replayGap = headSequence - afterSequence;\n                // Gap too large: replaying every intervening event (each a shell\n                // refetch) is far more expensive than a single O(active-threads)\n                // snapshot. A cursor ahead of this engine's authoritative state\n                // is also invalid, so reset it with a snapshot. Send the snapshot\n                // followed by the buffered live tail, exactly as the\n                // no-afterSequence path does.\n                if (replayGap < 0 || replayGap > SHELL_RESUME_MAX_GAP) {\n                  const snapshot = yield* loadSnapshot;\n                  return Stream.concat(\n                    Stream.make({ kind: \"snapshot\" as const, snapshot }),\n                    synchronizedThenLive,\n                  );\n                }\n                const catchUpStream = coalesceShellStream(\n                  // Replay only through the head captured above. Newer events\n                  // are already covered by the live subscription, so this bound\n                  // cannot chase a moving event-store head or grow the live\n                  // buffer indefinitely while waiting for an empty page.\n                  orchestrationEngine.readEvents(afterSequence, replayGap),\n                ).pipe(\n                  Stream.mapError(\n                    (cause) =>\n                      new OrchestrationGetSnapshotError({\n                        message: \"Failed to replay orchestration shell events\",\n                        cause,\n                      }),\n                  ),\n                );\n                return Stream.concat(catchUpStream, synchronizedThenLive);\n              }\n\n              const snapshot = yield* loadSnapshot;\n              return Stream.concat(\n                Stream.make({\n                  kind: \"snapshot\" as const,\n                  snapshot,\n                }),\n                synchronizedThenLive,\n              );\n            }),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot]: (_input) =>\n          observeRpcEffect(\n            ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,\n            projectionSnapshotQuery.getArchivedShellSnapshot().pipe(\n              Effect.tapError((cause) =>\n                Effect.logError(\"orchestration archived shell snapshot load failed\", { cause }),\n              ),\n              Effect.mapError(\n                (cause) =>\n                  new OrchestrationGetSnapshotError({\n                    message: \"Failed to load archived orchestration shell snapshot\",\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>\n          observeRpcStreamEffect(\n            ORCHESTRATION_WS_METHODS.subscribeThread,\n            Effect.gen(function* () {\n              const isThisThreadDetailEvent = (event: OrchestrationEvent) =>\n                event.aggregateKind === \"thread\" &&\n                event.aggregateId === input.threadId &&\n                isThreadDetailEvent(event);\n\n              const liveStream = orchestrationEngine.streamDomainEvents.pipe(\n                Stream.filter(isThisThreadDetailEvent),\n                Stream.map((event) => ({\n                  kind: \"event\" as const,\n                  event: projectActivityEvent(event),\n                })),\n              );\n\n              // Attach live delivery before reading either replay or snapshot state.\n              // Otherwise an event published while the snapshot is loading is lost.\n              const liveBuffer = yield* Queue.unbounded<OrchestrationThreadStreamItem>();\n              yield* Effect.forkScoped(\n                liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),\n              );\n              const bufferedLiveStream = Stream.fromQueue(liveBuffer);\n\n              // When the client already loaded the snapshot over HTTP it passes\n              // that snapshot's sequence, and we resume the live subscription by\n              // replaying persisted events after it instead of re-sending the\n              // (potentially multi-KB) snapshot frame over the socket.\n              //\n              // The live PubSub subscription must be attached *before* draining\n              // the catch-up replay, otherwise events published during the replay\n              // window are dropped (they are past the persisted tail the replay\n              // read, but the live stream is not yet subscribed). So fork the\n              // live stream into a buffer bound to this stream's scope, then emit\n              // catch-up followed by the buffered/ongoing live events. Overlapping\n              // events are deduped by sequence on the client.\n              //\n              // The replay is bounded to the projection head captured below. The\n              // catch-up range is normally tiny (a fresh HTTP snapshot sequence),\n              // but a stale cached cursor can sit hundreds of thousands of global\n              // events behind — replaying that decodes every intervening event\n              // (including every other thread's tool payloads) only to discard\n              // almost all of them, which has OOM-killed servers on large\n              // databases. A truncated replay would silently drop this thread's\n              // events, so past the gap cap we reset the client with a fresh\n              // thread snapshot instead, exactly like subscribeShell above.\n              if (input.afterSequence !== undefined) {\n                const afterSequence = input.afterSequence;\n                const headSequence = yield* orchestrationEngine.latestSequence;\n                const replayGap = headSequence - afterSequence;\n                if (replayGap >= 0 && replayGap <= THREAD_RESUME_MAX_GAP) {\n                  const catchUpStream = orchestrationEngine\n                    .readEvents(afterSequence, replayGap)\n                    .pipe(\n                      Stream.filter(isThisThreadDetailEvent),\n                      Stream.map((event) => ({\n                        kind: \"event\" as const,\n                        event: projectActivityEvent(event),\n                      })),\n                      Stream.mapError(\n                        (cause) =>\n                          new OrchestrationGetSnapshotError({\n                            message: `Failed to replay thread ${input.threadId} events`,\n                            cause,\n                          }),\n                      ),\n                    );\n                  const afterCatchUp =\n                    input.requestCompletionMarker === true\n                      ? Stream.concat(\n                          Stream.fromEffect(\n                            Queue.offer(liveBuffer, { kind: \"synchronized\" as const }),\n                          ).pipe(Stream.drain),\n                          bufferedLiveStream,\n                        )\n                      : bufferedLiveStream;\n                  return Stream.concat(catchUpStream, afterCatchUp);\n                }\n                // Gap too large (or cursor ahead of authoritative state): fall\n                // through to the snapshot path so the client converges from a\n                // fresh thread detail instead of an unbounded replay.\n              }\n\n              const snapshot = yield* projectionSnapshotQuery\n                .getThreadDetailSnapshot(\n                  input.threadId,\n                  // Windowing the fallback snapshot is opt-in per subscription:\n                  // clients that don't send turnLimit (including all\n                  // pre-pagination clients) get the full thread, since they\n                  // have no way to load older pages.\n                  input.turnLimit === undefined ? undefined : { turnLimit: input.turnLimit },\n                )\n                .pipe(\n                  Effect.mapError(\n                    (cause) =>\n                      new OrchestrationGetSnapshotError({\n                        message: `Failed to load thread ${input.threadId}`,\n                        cause,\n                      }),\n                  ),\n                );\n\n              if (Option.isNone(snapshot)) {\n                return yield* new OrchestrationGetSnapshotError({\n                  message: `Thread ${input.threadId} was not found`,\n                  cause: input.threadId,\n                });\n              }\n\n              const afterSnapshot =\n                input.requestCompletionMarker === true\n                  ? Stream.concat(\n                      Stream.fromEffect(\n                        Queue.offer(liveBuffer, { kind: \"synchronized\" as const }),\n                      ).pipe(Stream.drain),\n                      bufferedLiveStream,\n                    )\n                  : bufferedLiveStream;\n              return Stream.concat(\n                Stream.make({\n                  kind: \"snapshot\" as const,\n                  snapshot: projectThreadDetailSnapshot(snapshot.value),\n                }),\n                afterSnapshot,\n              );\n            }),\n            { \"rpc.aggregate\": \"orchestration\" },\n          ),\n        [WS_METHODS.serverProbe]: (_input) =>\n          observeRpcEffect(WS_METHODS.serverProbe, Effect.succeed({}), {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.serverGetConfig]: (_input) =>\n          observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.serverRefreshProviders]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.serverRefreshProviders,\n            (input.instanceId !== undefined\n              ? providerRegistry.refreshInstance(input.instanceId)\n              : providerRegistry.refresh()\n            ).pipe(Effect.map((providers) => ({ providers }))),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.serverUpdateProvider]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.serverUpdateProvider,\n            providerMaintenanceRunner.updateProvider(input),\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverUpdateServer]: (input) =>\n          observeRpcEffect(WS_METHODS.serverUpdateServer, serverSelfUpdate.update(input), {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.serverUpdateServerWithProgress]: (input) =>\n          observeRpcStream(\n            WS_METHODS.serverUpdateServerWithProgress,\n            Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) =>\n              serverSelfUpdate\n                .update(input, (stage) =>\n                  Queue.offer(queue, {\n                    type: \"progress\",\n                    stage,\n                  }).pipe(Effect.asVoid),\n                )\n                .pipe(\n                  Effect.flatMap((result) =>\n                    Queue.offer(queue, {\n                      type: \"complete\",\n                      result,\n                    }),\n                  ),\n                  Effect.catchTags({\n                    ServerSelfUpdateError: (error) => Queue.fail(queue, error),\n                  }),\n                  Effect.andThen(Queue.end(queue)),\n                  Effect.forkScoped,\n                ),\n            ),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.serverUpsertKeybinding]: (rule) =>\n          observeRpcEffect(\n            WS_METHODS.serverUpsertKeybinding,\n            Effect.gen(function* () {\n              const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule);\n              return { keybindings: keybindingsConfig, issues: [] };\n            }),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.serverRemoveKeybinding]: (rule) =>\n          observeRpcEffect(\n            WS_METHODS.serverRemoveKeybinding,\n            Effect.gen(function* () {\n              const keybindingsConfig = yield* keybindings.removeKeybindingRule(rule);\n              return { keybindings: keybindingsConfig, issues: [] };\n            }),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.serverGetSettings]: (_input) =>\n          observeRpcEffect(\n            WS_METHODS.serverGetSettings,\n            serverSettings.getSettings.pipe(\n              Effect.map(ServerSettings.redactServerSettingsForClient),\n            ),\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverUpdateSettings]: ({ patch }) =>\n          observeRpcEffect(\n            WS_METHODS.serverUpdateSettings,\n            serverSettings\n              .updateSettings(patch)\n              .pipe(Effect.map(ServerSettings.redactServerSettingsForClient)),\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverDiscoverSourceControl]: (_input) =>\n          observeRpcEffect(\n            WS_METHODS.serverDiscoverSourceControl,\n            sourceControlDiscovery.discover,\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverGetTraceDiagnostics]: (_input) =>\n          observeRpcEffect(\n            WS_METHODS.serverGetTraceDiagnostics,\n            TraceDiagnostics.readTraceDiagnostics({\n              traceFilePath: config.serverTracePath,\n              maxFiles: config.traceMaxFiles,\n            }),\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverGetProcessDiagnostics]: (_input) =>\n          observeRpcEffect(WS_METHODS.serverGetProcessDiagnostics, processDiagnostics.read, {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.serverGetProcessResourceHistory]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.serverGetProcessResourceHistory,\n            processResourceMonitor.readHistory(input),\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverGetResourceTelemetryHistory]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.serverGetResourceTelemetryHistory,\n            resourceTelemetry.readHistory(input),\n            {\n              \"rpc.aggregate\": \"server\",\n            },\n          ),\n        [WS_METHODS.serverGetUsageSummary]: (input) =>\n          observeRpcEffect(WS_METHODS.serverGetUsageSummary, usage.readSummary(input), {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.serverRetryResourceTelemetry]: (_input) =>\n          observeRpcEffect(WS_METHODS.serverRetryResourceTelemetry, resourceTelemetry.retry, {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.serverSignalProcess]: (input) =>\n          observeRpcEffect(WS_METHODS.serverSignalProcess, processDiagnostics.signal(input), {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.serverReportClientActivity]: (input, metadata) =>\n          Ref.update(rpcClientIds, (clientIds) => {\n            const next = new Set(clientIds);\n            next.add(RpcClientId.make(metadata.client.id));\n            return next;\n          }).pipe(\n            Effect.andThen(\n              observeRpcEffect(\n                WS_METHODS.serverReportClientActivity,\n                backgroundPolicy.reportClientActivity(\n                  currentSessionId,\n                  RpcClientId.make(metadata.client.id),\n                  input,\n                ),\n                { \"rpc.aggregate\": \"server\" },\n              ),\n            ),\n          ),\n        [WS_METHODS.serverReportHostPowerState]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.serverReportHostPowerState,\n            backgroundPolicy.reportHostPowerState(input),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.serverGetBackgroundPolicy]: (_input) =>\n          observeRpcEffect(WS_METHODS.serverGetBackgroundPolicy, backgroundPolicy.snapshot, {\n            \"rpc.aggregate\": \"server\",\n          }),\n        [WS_METHODS.cloudGetRelayClientStatus]: (_input) =>\n          observeRpcEffect(WS_METHODS.cloudGetRelayClientStatus, relayClient.resolve, {\n            \"rpc.aggregate\": \"cloud\",\n          }),\n        [WS_METHODS.cloudInstallRelayClient]: (_input) =>\n          observeRpcStream(\n            WS_METHODS.cloudInstallRelayClient,\n            Stream.callback<RelayClientInstallProgressEvent, RelayClientInstallFailedError>(\n              (queue) =>\n                relayClient\n                  .installWithProgress((event) => Queue.offer(queue, event).pipe(Effect.asVoid))\n                  .pipe(\n                    Effect.flatMap((status) =>\n                      Queue.offer(queue, {\n                        type: \"complete\",\n                        status,\n                      }),\n                    ),\n                    Effect.catchTag(\"RelayClientInstallError\", (error) =>\n                      Queue.fail(\n                        queue,\n                        new RelayClientInstallFailedError({\n                          reason: error.reason,\n                          message: error.message,\n                        }),\n                      ),\n                    ),\n                    Effect.andThen(Queue.end(queue)),\n                    Effect.forkScoped,\n                  ),\n            ),\n            { \"rpc.aggregate\": \"cloud\" },\n          ),\n        [WS_METHODS.sourceControlLookupRepository]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.sourceControlLookupRepository,\n            sourceControlRepositories.lookupRepository(input),\n            {\n              \"rpc.aggregate\": \"source-control\",\n            },\n          ),\n        [WS_METHODS.sourceControlCloneRepository]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.sourceControlCloneRepository,\n            sourceControlRepositories.cloneRepository(input),\n            {\n              \"rpc.aggregate\": \"source-control\",\n            },\n          ),\n        [WS_METHODS.sourceControlPublishRepository]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.sourceControlPublishRepository,\n            sourceControlRepositories\n              .publishRepository(input)\n              .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),\n            {\n              \"rpc.aggregate\": \"source-control\",\n            },\n          ),\n        [WS_METHODS.projectsSearchEntries]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsSearchEntries,\n            workspaceEntries.search(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectSearchEntriesError({\n                    cwd: input.cwd,\n                    queryLength: input.query.length,\n                    limit: input.limit,\n                    ...projectEntriesFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.projectsSearchContents]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsSearchContents,\n            workspaceEntries.searchContents(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectSearchContentsError({\n                    cwd: input.cwd,\n                    queryLength: input.query.length,\n                    limit: input.limit,\n                    ...projectEntriesFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.projectsListEntries]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsListEntries,\n            workspaceEntries.list(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectListEntriesError({\n                    ...input,\n                    ...projectEntriesFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.projectsReadFile]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsReadFile,\n            workspaceFileSystem.readFile(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectReadFileError({\n                    ...input,\n                    ...projectFileFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.projectsWriteFile]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.projectsWriteFile,\n            workspaceFileSystem.writeFile(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new ProjectWriteFileError({\n                    cwd: input.cwd,\n                    relativePath: input.relativePath,\n                    ...projectFileFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.shellOpenInEditor]: (input) =>\n          observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {\n            \"rpc.aggregate\": \"workspace\",\n          }),\n        [WS_METHODS.filesystemBrowse]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.filesystemBrowse,\n            workspaceEntries.browse(input).pipe(\n              Effect.mapError(\n                (cause) =>\n                  new FilesystemBrowseError({\n                    ...input,\n                    ...filesystemBrowseFailureContext(cause),\n                    cause,\n                  }),\n              ),\n            ),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.assetsCreateUrl]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.assetsCreateUrl,\n            Effect.gen(function* () {\n              if (input.resource._tag !== \"workspace-file\") {\n                return yield* issueAssetUrl({ resource: input.resource });\n              }\n              const thread = yield* projectionSnapshotQuery\n                .getThreadShellById(input.resource.threadId)\n                .pipe(\n                  Effect.mapError(\n                    (cause) =>\n                      new AssetWorkspaceContextResolutionError({\n                        resource: input.resource,\n                        cause,\n                      }),\n                  ),\n                );\n              if (Option.isNone(thread)) {\n                return yield* new AssetWorkspaceContextNotFoundError({\n                  resource: input.resource,\n                });\n              }\n              const project = yield* projectionSnapshotQuery\n                .getProjectShellById(thread.value.projectId)\n                .pipe(\n                  Effect.mapError(\n                    (cause) =>\n                      new AssetWorkspaceContextResolutionError({\n                        resource: input.resource,\n                        cause,\n                      }),\n                  ),\n                );\n              if (Option.isNone(project)) {\n                return yield* new AssetWorkspaceContextNotFoundError({\n                  resource: input.resource,\n                });\n              }\n              return yield* issueAssetUrl({\n                resource: input.resource,\n                workspaceRoot: thread.value.worktreePath ?? project.value.workspaceRoot,\n              });\n            }),\n            { \"rpc.aggregate\": \"workspace\" },\n          ),\n        [WS_METHODS.subscribeVcsStatus]: (input) =>\n          observeRpcStream(\n            WS_METHODS.subscribeVcsStatus,\n            vcsStatusBroadcaster.streamStatus(input, {\n              automaticRemoteRefreshInterval: automaticGitFetchInterval,\n            }),\n            {\n              \"rpc.aggregate\": \"vcs\",\n            },\n          ),\n        [WS_METHODS.vcsRefreshStatus]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.vcsRefreshStatus,\n            vcsStatusBroadcaster.refreshStatus(input.cwd),\n            {\n              \"rpc.aggregate\": \"vcs\",\n            },\n          ),\n        [WS_METHODS.vcsPull]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.vcsPull,\n            gitWorkflow.pullCurrentBranch(input.cwd).pipe(\n              Effect.matchCauseEffect({\n                onFailure: (cause) => Effect.failCause(cause),\n                onSuccess: (result) =>\n                  refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)),\n              }),\n            ),\n            { \"rpc.aggregate\": \"git\" },\n          ),\n        [WS_METHODS.gitRunStackedAction]: (input) =>\n          observeRpcStream(\n            WS_METHODS.gitRunStackedAction,\n            Stream.callback<GitActionProgressEvent, GitManagerServiceError>((queue) =>\n              gitWorkflow\n                .runStackedAction(input, {\n                  actionId: input.actionId,\n                  progressReporter: {\n                    publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid),\n                  },\n                })\n                .pipe(\n                  Effect.matchCauseEffect({\n                    onFailure: (cause) => Queue.failCause(queue, cause),\n                    onSuccess: () =>\n                      refreshGitStatus(input.cwd).pipe(\n                        Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)),\n                      ),\n                  }),\n                ),\n            ),\n            { \"rpc.aggregate\": \"vcs\" },\n          ),\n        [WS_METHODS.gitResolvePullRequest]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.gitResolvePullRequest,\n            gitWorkflow.resolvePullRequest(input),\n            {\n              \"rpc.aggregate\": \"git\",\n            },\n          ),\n        [WS_METHODS.gitPreparePullRequestThread]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.gitPreparePullRequestThread,\n            gitWorkflow\n              .preparePullRequestThread(input)\n              .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),\n            { \"rpc.aggregate\": \"git\" },\n          ),\n        [WS_METHODS.vcsListRefs]: (input) =>\n          observeRpcEffect(WS_METHODS.vcsListRefs, gitWorkflow.listRefs(input), {\n            \"rpc.aggregate\": \"vcs\",\n          }),\n        [WS_METHODS.vcsCreateWorktree]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.vcsCreateWorktree,\n            gitWorkflow.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),\n            { \"rpc.aggregate\": \"vcs\" },\n          ),\n        [WS_METHODS.vcsRemoveWorktree]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.vcsRemoveWorktree,\n            gitWorkflow.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),\n            { \"rpc.aggregate\": \"vcs\" },\n          ),\n        [WS_METHODS.vcsCreateRef]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.vcsCreateRef,\n            gitWorkflow.createRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),\n            { \"rpc.aggregate\": \"vcs\" },\n          ),\n        [WS_METHODS.vcsSwitchRef]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.vcsSwitchRef,\n            gitWorkflow.switchRef(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))),\n            { \"rpc.aggregate\": \"vcs\" },\n          ),\n        [WS_METHODS.vcsInit]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.vcsInit,\n            vcsProvisioning\n              .initRepository(input)\n              .pipe(Effect.tap(() => refreshGitStatus(input.cwd))),\n            { \"rpc.aggregate\": \"vcs\" },\n          ),\n        [WS_METHODS.reviewGetDiffPreview]: (input) =>\n          observeRpcEffect(WS_METHODS.reviewGetDiffPreview, review.getDiffPreview(input), {\n            \"rpc.aggregate\": \"review\",\n          }),\n        [WS_METHODS.reviewGetDiffFileContents]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.reviewGetDiffFileContents,\n            review.getDiffFileContents(input),\n            { \"rpc.aggregate\": \"review\" },\n          ),\n        [WS_METHODS.terminalOpen]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalAttach]: (input) =>\n          observeRpcStream(\n            WS_METHODS.terminalAttach,\n            Stream.callback<TerminalAttachStreamEvent, TerminalError>((queue) =>\n              Effect.acquireRelease(\n                terminalManager.attachStream(input, (event) => Queue.offer(queue, event)),\n                (unsubscribe) => Effect.sync(unsubscribe),\n              ),\n            ),\n            { \"rpc.aggregate\": \"terminal\" },\n          ),\n        [WS_METHODS.terminalWrite]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalResize]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalClear]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalRestart]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.terminalClose]: (input) =>\n          observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), {\n            \"rpc.aggregate\": \"terminal\",\n          }),\n        [WS_METHODS.subscribeTerminalEvents]: (_input) =>\n          observeRpcStream(\n            WS_METHODS.subscribeTerminalEvents,\n            Stream.callback<TerminalEvent>((queue) =>\n              Effect.acquireRelease(\n                terminalManager.subscribe((event) => Queue.offer(queue, event)),\n                (unsubscribe) => Effect.sync(unsubscribe),\n              ),\n            ),\n            { \"rpc.aggregate\": \"terminal\" },\n          ),\n        [WS_METHODS.subscribeTerminalMetadata]: (_input) =>\n          observeRpcStream(\n            WS_METHODS.subscribeTerminalMetadata,\n            Stream.callback<TerminalMetadataStreamEvent>((queue) =>\n              Effect.acquireRelease(\n                terminalManager.subscribeMetadata((event) => Queue.offer(queue, event)),\n                (unsubscribe) => Effect.sync(unsubscribe),\n              ),\n            ),\n            { \"rpc.aggregate\": \"terminal\" },\n          ),\n        [WS_METHODS.previewOpen]: (input) =>\n          observeRpcEffect(WS_METHODS.previewOpen, previewManager.open(input), {\n            \"rpc.aggregate\": \"preview\",\n          }),\n        [WS_METHODS.previewNavigate]: (input) =>\n          observeRpcEffect(WS_METHODS.previewNavigate, previewManager.navigate(input), {\n            \"rpc.aggregate\": \"preview\",\n          }),\n        [WS_METHODS.previewResize]: (input) =>\n          observeRpcEffect(WS_METHODS.previewResize, previewManager.resize(input), {\n            \"rpc.aggregate\": \"preview\",\n          }),\n        [WS_METHODS.previewRefresh]: (input) =>\n          observeRpcEffect(WS_METHODS.previewRefresh, previewManager.refresh(input), {\n            \"rpc.aggregate\": \"preview\",\n          }),\n        [WS_METHODS.previewClose]: (input) =>\n          observeRpcEffect(WS_METHODS.previewClose, previewManager.close(input), {\n            \"rpc.aggregate\": \"preview\",\n          }),\n        [WS_METHODS.previewList]: (input) =>\n          observeRpcEffect(WS_METHODS.previewList, previewManager.list(input), {\n            \"rpc.aggregate\": \"preview\",\n          }),\n        [WS_METHODS.previewReportStatus]: (input) =>\n          observeRpcEffect(WS_METHODS.previewReportStatus, previewManager.reportStatus(input), {\n            \"rpc.aggregate\": \"preview\",\n          }),\n        [WS_METHODS.previewAutomationConnect]: (input) =>\n          observeRpcStreamEffect(\n            WS_METHODS.previewAutomationConnect,\n            previewAutomationBroker.connect(input),\n            { \"rpc.aggregate\": \"preview-automation\" },\n          ),\n        [WS_METHODS.previewAutomationRespond]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.previewAutomationRespond,\n            previewAutomationBroker.respond(input),\n            { \"rpc.aggregate\": \"preview-automation\" },\n          ),\n        [WS_METHODS.previewAutomationFocusHost]: (input) =>\n          observeRpcEffect(\n            WS_METHODS.previewAutomationFocusHost,\n            previewAutomationBroker.focusHost(input),\n            { \"rpc.aggregate\": \"preview-automation\" },\n          ),\n        [WS_METHODS.subscribePreviewEvents]: (_input) =>\n          observeRpcStream(WS_METHODS.subscribePreviewEvents, previewManager.events, {\n            \"rpc.aggregate\": \"preview\",\n          }),\n        [WS_METHODS.subscribeDiscoveredLocalServers]: (_input) =>\n          observeRpcStream(\n            WS_METHODS.subscribeDiscoveredLocalServers,\n            Stream.callback<DiscoveredLocalServerList>((queue) =>\n              Effect.gen(function* () {\n                yield* portDiscovery.retain;\n                const initial = yield* portDiscovery.scan();\n                const initialScannedAt = DateTime.formatIso(yield* DateTime.now);\n                yield* Queue.offer(queue, {\n                  servers: initial,\n                  scannedAt: initialScannedAt,\n                });\n                yield* portDiscovery.subscribe((servers) =>\n                  Effect.gen(function* () {\n                    const scannedAt = DateTime.formatIso(yield* DateTime.now);\n                    yield* Queue.offer(queue, { servers, scannedAt });\n                  }),\n                );\n              }),\n            ),\n            { \"rpc.aggregate\": \"preview\" },\n          ),\n        [WS_METHODS.subscribeServerConfig]: (_input) =>\n          observeRpcStreamEffect(\n            WS_METHODS.subscribeServerConfig,\n            Effect.gen(function* () {\n              const keybindingsUpdates = keybindings.streamChanges.pipe(\n                Stream.map((event) => ({\n                  version: 1 as const,\n                  type: \"keybindingsUpdated\" as const,\n                  payload: {\n                    keybindings: event.keybindings,\n                    issues: event.issues,\n                  },\n                })),\n              );\n              const providerStatuses = providerRegistry.streamChanges.pipe(\n                Stream.map((providers) => ({\n                  version: 1 as const,\n                  type: \"providerStatuses\" as const,\n                  payload: { providers },\n                })),\n                Stream.debounce(Duration.millis(PROVIDER_STATUS_DEBOUNCE_MS)),\n              );\n              const settingsUpdates = serverSettings.streamChanges.pipe(\n                Stream.map((settings) => ServerSettings.redactServerSettingsForClient(settings)),\n                Stream.map((settings) => ({\n                  version: 1 as const,\n                  type: \"settingsUpdated\" as const,\n                  payload: { settings },\n                })),\n              );\n\n              yield* providerRegistry\n                .refresh()\n                .pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);\n\n              const liveUpdates = Stream.merge(\n                keybindingsUpdates,\n                Stream.merge(providerStatuses, settingsUpdates),\n              );\n\n              return Stream.concat(\n                Stream.make({\n                  version: 1 as const,\n                  type: \"snapshot\" as const,\n                  config: yield* loadServerConfig,\n                }),\n                liveUpdates,\n              );\n            }),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.subscribeServerLifecycle]: (_input) =>\n          observeRpcStreamEffect(\n            WS_METHODS.subscribeServerLifecycle,\n            Effect.gen(function* () {\n              const snapshot = yield* lifecycleEvents.snapshot;\n              const snapshotEvents = Array.from(snapshot.events).toSorted(\n                (left, right) => left.sequence - right.sequence,\n              );\n              const liveEvents = lifecycleEvents.stream.pipe(\n                Stream.filter((event) => event.sequence > snapshot.sequence),\n              );\n              return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents);\n            }),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.subscribeAuthAccess]: (_input) =>\n          observeRpcStreamEffect(\n            WS_METHODS.subscribeAuthAccess,\n            Effect.gen(function* () {\n              const initialSnapshot = yield* loadAuthAccessSnapshot();\n              const revisionRef = yield* Ref.make(1);\n              const accessChanges: Stream.Stream<\n                PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange\n              > = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges);\n\n              const liveEvents: Stream.Stream<AuthAccessStreamEvent> = accessChanges.pipe(\n                Stream.mapEffect((change) =>\n                  Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe(\n                    Effect.map((revision) =>\n                      toAuthAccessStreamEvent(change, revision, currentSessionId),\n                    ),\n                  ),\n                ),\n              );\n\n              return Stream.concat(\n                Stream.make({\n                  version: 1 as const,\n                  revision: 1,\n                  type: \"snapshot\" as const,\n                  payload: initialSnapshot,\n                }),\n                liveEvents,\n              );\n            }),\n            { \"rpc.aggregate\": \"auth\" },\n          ),\n        [WS_METHODS.subscribeBackgroundPolicy]: (_input) =>\n          observeRpcStream(\n            WS_METHODS.subscribeBackgroundPolicy,\n            Stream.unwrap(\n              Effect.map(backgroundPolicy.subscribe, ({ latest, changes }) =>\n                Stream.concat(Stream.make(latest), changes),\n              ),\n            ),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n        [WS_METHODS.subscribeResourceTelemetry]: (_input) =>\n          observeRpcStream(\n            WS_METHODS.subscribeResourceTelemetry,\n            Stream.unwrap(\n              Effect.map(resourceTelemetry.subscribe, ({ latest, changes }) =>\n                Stream.concat(Stream.make(latest), changes),\n              ),\n            ),\n            { \"rpc.aggregate\": \"server\" },\n          ),\n      });\n    }),\n  );\n\nexport const websocketRpcRouteLayer = Layer.unwrap(\n  Effect.gen(function* () {\n    const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;\n    const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;\n    return HttpRouter.add(\n      \"GET\",\n      \"/ws\",\n      Effect.gen(function* () {\n        const request = yield* HttpServerRequest.HttpServerRequest;\n        const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;\n        const sessions = yield* SessionStore.SessionStore;\n        const session = yield* serverAuth.authenticateWebSocketUpgrade(request).pipe(\n          Effect.catchIf(EnvironmentAuth.isServerAuthCredentialError, (error) =>\n            failEnvironmentAuthInvalid(EnvironmentAuth.serverAuthCredentialReason(error)),\n          ),\n          Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n            failEnvironmentInternal(\"internal_error\", error),\n          ),\n        );\n        const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, {\n          disableTracing: true,\n        }).pipe(\n          Effect.provide(\n            makeWsRpcLayer(session, previewAutomationBroker).pipe(\n              Layer.provideMerge(RpcSerialization.layerJson),\n              Layer.provide(ProviderMaintenanceRunner.layer),\n              Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),\n              Layer.provide(\n                SourceControlDiscovery.layer.pipe(\n                  Layer.provide(\n                    SourceControlProviderRegistry.layer.pipe(\n                      Layer.provide(\n                        Layer.mergeAll(\n                          AzureDevOpsCli.layer,\n                          BitbucketApi.layer,\n                          GitHubCli.layer,\n                          GitLabCli.layer,\n                        ),\n                      ),\n                      Layer.provideMerge(GitVcsDriver.layer),\n                      Layer.provide(\n                        VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer)),\n                      ),\n                    ),\n                  ),\n                  Layer.provide(VcsProcess.layer),\n                ),\n              ),\n            ),\n          ),\n        );\n        return yield* Effect.acquireUseRelease(\n          sessions.markConnected(session.sessionId),\n          () => rpcWebSocketHttpEffect,\n          () => sessions.markDisconnected(session.sessionId),\n        );\n      }).pipe(\n        Effect.catchTags({\n          EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,\n          EnvironmentInternalError: HttpServerRespondable.toResponse,\n        }),\n      ),\n    );\n  }),\n);\n","import * as Arr from \"effect/Array\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Struct from \"effect/Struct\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\nimport * as SqlSchema from \"effect/unstable/sql/SqlSchema\";\n\nimport {\n  IsoDateTime,\n  ProviderInstanceId,\n  ProviderSessionRuntimeStatus,\n  RuntimeMode,\n  ThreadId,\n} from \"@t3tools/contracts\";\n\nimport {\n  PersistenceDecodeError,\n  type PersistenceErrorCorrelation,\n  PersistenceSqlError,\n  type ProviderSessionRuntimeRepositoryError,\n} from \"./Errors.ts\";\n\n/**\n * ProviderSessionRuntimeRepository - Repository interface for provider runtime sessions.\n *\n * Owns persistence operations for provider runtime metadata and resume cursors.\n *\n * @module ProviderSessionRuntimeRepository\n */\n\nexport const ProviderSessionRuntime = Schema.Struct({\n  threadId: ThreadId,\n  providerName: Schema.String,\n  /**\n   * User-defined routing key for the configured provider instance that\n   * owns this session. Nullable only at the storage/migration boundary:\n   * rows persisted before the driver/instance split carry only\n   * `providerName`. Repository consumers must materialize a concrete\n   * instance id before routing.\n   */\n  providerInstanceId: Schema.NullOr(ProviderInstanceId),\n  adapterKey: Schema.String,\n  runtimeMode: RuntimeMode,\n  status: ProviderSessionRuntimeStatus,\n  lastSeenAt: IsoDateTime,\n  resumeCursor: Schema.NullOr(Schema.Unknown),\n  runtimePayload: Schema.NullOr(Schema.Unknown),\n});\nexport type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;\n\nexport const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });\nexport type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;\n\nexport const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });\nexport type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;\n\n/**\n * ProviderSessionRuntimeRepository - Service tag for provider runtime persistence.\n */\nexport class ProviderSessionRuntimeRepository extends Context.Service<\n  ProviderSessionRuntimeRepository,\n  {\n    /**\n     * Insert or replace a provider runtime row.\n     *\n     * Upserts by canonical `threadId`, including JSON payload/cursor fields.\n     */\n    readonly upsert: (\n      runtime: ProviderSessionRuntime,\n    ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;\n\n    /**\n     * Read provider runtime state by canonical thread id.\n     */\n    readonly getByThreadId: (\n      input: GetProviderSessionRuntimeInput,\n    ) => Effect.Effect<\n      Option.Option<ProviderSessionRuntime>,\n      ProviderSessionRuntimeRepositoryError\n    >;\n\n    /**\n     * List all provider runtime rows.\n     *\n     * Returned in ascending last-seen order.\n     */\n    readonly list: () => Effect.Effect<\n      ReadonlyArray<ProviderSessionRuntime>,\n      ProviderSessionRuntimeRepositoryError\n    >;\n\n    /**\n     * Delete provider runtime state by canonical thread id.\n     */\n    readonly deleteByThreadId: (\n      input: DeleteProviderSessionRuntimeInput,\n    ) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;\n  }\n>()(\"t3/persistence/ProviderSessionRuntime/ProviderSessionRuntimeRepository\") {}\n\nconst ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(\n  Struct.assign({\n    resumeCursor: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),\n    runtimePayload: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),\n  }),\n);\n\nconst ProviderSessionRuntimeRawDbRowSchema = Schema.Struct({\n  threadId: Schema.String,\n  providerName: Schema.Unknown,\n  providerInstanceId: Schema.Unknown,\n  adapterKey: Schema.Unknown,\n  runtimeMode: Schema.Unknown,\n  status: Schema.Unknown,\n  lastSeenAt: Schema.Unknown,\n  resumeCursor: Schema.Unknown,\n  runtimePayload: Schema.Unknown,\n});\n\nconst decodeRuntimeRow = Schema.decodeUnknownEffect(ProviderSessionRuntimeDbRowSchema);\n\nconst GetRuntimeRequestSchema = Schema.Struct({\n  threadId: ThreadId,\n});\n\nconst DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;\n\nfunction toPersistenceSqlOrDecodeError(\n  sqlOperation: string,\n  decodeOperation: string,\n  correlation?: PersistenceErrorCorrelation,\n) {\n  return (cause: unknown): ProviderSessionRuntimeRepositoryError =>\n    Schema.isSchemaError(cause)\n      ? PersistenceDecodeError.fromSchemaError(decodeOperation, cause, correlation)\n      : new PersistenceSqlError({\n          operation: sqlOperation,\n          ...(correlation === undefined ? {} : { correlation }),\n          cause,\n        });\n}\n\nexport const make = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n\n  const upsertRuntimeRow = SqlSchema.void({\n    Request: ProviderSessionRuntimeDbRowSchema,\n    execute: (runtime) =>\n      sql`\n        INSERT INTO provider_session_runtime (\n          thread_id,\n          provider_name,\n          provider_instance_id,\n          adapter_key,\n          runtime_mode,\n          status,\n          last_seen_at,\n          resume_cursor_json,\n          runtime_payload_json\n        )\n        VALUES (\n          ${runtime.threadId},\n          ${runtime.providerName},\n          ${runtime.providerInstanceId},\n          ${runtime.adapterKey},\n          ${runtime.runtimeMode},\n          ${runtime.status},\n          ${runtime.lastSeenAt},\n          ${runtime.resumeCursor},\n          ${runtime.runtimePayload}\n        )\n        ON CONFLICT (thread_id)\n        DO UPDATE SET\n          provider_name = excluded.provider_name,\n          provider_instance_id = excluded.provider_instance_id,\n          adapter_key = excluded.adapter_key,\n          runtime_mode = excluded.runtime_mode,\n          status = excluded.status,\n          last_seen_at = excluded.last_seen_at,\n          resume_cursor_json = excluded.resume_cursor_json,\n          runtime_payload_json = excluded.runtime_payload_json\n      `,\n  });\n\n  const getRuntimeRowByThreadId = SqlSchema.findOneOption({\n    Request: GetRuntimeRequestSchema,\n    Result: ProviderSessionRuntimeRawDbRowSchema,\n    execute: ({ threadId }) =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          adapter_key AS \"adapterKey\",\n          runtime_mode AS \"runtimeMode\",\n          status,\n          last_seen_at AS \"lastSeenAt\",\n          resume_cursor_json AS \"resumeCursor\",\n          runtime_payload_json AS \"runtimePayload\"\n        FROM provider_session_runtime\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const listRuntimeRows = SqlSchema.findAll({\n    Request: Schema.Void,\n    Result: ProviderSessionRuntimeRawDbRowSchema,\n    execute: () =>\n      sql`\n        SELECT\n          thread_id AS \"threadId\",\n          provider_name AS \"providerName\",\n          provider_instance_id AS \"providerInstanceId\",\n          adapter_key AS \"adapterKey\",\n          runtime_mode AS \"runtimeMode\",\n          status,\n          last_seen_at AS \"lastSeenAt\",\n          resume_cursor_json AS \"resumeCursor\",\n          runtime_payload_json AS \"runtimePayload\"\n        FROM provider_session_runtime\n        ORDER BY last_seen_at ASC, thread_id ASC\n      `,\n  });\n\n  const deleteRuntimeByThreadId = SqlSchema.void({\n    Request: DeleteRuntimeRequestSchema,\n    execute: ({ threadId }) =>\n      sql`\n        DELETE FROM provider_session_runtime\n        WHERE thread_id = ${threadId}\n      `,\n  });\n\n  const upsert: ProviderSessionRuntimeRepository[\"Service\"][\"upsert\"] = (runtime) =>\n    upsertRuntimeRow(runtime).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProviderSessionRuntimeRepository.upsert:query\",\n          \"ProviderSessionRuntimeRepository.upsert:encodeRequest\",\n          { threadId: runtime.threadId },\n        ),\n      ),\n    );\n\n  const getByThreadId: ProviderSessionRuntimeRepository[\"Service\"][\"getByThreadId\"] = (input) =>\n    getRuntimeRowByThreadId(input).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProviderSessionRuntimeRepository.getByThreadId:query\",\n          \"ProviderSessionRuntimeRepository.getByThreadId:decodeRow\",\n          { threadId: input.threadId },\n        ),\n      ),\n      Effect.flatMap((runtimeRowOption) =>\n        Option.match(runtimeRowOption, {\n          onNone: () => Effect.succeed(Option.none()),\n          onSome: (row) =>\n            decodeRuntimeRow(row).pipe(\n              Effect.mapError((cause) =>\n                PersistenceDecodeError.fromSchemaError(\n                  \"ProviderSessionRuntimeRepository.getByThreadId:decodeRow\",\n                  cause,\n                  { threadId: input.threadId },\n                ),\n              ),\n              Effect.map((runtime) => Option.some(runtime)),\n            ),\n        }),\n      ),\n    );\n\n  const list: ProviderSessionRuntimeRepository[\"Service\"][\"list\"] = () =>\n    listRuntimeRows(undefined).pipe(\n      Effect.mapError(\n        toPersistenceSqlOrDecodeError(\n          \"ProviderSessionRuntimeRepository.list:query\",\n          \"ProviderSessionRuntimeRepository.list:decodeRows\",\n        ),\n      ),\n      Effect.flatMap((rows) =>\n        // Skip rows that no longer decode (e.g. written by an older build)\n        // instead of failing the whole list — one stale row must not disable\n        // every consumer that enumerates sessions, such as the reaper.\n        Effect.forEach(rows, (row) =>\n          decodeRuntimeRow(row).pipe(\n            Effect.map(Option.some),\n            Effect.catch((cause) =>\n              Effect.logWarning(\"provider.session.runtime.row-skipped\", {\n                threadId: row.threadId,\n                error: PersistenceDecodeError.fromSchemaError(\n                  \"ProviderSessionRuntimeRepository.list:decodeRows\",\n                  cause,\n                  { threadId: row.threadId },\n                ).message,\n              }).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),\n            ),\n          ),\n        ),\n      ),\n      Effect.map((decoded) =>\n        Arr.filterMap(decoded, (row) =>\n          Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,\n        ),\n      ),\n    );\n\n  const deleteByThreadId: ProviderSessionRuntimeRepository[\"Service\"][\"deleteByThreadId\"] = (\n    input,\n  ) =>\n    deleteRuntimeByThreadId(input).pipe(\n      Effect.mapError(\n        (cause) =>\n          new PersistenceSqlError({\n            operation: \"ProviderSessionRuntimeRepository.deleteByThreadId:query\",\n            correlation: { threadId: input.threadId },\n            cause,\n          }),\n      ),\n    );\n\n  return {\n    upsert,\n    getByThreadId,\n    list,\n    deleteByThreadId,\n  } satisfies ProviderSessionRuntimeRepository[\"Service\"];\n});\n\nexport const layer = Layer.effect(ProviderSessionRuntimeRepository, make);\n","import * as Schema from \"effect/Schema\";\n\nimport type { CheckpointServiceError } from \"../checkpointing/Errors.ts\";\n\n/**\n * ProviderAdapterValidationError - Invalid adapter API input.\n */\nexport class ProviderAdapterValidationError extends Schema.TaggedErrorClass<ProviderAdapterValidationError>()(\n  \"ProviderAdapterValidationError\",\n  {\n    provider: Schema.String,\n    operation: Schema.String,\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider adapter validation failed (${this.provider}) in ${this.operation}: ${this.issue}`;\n  }\n}\n\n/**\n * ProviderAdapterSessionNotFoundError - Adapter-owned session id is unknown.\n */\nexport class ProviderAdapterSessionNotFoundError extends Schema.TaggedErrorClass<ProviderAdapterSessionNotFoundError>()(\n  \"ProviderAdapterSessionNotFoundError\",\n  {\n    provider: Schema.String,\n    threadId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Unknown ${this.provider} adapter thread: ${this.threadId}`;\n  }\n}\n\n/**\n * ProviderAdapterSessionClosedError - Adapter session exists but is closed.\n */\nexport class ProviderAdapterSessionClosedError extends Schema.TaggedErrorClass<ProviderAdapterSessionClosedError>()(\n  \"ProviderAdapterSessionClosedError\",\n  {\n    provider: Schema.String,\n    threadId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `${this.provider} adapter thread is closed: ${this.threadId}`;\n  }\n}\n\n/**\n * ProviderAdapterRequestError - Provider protocol request failed or timed out.\n */\nexport class ProviderAdapterRequestError extends Schema.TaggedErrorClass<ProviderAdapterRequestError>()(\n  \"ProviderAdapterRequestError\",\n  {\n    provider: Schema.String,\n    method: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider adapter request failed (${this.provider}) for ${this.method}: ${this.detail}`;\n  }\n}\n\n/**\n * ProviderAdapterProcessError - Provider process lifecycle failure.\n */\nexport class ProviderAdapterProcessError extends Schema.TaggedErrorClass<ProviderAdapterProcessError>()(\n  \"ProviderAdapterProcessError\",\n  {\n    provider: Schema.String,\n    threadId: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider adapter process error (${this.provider}) for thread ${this.threadId}: ${this.detail}`;\n  }\n}\n\n/**\n * ProviderValidationError - Invalid provider API input.\n */\nexport class ProviderValidationError extends Schema.TaggedErrorClass<ProviderValidationError>()(\n  \"ProviderValidationError\",\n  {\n    operation: Schema.String,\n    issue: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider validation failed in ${this.operation}: ${this.issue}`;\n  }\n}\n\n/**\n * ProviderUnsupportedError - Requested provider is not implemented.\n */\nexport class ProviderUnsupportedError extends Schema.TaggedErrorClass<ProviderUnsupportedError>()(\n  \"ProviderUnsupportedError\",\n  {\n    provider: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider '${this.provider}' is not implemented`;\n  }\n}\n\n/**\n * ProviderInstanceNotFoundError - Lookup against the instance registry failed.\n *\n * Distinct from `ProviderUnsupportedError`: the driver is registered, but no\n * instance with the requested id has been bootstrapped — typically because\n * the persisted instance id refers to an instance the user removed from\n * settings, or because routing is asked for an instance before the registry\n * has finished its first reload.\n */\nexport class ProviderInstanceNotFoundError extends Schema.TaggedErrorClass<ProviderInstanceNotFoundError>()(\n  \"ProviderInstanceNotFoundError\",\n  {\n    instanceId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `No provider instance bound to id '${this.instanceId}'`;\n  }\n}\n\n/**\n * ProviderDriverError - A driver `create` call failed before producing an\n * instance. Surfaced to the registry, which marks the offending entry as\n * an \"unavailable\" shadow snapshot rather than crashing the server.\n */\nexport class ProviderDriverError extends Schema.TaggedErrorClass<ProviderDriverError>()(\n  \"ProviderDriverError\",\n  {\n    driver: Schema.String,\n    instanceId: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider driver '${this.driver}' failed to create instance '${this.instanceId}': ${this.detail}`;\n  }\n}\n\n/**\n * ProviderSessionNotFoundError - Provider-facing session not found.\n */\nexport class ProviderSessionNotFoundError extends Schema.TaggedErrorClass<ProviderSessionNotFoundError>()(\n  \"ProviderSessionNotFoundError\",\n  {\n    threadId: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Unknown provider thread: ${this.threadId}`;\n  }\n}\n\n/**\n * ProviderSessionDirectoryPersistenceError - Session directory persistence failure.\n */\nexport class ProviderSessionDirectoryPersistenceError extends Schema.TaggedErrorClass<ProviderSessionDirectoryPersistenceError>()(\n  \"ProviderSessionDirectoryPersistenceError\",\n  {\n    operation: Schema.String,\n    detail: Schema.String,\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Provider session directory persistence error in ${this.operation}: ${this.detail}`;\n  }\n}\n\nexport type ProviderAdapterError =\n  | ProviderAdapterValidationError\n  | ProviderAdapterSessionNotFoundError\n  | ProviderAdapterSessionClosedError\n  | ProviderAdapterRequestError\n  | ProviderAdapterProcessError;\n\nexport type ProviderServiceError =\n  | ProviderValidationError\n  | ProviderUnsupportedError\n  | ProviderInstanceNotFoundError\n  | ProviderSessionNotFoundError\n  | ProviderSessionDirectoryPersistenceError\n  | ProviderAdapterError\n  | CheckpointServiceError;\n","import type {\n  ProviderInstanceId,\n  ProviderDriverKind,\n  ProviderSessionRuntimeStatus,\n  RuntimeMode,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Option from \"effect/Option\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nimport type {\n  ProviderSessionDirectoryPersistenceError,\n  ProviderValidationError,\n} from \"../Errors.ts\";\n\nexport interface ProviderRuntimeBinding {\n  readonly threadId: ThreadId;\n  readonly provider: ProviderDriverKind;\n  /**\n   * Routing key for the configured provider instance that owns this\n   * session. The persistence layer promotes legacy null rows before\n   * exposing bindings; runtime callers must not infer this from `provider`.\n   */\n  readonly providerInstanceId?: ProviderInstanceId;\n  readonly adapterKey?: string;\n  readonly status?: ProviderSessionRuntimeStatus;\n  readonly resumeCursor?: unknown | null;\n  readonly runtimePayload?: unknown | null;\n  readonly runtimeMode?: RuntimeMode;\n}\n\nexport interface ProviderRuntimeBindingWithMetadata extends ProviderRuntimeBinding {\n  readonly lastSeenAt: string;\n}\n\nexport type ProviderSessionDirectoryReadError = ProviderSessionDirectoryPersistenceError;\n\nexport type ProviderSessionDirectoryWriteError =\n  | ProviderValidationError\n  | ProviderSessionDirectoryPersistenceError;\n\nexport interface ProviderSessionDirectoryShape {\n  readonly upsert: (\n    binding: ProviderRuntimeBinding,\n  ) => Effect.Effect<void, ProviderSessionDirectoryWriteError>;\n\n  readonly getProvider: (\n    threadId: ThreadId,\n  ) => Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryReadError>;\n\n  readonly getBinding: (\n    threadId: ThreadId,\n  ) => Effect.Effect<Option.Option<ProviderRuntimeBinding>, ProviderSessionDirectoryReadError>;\n\n  readonly listThreadIds: () => Effect.Effect<\n    ReadonlyArray<ThreadId>,\n    ProviderSessionDirectoryPersistenceError\n  >;\n\n  readonly listBindings: () => Effect.Effect<\n    ReadonlyArray<ProviderRuntimeBindingWithMetadata>,\n    ProviderSessionDirectoryPersistenceError\n  >;\n}\n\nexport class ProviderSessionDirectory extends Context.Service<\n  ProviderSessionDirectory,\n  ProviderSessionDirectoryShape\n>()(\"t3/provider/Services/ProviderSessionDirectory\") {}\n","import { defaultInstanceIdForDriver, ProviderDriverKind, type ThreadId } from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ProviderSessionRuntime from \"../../persistence/ProviderSessionRuntime.ts\";\nimport { ProviderSessionDirectoryPersistenceError, ProviderValidationError } from \"../Errors.ts\";\nimport {\n  ProviderSessionDirectory,\n  type ProviderRuntimeBinding,\n  type ProviderRuntimeBindingWithMetadata,\n  type ProviderSessionDirectoryShape,\n} from \"../Services/ProviderSessionDirectory.ts\";\nconst decodeProviderDriverKindValue = Schema.decodeUnknownEffect(ProviderDriverKind);\n\nfunction toPersistenceError(operation: string) {\n  return (cause: unknown) =>\n    new ProviderSessionDirectoryPersistenceError({\n      operation,\n      detail: `Failed to execute ${operation}.`,\n      cause,\n    });\n}\n\nfunction decodeProviderDriverKind(\n  providerName: string,\n  operation: string,\n): Effect.Effect<ProviderDriverKind, ProviderSessionDirectoryPersistenceError> {\n  return decodeProviderDriverKindValue(providerName).pipe(\n    Effect.mapError(\n      (cause) =>\n        new ProviderSessionDirectoryPersistenceError({\n          operation,\n          detail: `Unknown persisted provider '${providerName}'.`,\n          cause,\n        }),\n    ),\n  );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction mergeRuntimePayload(\n  existing: unknown | null,\n  next: unknown | null | undefined,\n): unknown | null {\n  if (next === undefined) {\n    return existing ?? null;\n  }\n  if (isRecord(existing) && isRecord(next)) {\n    return { ...existing, ...next };\n  }\n  return next;\n}\n\nfunction toRuntimeBinding(\n  runtime: ProviderSessionRuntime.ProviderSessionRuntime,\n  operation: string,\n): Effect.Effect<ProviderRuntimeBindingWithMetadata, ProviderSessionDirectoryPersistenceError> {\n  return decodeProviderDriverKind(runtime.providerName, operation).pipe(\n    Effect.map(\n      (provider) =>\n        ({\n          threadId: runtime.threadId,\n          provider,\n          // Migration boundary only: rows written before the instance split\n          // have a null provider_instance_id. Promote them as they leave\n          // persistence so hot routing code never has to infer an instance\n          // from a driver kind.\n          providerInstanceId: runtime.providerInstanceId ?? defaultInstanceIdForDriver(provider),\n          adapterKey: runtime.adapterKey,\n          runtimeMode: runtime.runtimeMode,\n          status: runtime.status,\n          resumeCursor: runtime.resumeCursor,\n          runtimePayload: runtime.runtimePayload,\n          lastSeenAt: runtime.lastSeenAt,\n        }) satisfies ProviderRuntimeBindingWithMetadata,\n    ),\n  );\n}\n\nconst makeProviderSessionDirectory = Effect.gen(function* () {\n  const repository = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;\n\n  const getBinding = (threadId: ThreadId) =>\n    repository.getByThreadId({ threadId }).pipe(\n      Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.getBinding:getByThreadId\")),\n      Effect.flatMap((runtime) =>\n        Option.match(runtime, {\n          onNone: () => Effect.succeed(Option.none<ProviderRuntimeBinding>()),\n          onSome: (value) =>\n            toRuntimeBinding(value, \"ProviderSessionDirectory.getBinding\").pipe(\n              Effect.map((binding) => Option.some(binding)),\n            ),\n        }),\n      ),\n    );\n\n  const upsert: ProviderSessionDirectoryShape[\"upsert\"] = Effect.fn(function* (binding) {\n    const existing = yield* repository\n      .getByThreadId({ threadId: binding.threadId })\n      .pipe(Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.upsert:getByThreadId\")));\n\n    const existingRuntime = Option.getOrUndefined(existing);\n    const resolvedThreadId = binding.threadId ?? existingRuntime?.threadId;\n    if (!resolvedThreadId) {\n      return yield* new ProviderValidationError({\n        operation: \"ProviderSessionDirectory.upsert\",\n        issue: \"threadId must be a non-empty string.\",\n      });\n    }\n\n    const now = DateTime.formatIso(yield* DateTime.now);\n    const providerChanged =\n      existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;\n    const providerInstanceId =\n      binding.providerInstanceId ?? (!providerChanged ? existingRuntime?.providerInstanceId : null);\n    if (providerInstanceId === null || providerInstanceId === undefined) {\n      return yield* new ProviderValidationError({\n        operation: \"ProviderSessionDirectory.upsert\",\n        issue: \"providerInstanceId is required for provider session runtime bindings.\",\n      });\n    }\n    yield* repository\n      .upsert({\n        threadId: resolvedThreadId,\n        providerName: binding.provider,\n        providerInstanceId,\n        adapterKey:\n          binding.adapterKey ??\n          (providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),\n        runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? \"full-access\",\n        status: binding.status ?? existingRuntime?.status ?? \"running\",\n        lastSeenAt: now,\n        resumeCursor:\n          binding.resumeCursor !== undefined\n            ? binding.resumeCursor\n            : (existingRuntime?.resumeCursor ?? null),\n        runtimePayload: mergeRuntimePayload(\n          existingRuntime?.runtimePayload ?? null,\n          binding.runtimePayload,\n        ),\n      })\n      .pipe(Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.upsert:upsert\")));\n  });\n\n  const getProvider: ProviderSessionDirectoryShape[\"getProvider\"] = (threadId) =>\n    getBinding(threadId).pipe(\n      Effect.flatMap((binding) =>\n        Option.match(binding, {\n          onSome: (value) => Effect.succeed(value.provider),\n          onNone: () =>\n            Effect.fail(\n              new ProviderSessionDirectoryPersistenceError({\n                operation: \"ProviderSessionDirectory.getProvider\",\n                detail: `No persisted provider binding found for thread '${threadId}'.`,\n              }),\n            ),\n        }),\n      ),\n    );\n\n  const listThreadIds: ProviderSessionDirectoryShape[\"listThreadIds\"] = () =>\n    repository.list().pipe(\n      Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.listThreadIds:list\")),\n      Effect.map((rows) => rows.map((row) => row.threadId)),\n    );\n\n  const listBindings: ProviderSessionDirectoryShape[\"listBindings\"] = () =>\n    repository.list().pipe(\n      Effect.mapError(toPersistenceError(\"ProviderSessionDirectory.listBindings:list\")),\n      Effect.flatMap((rows) =>\n        Effect.forEach(\n          rows,\n          (row) => toRuntimeBinding(row, \"ProviderSessionDirectory.listBindings\"),\n          { concurrency: \"unbounded\" },\n        ),\n      ),\n    );\n\n  return {\n    upsert,\n    getProvider,\n    getBinding,\n    listThreadIds,\n    listBindings,\n  } satisfies ProviderSessionDirectoryShape;\n});\n\nexport const ProviderSessionDirectoryLive = Layer.effect(\n  ProviderSessionDirectory,\n  makeProviderSessionDirectory,\n);\n\nexport function makeProviderSessionDirectoryLive() {\n  return Layer.effect(ProviderSessionDirectory, makeProviderSessionDirectory);\n}\n","/**\n * ProviderAdapterRegistry - Lookup boundary for provider adapter implementations.\n *\n * Maps a `ProviderInstanceId` (the new per-instance routing key) or a\n * `ProviderDriverKind` (legacy single-instance-per-driver key) to the concrete\n * adapter service (Codex, Claude, etc). It does not own session lifecycle\n * or routing rules; `ProviderService` uses this registry together with\n * `ProviderSessionDirectory`.\n *\n * During the driver/instance migration this tag exposes both flavours:\n *\n *   - `getByInstance` / `listInstances` — new per-instance routing. Callers\n *     that already know an `instanceId` (threads, sessions, events)\n *     should prefer these.\n *     (`defaultInstanceIdForDriver(kind) === kind`), matching the pre-Slice-D\n *     behaviour. New code should not grow additional callers of the kind-keyed\n *     methods; they exist so the settings UI, WS refresh RPC, and a handful\n *     of legacy persisted rows can still be routed during the rollout.\n *\n * @module ProviderAdapterRegistry\n */\nimport type { ProviderDriverKind, ProviderInstanceId } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as PubSub from \"effect/PubSub\";\nimport type * as Scope from \"effect/Scope\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { ProviderAdapterError, ProviderUnsupportedError } from \"../Errors.ts\";\nimport type { ProviderAdapterShape } from \"./ProviderAdapter.ts\";\nimport type { ProviderContinuationIdentity } from \"../ProviderDriver.ts\";\n\nexport interface ProviderInstanceRoutingInfo {\n  readonly instanceId: ProviderInstanceId;\n  readonly driverKind: ProviderDriverKind;\n  readonly displayName: string | undefined;\n  readonly accentColor?: string | undefined;\n  readonly enabled: boolean;\n  readonly continuationIdentity: ProviderContinuationIdentity;\n}\n\n/**\n * ProviderAdapterRegistryShape - Service API for adapter lookup.\n */\nexport interface ProviderAdapterRegistryShape {\n  /**\n   * Resolve the adapter for a specific instance id. Returns\n   * `ProviderUnsupportedError` if no such instance is currently registered\n   * (which covers \"never configured\" *and* \"configured but the driver is\n   * unavailable in this build\" — both surface the same failure to callers\n   * that expect a working adapter).\n   */\n  readonly getByInstance: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderAdapterShape<ProviderAdapterError>, ProviderUnsupportedError>;\n\n  readonly getInstanceInfo: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderUnsupportedError>;\n\n  /**\n   * List all live instance ids. Excludes unavailable/shadow instances —\n   * callers of this method want something they can pass to `getByInstance`.\n   */\n  readonly listInstances: () => Effect.Effect<ReadonlyArray<ProviderInstanceId>>;\n\n  /**\n   * Legacy: list provider kinds whose default instance is currently\n   * registered.\n   *\n   * @deprecated Prefer `listInstances`. Retained for migration-era call\n   * sites that iterate providers to build UI/metrics.\n   */\n  readonly listProviders: () => Effect.Effect<ReadonlyArray<ProviderDriverKind>>;\n\n  /**\n   * Change notification stream mirroring `ProviderInstanceRegistry.streamChanges`.\n   * Emits one `void` tick whenever the set of live instances changes\n   * (instance added, removed, or rebuilt after a settings edit). Consumers\n   * that fan out `adapter.streamEvents` per instance — e.g. `ProviderService`'s\n   * runtime event bus — re-pull `listInstances` on each tick and fork new\n   * subscriptions for instances they haven't seen yet.\n   */\n  readonly streamChanges: Stream.Stream<void>;\n\n  /**\n   * Acquire a change subscription synchronously in the caller's current fiber.\n   * Consumers that must avoid missing a publish between initial reconciliation\n   * and watcher startup should use this, then fork `Stream.fromSubscription`.\n   */\n  readonly subscribeChanges: Effect.Effect<PubSub.Subscription<void>, never, Scope.Scope>;\n}\n\n/**\n * ProviderAdapterRegistry - Service tag for provider adapter lookup.\n */\nexport class ProviderAdapterRegistry extends Context.Service<\n  ProviderAdapterRegistry,\n  ProviderAdapterRegistryShape\n>()(\"t3/provider/Services/ProviderAdapterRegistry\") {}\n","/**\n * ProviderAdapterRegistryLive — facade over `ProviderInstanceRegistry`.\n *\n * `ProviderAdapterRegistry` historically mapped one `ProviderDriverKind` to one\n * adapter via the four `<X>AdapterLive` singleton Layers. The per-instance\n * refactor moved adapter construction inside each `ProviderDriver.create()`:\n * adapters are now bundled on the `ProviderInstance` that the\n * `ProviderInstanceRegistry` owns.\n *\n * This facade fulfills the `ProviderAdapterRegistryShape` contract by doing\n * dynamic look-ups against `ProviderInstanceRegistry` on every call. That\n * means settings-driven hot-reload shows up here automatically — adding a\n * new instance via settings makes `getByInstance` resolve immediately\n * without rebuilding the facade.\n *\n * @module ProviderAdapterRegistryLive\n */\nimport {\n  defaultInstanceIdForDriver,\n  ProviderInstanceId,\n  type ProviderDriverKind,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { ProviderUnsupportedError } from \"../Errors.ts\";\nimport { ProviderInstanceRegistry } from \"../Services/ProviderInstanceRegistry.ts\";\nimport {\n  ProviderAdapterRegistry,\n  type ProviderAdapterRegistryShape,\n} from \"../Services/ProviderAdapterRegistry.ts\";\n\nconst makeProviderAdapterRegistry = Effect.fn(\"makeProviderAdapterRegistry\")(function* () {\n  const registry = yield* ProviderInstanceRegistry;\n\n  const getByInstance: ProviderAdapterRegistryShape[\"getByInstance\"] = (instanceId) =>\n    registry.getInstance(instanceId).pipe(\n      Effect.flatMap((instance) =>\n        instance === undefined\n          ? Effect.fail(\n              new ProviderUnsupportedError({\n                provider: instanceId,\n              }),\n            )\n          : Effect.succeed(instance.adapter),\n      ),\n    );\n\n  const getInstanceInfo: ProviderAdapterRegistryShape[\"getInstanceInfo\"] = (instanceId) =>\n    registry.getInstance(instanceId).pipe(\n      Effect.flatMap((instance) =>\n        instance === undefined\n          ? Effect.fail(\n              new ProviderUnsupportedError({\n                provider: instanceId,\n              }),\n            )\n          : Effect.succeed({\n              instanceId: instance.instanceId,\n              driverKind: instance.driverKind,\n              displayName: instance.displayName,\n              accentColor: instance.accentColor,\n              enabled: instance.enabled,\n              continuationIdentity: instance.continuationIdentity,\n            }),\n      ),\n    );\n\n  const listInstances: ProviderAdapterRegistryShape[\"listInstances\"] = () =>\n    registry.listInstances.pipe(\n      Effect.map((instances) => instances.map((instance) => instance.instanceId)),\n    );\n\n  const listProviders: ProviderAdapterRegistryShape[\"listProviders\"] = () =>\n    registry.listInstances.pipe(\n      Effect.map((instances) => {\n        const kinds = new Set<ProviderDriverKind>();\n        for (const instance of instances) {\n          const defaultId = defaultInstanceIdForDriver(instance.driverKind);\n          if (instance.instanceId === defaultId) {\n            // Only the default-instance rows show up through the legacy\n            // shim — custom instances like `codex_personal` have no\n            // `ProviderDriverKind` equivalent.\n            kinds.add(instance.driverKind);\n          }\n        }\n        return Array.from(kinds);\n      }),\n    );\n\n  return {\n    getByInstance,\n    getInstanceInfo,\n    listInstances,\n    listProviders,\n    // Proxy directly — the facade has no state of its own; the instance\n    // registry already coalesces adds/removes/rebuilds into one emission.\n    streamChanges: registry.streamChanges,\n    subscribeChanges: registry.subscribeChanges,\n  } satisfies ProviderAdapterRegistryShape;\n});\n\nexport const ProviderAdapterRegistryLive = Layer.effect(\n  ProviderAdapterRegistry,\n  makeProviderAdapterRegistry(),\n);\n\n// Exposed for tests that want to build a facade over a pre-assembled\n// `ProviderInstanceRegistry` without pulling in the whole boot graph.\nexport { makeProviderAdapterRegistry };\n\n// Re-export for consumers that need the accessor shape. The service tag\n// itself lives in `Services/ProviderAdapterRegistry.ts`.\nexport { ProviderAdapterRegistry } from \"../Services/ProviderAdapterRegistry.ts\";\n// Re-export for consumers (including tests) that construct a\n// `ProviderInstanceId` before calling `getByInstance`.\nexport { ProviderInstanceId };\n","// @effect-diagnostics nodeBuiltinImport:off\n/**\n * Best-effort provider event logging with one shared writer per thread.\n *\n * Native and canonical views share batching, rotation, and retention state so\n * they cannot race while appending to the same thread-scoped file.\n */\nimport * as NodeFS from \"node:fs\";\nimport * as NodePath from \"node:path\";\n\nimport type { ThreadId } from \"@t3tools/contracts\";\nimport { RotatingFileSink } from \"@t3tools/shared/logging\";\nimport { errorTag } from \"@t3tools/shared/observability\";\nimport * as Clock from \"effect/Clock\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\n\nimport { toSafeThreadAttachmentSegment } from \"../../attachmentStore.ts\";\nimport type { ResourceAttribution } from \"../../resourceTelemetry/ResourceAttribution.ts\";\n\nconst MEBIBYTE = 1024 * 1024;\nconst DAY_MS = 24 * 60 * 60 * 1_000;\nconst DEFAULT_MAX_BYTES = 10 * MEBIBYTE;\nconst DEFAULT_MAX_FILES = 10;\nconst DEFAULT_BATCH_WINDOW_MS = 1_000;\nconst DEFAULT_MAX_TOTAL_BYTES = 512 * MEBIBYTE;\nconst DEFAULT_MAX_AGE_MS = 14 * DAY_MS;\nconst DEFAULT_RETENTION_CHECK_INTERVAL_MS = 5 * 60 * 1_000;\nconst DEFAULT_MAX_BUFFERED_BYTES = MEBIBYTE;\nconst DEFAULT_MAX_BUFFERED_RECORDS = 512;\nconst GLOBAL_THREAD_SEGMENT = \"_global\";\nconst LOG_SCOPE = \"provider-observability\";\nconst encodeUnknownJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst transientCanonicalEventTypes = new Set([\n  \"content.delta\",\n  \"hook.progress\",\n  \"item.updated\",\n  \"task.progress\",\n  \"thread.realtime.audio.delta\",\n  \"tool.progress\",\n  \"turn.proposed.delta\",\n]);\n\nexport type EventNdjsonStream = \"native\" | \"canonical\" | \"orchestration\";\n\nexport interface EventNdjsonLogger {\n  readonly filePath: string;\n  readonly write: (event: unknown, threadId: ThreadId | null) => Effect.Effect<void>;\n  readonly close: () => Effect.Effect<void>;\n}\n\nexport interface EventNdjsonLogStore {\n  readonly filePath: string;\n  readonly logger: (stream: EventNdjsonStream) => EventNdjsonLogger;\n  readonly close: () => Effect.Effect<void>;\n}\n\nexport interface EventNdjsonLogStoreOptions {\n  readonly maxBytes?: number;\n  readonly maxFiles?: number;\n  readonly batchWindowMs?: number;\n  readonly maxTotalBytes?: number;\n  readonly maxAgeMs?: number;\n  readonly retentionCheckIntervalMs?: number;\n  readonly maxBufferedBytes?: number;\n  readonly maxBufferedRecords?: number;\n  readonly attribution?: ResourceAttribution[\"Service\"];\n}\n\nexport interface EventNdjsonLoggerOptions extends EventNdjsonLogStoreOptions {\n  readonly stream: EventNdjsonStream;\n}\n\nexport class EventNdjsonLogConfigurationError extends Schema.TaggedErrorClass<EventNdjsonLogConfigurationError>()(\n  \"EventNdjsonLogConfigurationError\",\n  {\n    filePath: Schema.String,\n    option: Schema.String,\n    value: Schema.Number,\n    minimum: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Provider event log option '${this.option}' must be an integer >= ${this.minimum}; received ${this.value} for '${this.filePath}'`;\n  }\n}\n\nexport class EventNdjsonLogDirectoryError extends Schema.TaggedErrorClass<EventNdjsonLogDirectoryError>()(\n  \"EventNdjsonLogDirectoryError\",\n  {\n    directory: Schema.String,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to create provider event log directory '${this.directory}'`;\n  }\n}\n\nexport type EventNdjsonLogStoreError =\n  | EventNdjsonLogConfigurationError\n  | EventNdjsonLogDirectoryError;\n\ninterface ResolvedOptions {\n  readonly maxBytes: number;\n  readonly maxFiles: number;\n  readonly batchWindowMs: number;\n  readonly maxTotalBytes: number;\n  readonly maxAgeMs: number;\n  readonly retentionCheckIntervalMs: number;\n  readonly maxBufferedBytes: number;\n  readonly maxBufferedRecords: number;\n  readonly attribution: ResourceAttribution[\"Service\"] | undefined;\n}\n\nexport interface PendingRecord {\n  readonly stream: EventNdjsonStream;\n  readonly threadSegment: string;\n  readonly line: string;\n  readonly bytes: number;\n}\n\ninterface StoreState {\n  readonly pending: ReadonlyArray<PendingRecord>;\n  readonly pendingBytes: number;\n  readonly sinks: ReadonlyMap<string, RotatingFileSink>;\n  readonly flushScheduled: boolean;\n  readonly closed: boolean;\n  readonly lastRetentionAt: number;\n}\n\ninterface AttributionSummary {\n  readonly stream: EventNdjsonStream;\n  readonly count: number;\n  readonly logicalWriteBytes: number;\n}\n\ninterface FileOperationFailure {\n  readonly filePath: string;\n  readonly cause: unknown;\n}\n\ninterface RetentionResult {\n  readonly failures: ReadonlyArray<FileOperationFailure>;\n}\n\ninterface DrainResult {\n  readonly attributions: ReadonlyArray<AttributionSummary>;\n  readonly failures: ReadonlyArray<FileOperationFailure>;\n}\n\nfunction logWarning(message: string, context: Record<string, unknown>): Effect.Effect<void> {\n  return Effect.logWarning(message, context).pipe(Effect.annotateLogs({ scope: LOG_SCOPE }));\n}\n\nfunction resolveThreadSegment(raw: string | null | undefined): string {\n  const normalized = typeof raw === \"string\" ? toSafeThreadAttachmentSegment(raw) : null;\n  return normalized ?? GLOBAL_THREAD_SEGMENT;\n}\n\nfunction resolveStreamLabel(stream: EventNdjsonStream): string {\n  return stream === \"native\" ? \"NTIVE\" : stream === \"orchestration\" ? \"ORCH\" : \"CANON\";\n}\n\nfunction providerLogPrefix(filePath: string): string {\n  const basename = NodePath.basename(filePath);\n  const extension = NodePath.extname(basename);\n  return `${extension.length > 0 ? basename.slice(0, -extension.length) : basename}.`;\n}\n\nfunction providerLogPath(directory: string, prefix: string, threadSegment: string): string {\n  return NodePath.join(directory, `${prefix}${threadSegment}.log`);\n}\n\nfunction shouldPersist(stream: EventNdjsonStream, event: unknown): boolean {\n  if (stream !== \"canonical\" || typeof event !== \"object\" || event === null) {\n    return true;\n  }\n  try {\n    const type = Reflect.get(event, \"type\");\n    return typeof type !== \"string\" || !transientCanonicalEventTypes.has(type);\n  } catch {\n    return true;\n  }\n}\n\nexport function writeBatchedMessages(\n  sink: Pick<RotatingFileSink, \"write\">,\n  records: ReadonlyArray<PendingRecord>,\n  maxBytes: number,\n  onWritten: (records: ReadonlyArray<PendingRecord>) => void,\n): void {\n  let pendingRecords: Array<PendingRecord> = [];\n  let pendingBytes = 0;\n\n  const flush = () => {\n    if (pendingRecords.length === 0) return;\n    const writtenRecords = pendingRecords;\n    sink.write(writtenRecords.map((record) => record.line).join(\"\"));\n    onWritten(writtenRecords);\n    pendingRecords = [];\n    pendingBytes = 0;\n  };\n\n  for (const record of records) {\n    if (pendingBytes > 0 && pendingBytes + record.bytes > maxBytes) {\n      flush();\n    }\n    pendingRecords.push(record);\n    pendingBytes += record.bytes;\n    if (pendingBytes >= maxBytes) {\n      flush();\n    }\n  }\n  flush();\n}\n\nfunction isProviderLogFile(filePath: string, fileName: string, filePrefix: string): boolean {\n  if (!/\\.log(?:\\.\\d+)?$/u.test(fileName)) return false;\n  if (fileName.startsWith(filePrefix)) return true;\n\n  const descriptor = NodeFS.openSync(filePath, \"r\");\n  try {\n    const header = Buffer.alloc(256);\n    const bytesRead = NodeFS.readSync(descriptor, header, 0, header.byteLength, 0);\n    return /^\\[[^\\]\\r\\n]+\\] (?:NTIVE|CANON|ORCH): /u.test(header.toString(\"utf8\", 0, bytesRead));\n  } finally {\n    NodeFS.closeSync(descriptor);\n  }\n}\n\nfunction enforceRetention(input: {\n  readonly directory: string;\n  readonly maxTotalBytes: number;\n  readonly maxAgeMs: number;\n  readonly activeFilePaths: ReadonlySet<string>;\n  readonly filePrefix: string;\n  readonly now: number;\n}): RetentionResult {\n  const failures: Array<FileOperationFailure> = [];\n  const files: Array<{ filePath: string; mtimeMs: number; size: number }> = [];\n\n  let entries: ReadonlyArray<NodeFS.Dirent>;\n  try {\n    entries = NodeFS.readdirSync(input.directory, { withFileTypes: true });\n  } catch (cause) {\n    return { failures: [{ filePath: input.directory, cause }] };\n  }\n\n  for (const entry of entries) {\n    if (!entry.isFile()) continue;\n    const filePath = NodePath.join(input.directory, entry.name);\n    try {\n      if (!isProviderLogFile(filePath, entry.name, input.filePrefix)) continue;\n      const stat = NodeFS.statSync(filePath);\n      files.push({ filePath, mtimeMs: stat.mtimeMs, size: stat.size });\n    } catch (cause) {\n      failures.push({ filePath, cause });\n    }\n  }\n\n  let totalBytes = files.reduce((total, file) => total + file.size, 0);\n  const remove = (file: (typeof files)[number]) => {\n    if (input.activeFilePaths.has(file.filePath)) return false;\n    try {\n      NodeFS.rmSync(file.filePath, { force: true });\n      totalBytes -= file.size;\n      return true;\n    } catch (cause) {\n      failures.push({ filePath: file.filePath, cause });\n      return false;\n    }\n  };\n\n  const retained = files.filter((file) => {\n    if (input.now - file.mtimeMs <= input.maxAgeMs) return true;\n    return !remove(file);\n  });\n\n  for (const file of retained.toSorted(\n    (left, right) => left.mtimeMs - right.mtimeMs || left.filePath.localeCompare(right.filePath),\n  )) {\n    if (totalBytes <= input.maxTotalBytes) break;\n    remove(file);\n  }\n\n  return { failures };\n}\n\nfunction validateOption(input: {\n  readonly filePath: string;\n  readonly option: string;\n  readonly value: number;\n  readonly minimum: number;\n}): EventNdjsonLogConfigurationError | undefined {\n  if (Number.isInteger(input.value) && input.value >= input.minimum) return undefined;\n  return new EventNdjsonLogConfigurationError(input);\n}\n\nfunction resolveOptions(\n  filePath: string,\n  options: EventNdjsonLogStoreOptions,\n): Effect.Effect<ResolvedOptions, EventNdjsonLogConfigurationError> {\n  const resolved = {\n    maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,\n    maxFiles: options.maxFiles ?? DEFAULT_MAX_FILES,\n    batchWindowMs: options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS,\n    maxTotalBytes: options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,\n    maxAgeMs: options.maxAgeMs ?? DEFAULT_MAX_AGE_MS,\n    retentionCheckIntervalMs:\n      options.retentionCheckIntervalMs ?? DEFAULT_RETENTION_CHECK_INTERVAL_MS,\n    maxBufferedBytes: options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES,\n    maxBufferedRecords: options.maxBufferedRecords ?? DEFAULT_MAX_BUFFERED_RECORDS,\n    attribution: options.attribution,\n  } satisfies ResolvedOptions;\n\n  const validations = [\n    [\"maxBytes\", resolved.maxBytes, 1],\n    [\"maxFiles\", resolved.maxFiles, 1],\n    [\"batchWindowMs\", resolved.batchWindowMs, 0],\n    [\"maxTotalBytes\", resolved.maxTotalBytes, 1],\n    [\"maxAgeMs\", resolved.maxAgeMs, 1],\n    [\"retentionCheckIntervalMs\", resolved.retentionCheckIntervalMs, 1],\n    [\"maxBufferedBytes\", resolved.maxBufferedBytes, 1],\n    [\"maxBufferedRecords\", resolved.maxBufferedRecords, 1],\n  ] as const;\n\n  for (const [option, value, minimum] of validations) {\n    const error = validateOption({ filePath, option, value, minimum });\n    if (error) return Effect.fail(error);\n  }\n  return Effect.succeed(resolved);\n}\n\nfunction drainPending(input: {\n  readonly directory: string;\n  readonly options: ResolvedOptions;\n  readonly state: StoreState;\n  readonly filePrefix: string;\n  readonly now: number;\n  readonly timerFired: boolean;\n  readonly close: boolean;\n}): readonly [DrainResult, StoreState] {\n  if (input.state.closed) {\n    return [{ attributions: [], failures: [] }, input.state];\n  }\n\n  const sinks = new Map(input.state.sinks);\n  const failures: Array<FileOperationFailure> = [];\n  const attributionByStream = new Map<\n    EventNdjsonStream,\n    { count: number; logicalWriteBytes: number }\n  >();\n  const recordsBySegment = new Map<string, Array<PendingRecord>>();\n\n  for (const record of input.state.pending) {\n    const records = recordsBySegment.get(record.threadSegment) ?? [];\n    records.push(record);\n    recordsBySegment.set(record.threadSegment, records);\n  }\n\n  for (const [threadSegment, records] of recordsBySegment) {\n    const filePath = providerLogPath(input.directory, input.filePrefix, threadSegment);\n    let sink = sinks.get(threadSegment);\n    if (!sink) {\n      try {\n        sink = new RotatingFileSink({\n          filePath,\n          maxBytes: input.options.maxBytes,\n          maxFiles: input.options.maxFiles,\n          throwOnError: true,\n        });\n        sinks.set(threadSegment, sink);\n      } catch (cause) {\n        failures.push({ filePath, cause });\n        continue;\n      }\n    }\n\n    try {\n      writeBatchedMessages(sink, records, input.options.maxBytes, (writtenRecords) => {\n        for (const record of writtenRecords) {\n          const current = attributionByStream.get(record.stream) ?? {\n            count: 0,\n            logicalWriteBytes: 0,\n          };\n          attributionByStream.set(record.stream, {\n            count: current.count + 1,\n            logicalWriteBytes: current.logicalWriteBytes + record.bytes,\n          });\n        }\n      });\n    } catch (cause) {\n      sinks.delete(threadSegment);\n      failures.push({ filePath, cause });\n    }\n  }\n\n  const retentionDue =\n    input.now - input.state.lastRetentionAt >= input.options.retentionCheckIntervalMs;\n  const retention = retentionDue\n    ? enforceRetention({\n        directory: input.directory,\n        maxTotalBytes: input.options.maxTotalBytes,\n        maxAgeMs: input.options.maxAgeMs,\n        activeFilePaths: new Set(\n          Array.from(sinks.keys(), (threadSegment) =>\n            providerLogPath(input.directory, input.filePrefix, threadSegment),\n          ),\n        ),\n        filePrefix: input.filePrefix,\n        now: input.now,\n      })\n    : { failures: [] };\n\n  return [\n    {\n      attributions: Array.from(attributionByStream, ([stream, value]) => ({\n        stream,\n        ...value,\n      })),\n      failures: [...failures, ...retention.failures],\n    },\n    {\n      pending: [],\n      pendingBytes: 0,\n      sinks,\n      flushScheduled: input.timerFired ? false : input.state.flushScheduled,\n      closed: input.close,\n      lastRetentionAt: retentionDue ? input.now : input.state.lastRetentionAt,\n    },\n  ];\n}\n\nconst serializeEvent = Effect.fnUntraced(function* (event: unknown) {\n  return yield* encodeUnknownJsonString(event).pipe(\n    Effect.catch((error) =>\n      logWarning(\"failed to serialize provider event log record\", {\n        errorTag: errorTag(error),\n      }).pipe(Effect.as(undefined)),\n    ),\n  );\n});\n\nexport const makeEventNdjsonLogStore = Effect.fnUntraced(function* (\n  filePath: string,\n  options: EventNdjsonLogStoreOptions = {},\n): Effect.fn.Return<EventNdjsonLogStore, EventNdjsonLogStoreError> {\n  const resolved = yield* resolveOptions(filePath, options);\n  const directory = NodePath.dirname(filePath);\n  const filePrefix = providerLogPrefix(filePath);\n\n  yield* Effect.try({\n    try: () => NodeFS.mkdirSync(directory, { recursive: true }),\n    catch: (cause) => new EventNdjsonLogDirectoryError({ directory, cause }),\n  });\n\n  const initializedAt = yield* Clock.currentTimeMillis;\n  const initialRetention = yield* Effect.sync(() =>\n    enforceRetention({\n      directory,\n      maxTotalBytes: resolved.maxTotalBytes,\n      maxAgeMs: resolved.maxAgeMs,\n      activeFilePaths: new Set(),\n      filePrefix,\n      now: initializedAt,\n    }),\n  );\n  for (const failure of initialRetention.failures) {\n    yield* logWarning(\"provider event log retention failed\", {\n      filePath: failure.filePath,\n      errorTag: errorTag(failure.cause),\n    });\n  }\n\n  const stateRef = yield* SynchronizedRef.make<StoreState>({\n    pending: [],\n    pendingBytes: 0,\n    sinks: new Map(),\n    flushScheduled: false,\n    closed: false,\n    lastRetentionAt: initializedAt,\n  });\n  const timerScope = yield* Scope.make();\n\n  const flush = Effect.fnUntraced(function* (timerFired: boolean, close: boolean) {\n    const startedAt = yield* Clock.currentTimeMillis;\n    const result = yield* SynchronizedRef.modifyEffect(stateRef, (state) =>\n      Effect.sync(() =>\n        drainPending({\n          directory,\n          options: resolved,\n          state,\n          filePrefix,\n          now: startedAt,\n          timerFired,\n          close,\n        }),\n      ),\n    );\n\n    for (const failure of result.failures) {\n      yield* logWarning(\"provider event log write or retention failed\", {\n        filePath: failure.filePath,\n        errorTag: errorTag(failure.cause),\n      });\n    }\n\n    if (resolved.attribution && result.attributions.length > 0) {\n      const completedAt = yield* Clock.currentTimeMillis;\n      const durationMs = Math.max(0, completedAt - startedAt);\n      const totalBytes = result.attributions.reduce(\n        (total, entry) => total + entry.logicalWriteBytes,\n        0,\n      );\n      yield* Effect.forEach(\n        result.attributions,\n        (entry) =>\n          resolved.attribution?.record({\n            component: \"provider-event-log\",\n            operation: `${entry.stream}.append`,\n            logicalWriteBytes: entry.logicalWriteBytes,\n            count: entry.count,\n            durationMs:\n              totalBytes === 0\n                ? 0\n                : Math.round(durationMs * (entry.logicalWriteBytes / totalBytes)),\n          }) ?? Effect.void,\n        { discard: true },\n      );\n    }\n  });\n\n  const scheduleFlush = Effect.fnUntraced(function* () {\n    yield* Effect.forkIn(\n      Effect.sleep(resolved.batchWindowMs).pipe(Effect.andThen(flush(true, false))),\n      timerScope,\n      { startImmediately: true },\n    );\n  });\n\n  const close = Effect.fnUntraced(function* () {\n    yield* flush(false, true);\n    yield* Scope.close(timerScope, Exit.void);\n  });\n\n  const loggerViews = new Map<EventNdjsonStream, EventNdjsonLogger>();\n  const logger = (stream: EventNdjsonStream): EventNdjsonLogger => {\n    const existing = loggerViews.get(stream);\n    if (existing) return existing;\n\n    const write = Effect.fnUntraced(function* (event: unknown, threadId: ThreadId | null) {\n      if (!shouldPersist(stream, event)) return;\n      const payload = yield* serializeEvent(event);\n      if (payload === undefined) return;\n\n      const observedAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));\n      const line = `[${observedAt}] ${resolveStreamLabel(stream)}: ${payload}\\n`;\n      const bytes = Buffer.byteLength(line);\n      const action = yield* SynchronizedRef.modifyEffect(stateRef, (state) => {\n        if (state.closed) {\n          return Effect.succeed([{ flush: false }, state] as const);\n        }\n        const pending = [\n          ...state.pending,\n          { stream, threadSegment: resolveThreadSegment(threadId), line, bytes },\n        ];\n        const pendingBytes = state.pendingBytes + bytes;\n        const flush =\n          resolved.batchWindowMs === 0 ||\n          pending.length >= resolved.maxBufferedRecords ||\n          pendingBytes >= resolved.maxBufferedBytes;\n        const schedule = !flush && !state.flushScheduled;\n        const nextState = {\n          ...state,\n          pending,\n          pendingBytes,\n          flushScheduled: state.flushScheduled || schedule,\n        };\n        return (schedule ? scheduleFlush() : Effect.void).pipe(\n          Effect.as([{ flush }, nextState] as const),\n        );\n      }).pipe(Effect.uninterruptible);\n\n      if (action.flush) {\n        yield* flush(false, false);\n      }\n    });\n\n    const view = { filePath, write, close: () => Effect.void } satisfies EventNdjsonLogger;\n    loggerViews.set(stream, view);\n    return view;\n  };\n\n  return { filePath, logger, close } satisfies EventNdjsonLogStore;\n});\n\nexport const makeEventNdjsonLogger = Effect.fnUntraced(function* (\n  filePath: string,\n  options: EventNdjsonLoggerOptions,\n): Effect.fn.Return<EventNdjsonLogger | undefined> {\n  const store = yield* makeEventNdjsonLogStore(filePath, options).pipe(\n    Effect.catch((error) =>\n      logWarning(error.message, { error }).pipe(\n        Effect.as<EventNdjsonLogStore | undefined>(undefined),\n      ),\n    ),\n  );\n  if (!store) return undefined;\n  return { ...store.logger(options.stream), close: store.close };\n});\n","/**\n * ProviderEventLoggers — single observability service that owns the shared\n * provider event log store and exposes its two runtime views:\n *\n *   - `native`    — provider-protocol events as the SDK emits them, written\n *                   from inside each `<X>Adapter` factory.\n *   - `canonical` — runtime events after `ProviderService` has normalized\n *                   them onto `ProviderRuntimeEvent`.\n *\n * Why a service tag and not constructor options?\n *\n *   - Adapters are now constructed *inside* drivers (`<X>Driver.create()`),\n *     not at the boot Layer. There is no longer a single `make<X>AdapterLive(options)`\n *     call site where we can hand an `EventNdjsonLogger` in by hand.\n *   - Multiple driver instances per kind (`codex_personal`, `codex_work`)\n *     must share one underlying log store — opening N writers against the\n *     same rotating file would race the rotation logic. Owning the loggers on\n *     a single tag keeps that invariant intact.\n *   - Tests can swap one (or both) loggers with in-memory recorders by\n *     `Layer.succeed(ProviderEventLoggers, { native, canonical })` instead of\n *     juggling per-Layer option threading.\n *\n * Both fields are optional because observability must not prevent startup.\n *\n * @module provider/Layers/ProviderEventLoggers\n */\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport { ServerConfig } from \"../../config.ts\";\nimport * as ResourceAttribution from \"../../resourceTelemetry/ResourceAttribution.ts\";\nimport * as EventNdjsonLogger from \"./EventNdjsonLogger.ts\";\n\n/**\n * Shared logger pair for native + canonical provider event streams.\n *\n * Service value is intentionally a struct of two optional loggers rather\n * than two parallel tags. Construction site is one place\n * (`layer`); consumers (drivers, `ProviderService`) read one tag and pluck the\n * field they need.\n */\nexport class ProviderEventLoggers extends Context.Service<\n  ProviderEventLoggers,\n  {\n    readonly native: EventNdjsonLogger.EventNdjsonLogger | undefined;\n    readonly canonical: EventNdjsonLogger.EventNdjsonLogger | undefined;\n  }\n>()(\"t3/provider/Layers/ProviderEventLoggers\") {}\n\n/**\n * Constant value used by tests / boot layers that want to opt out of native\n * + canonical logging entirely. Keeps the tag non-optional in the type\n * system while letting the runtime treat absence as a no-op.\n */\nexport const NoOpProviderEventLoggers: ProviderEventLoggers[\"Service\"] = {\n  native: undefined,\n  canonical: undefined,\n};\n\n/**\n * Builds both stream views over one shared store. Setup failures are logged\n * and downgraded to the no-op service so diagnostics never block startup.\n */\nexport const make = Effect.gen(function* () {\n  const { providerEventLogPath } = yield* ServerConfig;\n  const attribution = yield* ResourceAttribution.ResourceAttribution;\n  const store = yield* EventNdjsonLogger.makeEventNdjsonLogStore(providerEventLogPath, {\n    attribution,\n  }).pipe(\n    Effect.catch((error) =>\n      Effect.logWarning(error.message, { error }).pipe(\n        Effect.annotateLogs({ scope: \"provider-observability\" }),\n        Effect.as<EventNdjsonLogger.EventNdjsonLogStore | undefined>(undefined),\n      ),\n    ),\n  );\n\n  if (!store) {\n    return ProviderEventLoggers.of(NoOpProviderEventLoggers);\n  }\n\n  yield* Effect.addFinalizer(() => store.close());\n  return ProviderEventLoggers.of({\n    native: store.logger(\"native\"),\n    canonical: store.logger(\"canonical\"),\n  });\n});\n\nexport const layer = Layer.effect(ProviderEventLoggers, make);\n","/**\n * ProviderService - Service interface for provider sessions, turns, and checkpoints.\n *\n * Acts as the cross-provider facade used by transports (WebSocket/RPC). It\n * resolves provider adapters through `ProviderAdapterRegistry`, routes\n * session-scoped calls via `ProviderSessionDirectory`, and exposes one unified\n * provider event stream to callers.\n *\n * Uses Effect `Context.Service` for dependency injection and returns typed\n * domain errors for validation, session, codex, and checkpoint workflows.\n *\n * @module ProviderService\n */\nimport type {\n  ProviderInterruptTurnInput,\n  ProviderInstanceId,\n  ProviderRespondToRequestInput,\n  ProviderRespondToUserInputInput,\n  ProviderRuntimeEvent,\n  ProviderSendTurnInput,\n  ProviderSession,\n  ProviderSessionStartInput,\n  ProviderStopSessionInput,\n  ThreadId,\n  ProviderTurnStartResult,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\n\nimport type { ProviderServiceError } from \"../Errors.ts\";\nimport type { ProviderAdapterCapabilities } from \"./ProviderAdapter.ts\";\nimport type { ProviderInstanceRoutingInfo } from \"./ProviderAdapterRegistry.ts\";\n\n/**\n * ProviderServiceShape - Service API for provider session and turn orchestration.\n */\nexport interface ProviderServiceShape {\n  /**\n   * Start a provider session.\n   */\n  readonly startSession: (\n    threadId: ThreadId,\n    input: ProviderSessionStartInput,\n  ) => Effect.Effect<ProviderSession, ProviderServiceError>;\n\n  /**\n   * Send a provider turn.\n   */\n  readonly sendTurn: (\n    input: ProviderSendTurnInput,\n  ) => Effect.Effect<ProviderTurnStartResult, ProviderServiceError>;\n\n  /**\n   * Interrupt a running provider turn.\n   */\n  readonly interruptTurn: (\n    input: ProviderInterruptTurnInput,\n  ) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * Respond to a provider approval request.\n   */\n  readonly respondToRequest: (\n    input: ProviderRespondToRequestInput,\n  ) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * Respond to a provider structured user-input request.\n   */\n  readonly respondToUserInput: (\n    input: ProviderRespondToUserInputInput,\n  ) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * Stop a provider session.\n   */\n  readonly stopSession: (\n    input: ProviderStopSessionInput,\n  ) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * List active provider sessions.\n   *\n   * Aggregates runtime session lists from all registered adapters.\n   */\n  readonly listSessions: () => Effect.Effect<ReadonlyArray<ProviderSession>>;\n\n  /**\n   * Read capabilities for the adapter bound to a configured provider instance.\n   */\n  readonly getCapabilities: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderAdapterCapabilities, ProviderServiceError>;\n\n  readonly getInstanceInfo: (\n    instanceId: ProviderInstanceId,\n  ) => Effect.Effect<ProviderInstanceRoutingInfo, ProviderServiceError>;\n\n  /**\n   * Roll back provider conversation state by a number of turns.\n   */\n  readonly rollbackConversation: (input: {\n    readonly threadId: ThreadId;\n    readonly numTurns: number;\n  }) => Effect.Effect<void, ProviderServiceError>;\n\n  /**\n   * Canonical provider runtime event stream.\n   *\n   * Fan-out is owned by ProviderService (not by a standalone event-bus service).\n   */\n  readonly streamEvents: Stream.Stream<ProviderRuntimeEvent>;\n}\n\n/**\n * ProviderService - Service tag for provider orchestration.\n */\nexport class ProviderService extends Context.Service<ProviderService, ProviderServiceShape>()(\n  \"t3/provider/Services/ProviderService\",\n) {}\n","import type { EnvironmentId, ProviderInstanceId, ThreadId } from \"@t3tools/contracts\";\n\nexport interface McpProviderSessionConfig {\n  readonly environmentId: EnvironmentId;\n  readonly threadId: ThreadId;\n  readonly providerSessionId: string;\n  readonly providerInstanceId: ProviderInstanceId;\n  readonly endpoint: string;\n  readonly authorizationHeader: string;\n}\n\nconst sessionsByThread = new Map<ThreadId, McpProviderSessionConfig>();\n\nexport function setMcpProviderSession(config: McpProviderSessionConfig): void {\n  sessionsByThread.set(config.threadId, config);\n}\n\nexport function readMcpProviderSession(threadId: ThreadId): McpProviderSessionConfig | undefined {\n  return sessionsByThread.get(threadId);\n}\n\nexport function clearMcpProviderSession(threadId: ThreadId): void {\n  sessionsByThread.delete(threadId);\n}\n\nexport function clearAllMcpProviderSessions(): void {\n  sessionsByThread.clear();\n}\n","import { ProviderInstanceId, ThreadId } from \"@t3tools/contracts\";\nimport * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\nimport { HttpServer } from \"effect/unstable/http\";\n\nimport * as ServerEnvironment from \"../environment/ServerEnvironment.ts\";\nimport * as McpInvocationContext from \"./McpInvocationContext.ts\";\nimport * as McpProviderSession from \"./McpProviderSession.ts\";\n\nexport interface McpCredentialRequest {\n  readonly threadId: ThreadId;\n  readonly providerInstanceId: ProviderInstanceId;\n}\n\nexport interface McpIssuedCredential {\n  readonly config: McpProviderSession.McpProviderSessionConfig;\n}\n\nexport interface McpSessionRegistryShape {\n  readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;\n  readonly resolve: (\n    rawToken: string,\n  ) => Effect.Effect<McpInvocationContext.McpInvocationScope | undefined>;\n  /**\n   * Records a sign of life for every credential bound to `threadId`. Provider\n   * turns call this so that a session which is plainly alive keeps its\n   * credential even when it goes a long time without touching an MCP tool.\n   */\n  readonly touch: (threadId: ThreadId) => Effect.Effect<void>;\n  readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;\n  readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;\n  readonly revokeAll: Effect.Effect<void>;\n}\n\nexport class McpSessionRegistry extends Context.Service<\n  McpSessionRegistry,\n  McpSessionRegistryShape\n>()(\"t3/mcp/McpSessionRegistry\") {}\n\ninterface CredentialRecord {\n  readonly tokenHash: string;\n  readonly scope: McpInvocationContext.McpInvocationScope;\n  readonly lastAliveAt: number;\n}\n\ninterface RegistryState {\n  readonly records: ReadonlyMap<string, CredentialRecord>;\n}\n\nexport interface McpSessionRegistryOptions {\n  readonly livenessWindowMs?: number;\n  readonly now?: () => number;\n}\n\n/**\n * How long a credential outlives the last sign of life from its provider\n * session.\n *\n * Liveness is refreshed both by MCP traffic and by `touch` on every provider\n * turn, so a session that is still doing work never expires no matter how long\n * it goes between browser tool calls. This window therefore only bounds\n * credentials whose session died without a clean stop — the normal paths\n * (`stopSession`, `stopAll`) revoke eagerly and do not wait for it.\n *\n * The bound matters because `/mcp` is mounted outside the environment auth\n * stack and is reachable on whatever host the server binds to, so this token is\n * the only thing guarding the preview toolkit on a remote-reachable server.\n */\nconst DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000;\n\nconst bytesToHex = (bytes: Uint8Array): string =>\n  Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n\nconst tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString(\"base64url\");\n\nconst getHttpMcpEndpointHost = (hostname: string): string => {\n  const normalized = hostname.toLowerCase();\n  const endpointHostname =\n    normalized === \"0.0.0.0\" || normalized === \"::\" || normalized === \"[::]\"\n      ? \"127.0.0.1\"\n      : hostname;\n  return endpointHostname.includes(\":\") && !endpointHostname.startsWith(\"[\")\n    ? `[${endpointHostname}]`\n    : endpointHostname;\n};\n\nconst makeWithOptions = Effect.fn(\"McpSessionRegistry.make\")(function* (\n  options: McpSessionRegistryOptions = {},\n) {\n  const crypto = yield* Crypto.Crypto;\n  const environment = yield* ServerEnvironment.ServerEnvironment;\n  const environmentId = yield* environment.getEnvironmentId;\n  const httpServer = yield* HttpServer.HttpServer;\n  const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });\n  const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;\n  const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;\n  const endpoint =\n    httpServer.address._tag === \"TcpAddress\"\n      ? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`\n      : \"http://127.0.0.1/mcp\";\n\n  const hashToken = (token: string) =>\n    crypto\n      .digest(\"SHA-256\", new TextEncoder().encode(token))\n      .pipe(Effect.map(bytesToHex), Effect.orDie);\n\n  const pruneDead = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {\n    const next = new Map(\n      Array.from(records).filter(\n        ([, record]) => timestamp - record.lastAliveAt <= livenessWindowMs,\n      ),\n    );\n    return next.size === records.size ? records : next;\n  };\n\n  const issue: McpSessionRegistryShape[\"issue\"] = Effect.fn(\"McpSessionRegistry.issue\")(\n    function* (request) {\n      const issuedAt = yield* currentTimeMillis;\n      const providerSessionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);\n      const rawToken = yield* crypto.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);\n      const tokenHash = yield* hashToken(rawToken);\n      const scope: McpInvocationContext.McpInvocationScope = {\n        environmentId,\n        threadId: ThreadId.make(request.threadId),\n        providerSessionId,\n        providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),\n        capabilities: new Set([\"preview\"]),\n        issuedAt,\n      };\n      yield* SynchronizedRef.update(state, ({ records }) => {\n        const next = new Map(pruneDead(records, issuedAt));\n        next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt });\n        return { records: next };\n      });\n      return {\n        config: {\n          environmentId,\n          threadId: scope.threadId,\n          providerSessionId,\n          providerInstanceId: scope.providerInstanceId,\n          endpoint,\n          authorizationHeader: `Bearer ${rawToken}`,\n        },\n      };\n    },\n  );\n\n  const resolve: McpSessionRegistryShape[\"resolve\"] = Effect.fn(\"McpSessionRegistry.resolve\")(\n    function* (rawToken) {\n      if (rawToken.length === 0) return undefined;\n      const tokenHash = yield* hashToken(rawToken);\n      const timestamp = yield* currentTimeMillis;\n      return yield* SynchronizedRef.modify(state, ({ records }) => {\n        const current = pruneDead(records, timestamp);\n        const record = current.get(tokenHash);\n        if (!record) return [undefined, { records: current }] as const;\n        const next = new Map(current);\n        next.set(tokenHash, { ...record, lastAliveAt: timestamp });\n        return [record.scope, { records: next }] as const;\n      });\n    },\n  );\n\n  const touch: McpSessionRegistryShape[\"touch\"] = Effect.fn(\"McpSessionRegistry.touch\")(\n    function* (threadId) {\n      const timestamp = yield* currentTimeMillis;\n      yield* SynchronizedRef.update(state, ({ records }) => {\n        const current = pruneDead(records, timestamp);\n        const next = new Map(current);\n        for (const [tokenHash, record] of current) {\n          if (record.scope.threadId === threadId) {\n            next.set(tokenHash, { ...record, lastAliveAt: timestamp });\n          }\n        }\n        return { records: next };\n      });\n    },\n  );\n\n  const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>\n    SynchronizedRef.update(state, ({ records }) => ({\n      records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),\n    }));\n\n  return McpSessionRegistry.of({\n    issue,\n    resolve,\n    touch,\n    revokeProviderSession: Effect.fn(\"McpSessionRegistry.revokeProviderSession\")(\n      function* (providerSessionId) {\n        yield* revokeWhere((record) => record.scope.providerSessionId === providerSessionId);\n      },\n    ),\n    revokeThread: Effect.fn(\"McpSessionRegistry.revokeThread\")(function* (threadId) {\n      yield* revokeWhere((record) => record.scope.threadId === threadId);\n    }),\n    revokeAll: SynchronizedRef.set(state, { records: new Map() }),\n  });\n});\n\nlet activeMcpSessionRegistry: McpSessionRegistryShape | undefined;\n\nconst make = Effect.acquireRelease(\n  makeWithOptions().pipe(\n    Effect.tap((registry) =>\n      Effect.sync(() => {\n        activeMcpSessionRegistry = registry;\n      }),\n    ),\n  ),\n  (registry) =>\n    Effect.sync(() => {\n      if (activeMcpSessionRegistry === registry) {\n        activeMcpSessionRegistry = undefined;\n      }\n    }),\n);\n\nexport const layer = Layer.effect(McpSessionRegistry, make);\n\nexport const issueActiveMcpCredential = (\n  request: McpCredentialRequest,\n): Effect.Effect<McpIssuedCredential | undefined> =>\n  activeMcpSessionRegistry\n    ? activeMcpSessionRegistry\n        .revokeThread(request.threadId)\n        .pipe(Effect.andThen(activeMcpSessionRegistry.issue(request)))\n    : Effect.sync((): McpIssuedCredential | undefined => undefined);\n\n/**\n * Refreshes the liveness of a thread's MCP credential. Called on every provider\n * turn so an active session is never mistaken for an abandoned one.\n */\nexport const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>\n  activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void;\n\nexport const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>\n  activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void;\n\nexport const revokeAllActiveMcpCredentials = (): Effect.Effect<void> =>\n  activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeAll : Effect.void;\n\n/** Exposed for tests. */\nexport const __testing = {\n  make: makeWithOptions,\n};\n","/**\n * ProviderServiceLive - Cross-provider orchestration layer.\n *\n * Routes validated transport/API calls to provider adapters through\n * `ProviderAdapterRegistry` and `ProviderSessionDirectory`, and exposes a\n * unified provider event stream for subscribers.\n *\n * It does not implement provider protocol details (adapter concern).\n *\n * @module ProviderServiceLive\n */\nimport {\n  ModelSelection,\n  NonNegativeInt,\n  ThreadId,\n  ProviderInterruptTurnInput,\n  ProviderRespondToRequestInput,\n  ProviderRespondToUserInputInput,\n  ProviderSendTurnInput,\n  ProviderSessionStartInput,\n  ProviderStopSessionInput,\n  type ProviderInstanceId,\n  type ProviderDriverKind,\n  type ProviderRuntimeEvent,\n  type ProviderSession,\n} from \"@t3tools/contracts\";\nimport { causeErrorTag } from \"@t3tools/shared/observability\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n  increment,\n  providerMetricAttributes,\n  providerRuntimeEventsTotal,\n  providerSessionsTotal,\n  providerTurnDuration,\n  providerTurnsTotal,\n  providerTurnMetricAttributes,\n  withMetrics,\n} from \"../../observability/Metrics.ts\";\nimport { type ProviderAdapterError, ProviderValidationError } from \"../Errors.ts\";\nimport type { ProviderAdapterShape } from \"../Services/ProviderAdapter.ts\";\nimport * as ProviderAdapterRegistry from \"../Services/ProviderAdapterRegistry.ts\";\nimport * as ProviderService from \"../Services/ProviderService.ts\";\nimport * as ProviderSessionDirectory from \"../Services/ProviderSessionDirectory.ts\";\nimport { type EventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\nimport * as ProviderEventLoggers from \"./ProviderEventLoggers.ts\";\nimport * as AnalyticsService from \"../../telemetry/AnalyticsService.ts\";\nimport * as McpProviderSession from \"../../mcp/McpProviderSession.ts\";\nimport * as McpSessionRegistry from \"../../mcp/McpSessionRegistry.ts\";\nconst isModelSelection = Schema.is(ModelSelection);\n\n/**\n * Hook for tests that want to override the canonical event logger pulled\n * from `ProviderEventLoggers`. Production wiring leaves this undefined and\n * reads the logger off the tag.\n */\nexport interface ProviderServiceLiveOptions {\n  readonly canonicalEventLogger?: EventNdjsonLogger;\n}\n\ntype ProviderServiceMethod<Name extends keyof ProviderService.ProviderService[\"Service\"]> =\n  ProviderService.ProviderService[\"Service\"][Name];\n\nconst ProviderRollbackConversationInput = Schema.Struct({\n  threadId: ThreadId,\n  numTurns: NonNegativeInt,\n});\n\nfunction toValidationError(\n  operation: string,\n  issue: string,\n  cause?: unknown,\n): ProviderValidationError {\n  return new ProviderValidationError({\n    operation,\n    issue,\n    ...(cause !== undefined ? { cause } : {}),\n  });\n}\n\nconst decodeInputOrValidationError = <S extends Schema.Top>(input: {\n  readonly operation: string;\n  readonly schema: S;\n  readonly payload: unknown;\n}) => {\n  const decodeProviderRequestInput = Schema.decodeUnknownEffect(input.schema);\n  return decodeProviderRequestInput(input.payload).pipe(\n    Effect.mapError(\n      (schemaError) =>\n        new ProviderValidationError({\n          operation: input.operation,\n          issue: SchemaIssue.makeFormatterDefault()(schemaError.issue),\n          cause: schemaError,\n        }),\n    ),\n  );\n};\n\nfunction toRuntimeStatus(session: ProviderSession): \"starting\" | \"running\" | \"stopped\" | \"error\" {\n  switch (session.status) {\n    case \"connecting\":\n      return \"starting\";\n    case \"error\":\n      return \"error\";\n    case \"closed\":\n      return \"stopped\";\n    case \"ready\":\n    case \"running\":\n    default:\n      return \"running\";\n  }\n}\n\nfunction toRuntimePayloadFromSession(\n  session: ProviderSession,\n  extra?: {\n    readonly modelSelection?: unknown;\n    readonly lastRuntimeEvent?: string;\n    readonly lastRuntimeEventAt?: string;\n  },\n): Record<string, unknown> {\n  return {\n    cwd: session.cwd ?? null,\n    model: session.model ?? null,\n    activeTurnId: session.activeTurnId ?? null,\n    lastError: session.lastError ?? null,\n    ...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),\n    ...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),\n    ...(extra?.lastRuntimeEventAt !== undefined\n      ? { lastRuntimeEventAt: extra.lastRuntimeEventAt }\n      : {}),\n  };\n}\n\nfunction readPersistedModelSelection(\n  runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding[\"runtimePayload\"],\n): ModelSelection | undefined {\n  if (!runtimePayload || typeof runtimePayload !== \"object\" || Array.isArray(runtimePayload)) {\n    return undefined;\n  }\n  const raw = \"modelSelection\" in runtimePayload ? runtimePayload.modelSelection : undefined;\n  return isModelSelection(raw) ? raw : undefined;\n}\n\nfunction readPersistedCwd(\n  runtimePayload: ProviderSessionDirectory.ProviderRuntimeBinding[\"runtimePayload\"],\n): string | undefined {\n  if (!runtimePayload || typeof runtimePayload !== \"object\" || Array.isArray(runtimePayload)) {\n    return undefined;\n  }\n  const rawCwd = \"cwd\" in runtimePayload ? runtimePayload.cwd : undefined;\n  if (typeof rawCwd !== \"string\") return undefined;\n  const trimmed = rawCwd.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\nconst dieOnMissingBindingInstanceId = (\n  operation: string,\n  payload: {\n    readonly providerInstanceId?: ProviderInstanceId | undefined;\n    readonly provider?: ProviderDriverKind | undefined;\n  },\n): ProviderInstanceId => {\n  if (payload.providerInstanceId !== undefined) {\n    return payload.providerInstanceId;\n  }\n  throw new Error(\n    payload.provider\n      ? `${operation}: provider instance id is required for provider '${payload.provider}'.`\n      : `${operation}: provider instance id is required.`,\n  );\n};\n\nconst correlateRuntimeEventWithInstance = (\n  source: {\n    readonly instanceId: ProviderInstanceId;\n    readonly provider: ProviderDriverKind;\n  },\n  event: ProviderRuntimeEvent,\n): ProviderRuntimeEvent => {\n  if (event.provider !== source.provider) {\n    throw new Error(\n      `ProviderService.streamEvents: provider instance '${source.instanceId}' is backed by driver '${source.provider}' but emitted driver '${event.provider}'.`,\n    );\n  }\n  if (event.providerInstanceId !== undefined && event.providerInstanceId !== source.instanceId) {\n    throw new Error(\n      `ProviderService.streamEvents: provider instance '${source.instanceId}' emitted event for instance '${event.providerInstanceId}'.`,\n    );\n  }\n  return { ...event, providerInstanceId: source.instanceId };\n};\n\nconst makeProviderService = Effect.fn(\"makeProviderService\")(function* (\n  options?: ProviderServiceLiveOptions,\n) {\n  const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);\n  const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;\n  // Options-provided logger wins (test overrides); otherwise we take whatever\n  // the `ProviderEventLoggers` tag exposes — `undefined` means \"no canonical\n  // log writer is attached\", which downstream code already handles as a\n  // no-op.\n  const canonicalEventLogger = options?.canonicalEventLogger ?? eventLoggers.canonical;\n\n  const registry = yield* ProviderAdapterRegistry.ProviderAdapterRegistry;\n  const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;\n  const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();\n  const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n  const prepareMcpSession = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) =>\n    McpSessionRegistry.issueActiveMcpCredential({ threadId, providerInstanceId }).pipe(\n      Effect.tap((credential) =>\n        credential\n          ? Effect.sync(() => McpProviderSession.setMcpProviderSession(credential.config))\n          : Effect.void,\n      ),\n    );\n  const clearMcpSession = (threadId: ThreadId) =>\n    McpSessionRegistry.revokeActiveMcpThread(threadId).pipe(\n      Effect.tap(() => Effect.sync(() => McpProviderSession.clearMcpProviderSession(threadId))),\n    );\n\n  const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>\n    Effect.succeed(event).pipe(\n      Effect.tap((canonicalEvent) =>\n        canonicalEventLogger\n          ? canonicalEventLogger.write(canonicalEvent, canonicalEvent.threadId)\n          : Effect.void,\n      ),\n      Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),\n      Effect.asVoid,\n    );\n\n  const requireBindingInstanceId = (\n    operation: string,\n    payload: {\n      readonly providerInstanceId?: ProviderInstanceId | undefined;\n      readonly provider?: ProviderDriverKind | undefined;\n    },\n  ): Effect.Effect<ProviderInstanceId, ProviderValidationError> =>\n    payload.providerInstanceId !== undefined\n      ? Effect.succeed(payload.providerInstanceId)\n      : Effect.fail(\n          toValidationError(\n            operation,\n            payload.provider\n              ? `Provider instance id is required for provider '${payload.provider}'.`\n              : \"Provider instance id is required.\",\n          ),\n        );\n\n  const upsertSessionBinding = (\n    session: ProviderSession,\n    threadId: ThreadId,\n    extra?: {\n      readonly modelSelection?: unknown;\n      readonly lastRuntimeEvent?: string;\n      readonly lastRuntimeEventAt?: string;\n    },\n  ) =>\n    Effect.gen(function* () {\n      const providerInstanceId = yield* requireBindingInstanceId(\n        \"ProviderService.upsertSessionBinding\",\n        session,\n      );\n      yield* directory.upsert({\n        threadId,\n        provider: session.provider,\n        providerInstanceId,\n        runtimeMode: session.runtimeMode,\n        status: toRuntimeStatus(session),\n        ...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),\n        runtimePayload: toRuntimePayloadFromSession(session, extra),\n      });\n    });\n\n  const processRuntimeEvent = (\n    source: {\n      readonly instanceId: ProviderInstanceId;\n      readonly provider: ProviderDriverKind;\n    },\n    event: ProviderRuntimeEvent,\n  ): Effect.Effect<void> =>\n    Effect.sync(() => correlateRuntimeEventWithInstance(source, event)).pipe(\n      Effect.flatMap((canonicalEvent) =>\n        increment(providerRuntimeEventsTotal, {\n          provider: canonicalEvent.provider,\n          eventType: canonicalEvent.type,\n        }).pipe(Effect.andThen(publishRuntimeEvent(canonicalEvent))),\n      ),\n    );\n\n  // `subscribedAdapters` is our source-of-truth for \"which instance adapters\n  // are currently wired into the runtime event bus\". It both tracks the set\n  // of live subscriptions (so `reconcileInstanceSubscriptions` can diff and\n  // fork only the *new* or *rebuilt* ones) and serves as the dynamic adapter\n  // list consumed by `stopStaleSessionsForThread`, `listSessions`, and\n  // `runStopAll` — replacing the pre-Slice-D startup snapshot so hot-added\n  // instances become visible to those call sites as soon as settings edits\n  // land.\n  const subscribedAdapters = yield* Ref.make(\n    new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>(),\n  );\n\n  const getAdapterEntries = Ref.get(subscribedAdapters).pipe(\n    Effect.map((map) => Array.from(map.entries())),\n  );\n\n  // Rebuild the map of id → adapter from the registry and fork a new event\n  // subscription for every instance that is either brand new or whose adapter\n  // identity changed (indicating the underlying `ProviderInstance` was torn\n  // down and rebuilt by `ProviderInstanceRegistry.reconcile`). Orphaned\n  // fibers for removed/replaced instances exit on their own because their\n  // adapter's `streamEvents` source terminates when the old scope closes.\n  const reconcileInstanceSubscriptions = Effect.gen(function* () {\n    const previous = yield* Ref.get(subscribedAdapters);\n    const currentIds = yield* registry.listInstances();\n    const next = new Map<ProviderInstanceId, ProviderAdapterShape<ProviderAdapterError>>();\n    for (const id of currentIds) {\n      const adapterOption = yield* registry\n        .getByInstance(id)\n        .pipe(Effect.tapError(Effect.logWarning), Effect.option);\n      if (Option.isNone(adapterOption)) continue;\n      const adapter = adapterOption.value;\n      next.set(id, adapter);\n      if (previous.get(id) !== adapter) {\n        yield* Stream.runForEach(adapter.streamEvents, (event) =>\n          processRuntimeEvent(\n            {\n              instanceId: id,\n              provider: adapter.provider,\n            },\n            event,\n          ),\n        ).pipe(Effect.forkScoped);\n      }\n    }\n    yield* Ref.set(subscribedAdapters, next);\n  });\n\n  const instanceChanges = yield* registry.subscribeChanges;\n  yield* reconcileInstanceSubscriptions;\n  yield* Stream.runForEach(\n    Stream.fromSubscription(instanceChanges),\n    () => reconcileInstanceSubscriptions,\n  ).pipe(Effect.forkScoped);\n\n  const recoverSessionForThread = Effect.fn(\"recoverSessionForThread\")(function* (input: {\n    readonly binding: ProviderSessionDirectory.ProviderRuntimeBinding;\n    readonly operation: string;\n  }) {\n    const bindingInstanceId = yield* requireBindingInstanceId(input.operation, input.binding);\n    yield* Effect.annotateCurrentSpan({\n      \"provider.operation\": \"recover-session\",\n      \"provider.kind\": input.binding.provider,\n      \"provider.instance_id\": bindingInstanceId,\n      \"provider.thread_id\": input.binding.threadId,\n    });\n    return yield* Effect.gen(function* () {\n      const adapter = yield* registry.getByInstance(bindingInstanceId);\n      const hasResumeCursor =\n        input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;\n      const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);\n      if (hasActiveSession) {\n        const activeSessions = yield* adapter.listSessions();\n        const existing = activeSessions.find(\n          (session) => session.threadId === input.binding.threadId,\n        );\n        if (existing) {\n          yield* upsertSessionBinding(\n            { ...existing, providerInstanceId: bindingInstanceId },\n            input.binding.threadId,\n          );\n          yield* analytics.record(\"provider.session.recovered\", {\n            provider: existing.provider,\n            strategy: \"adopt-existing\",\n            hasResumeCursor: existing.resumeCursor !== undefined,\n          });\n          return { adapter, session: existing } as const;\n        }\n      }\n\n      if (!hasResumeCursor) {\n        return yield* toValidationError(\n          input.operation,\n          `Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,\n        );\n      }\n\n      const persistedCwd = readPersistedCwd(input.binding.runtimePayload);\n      const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);\n\n      yield* prepareMcpSession(input.binding.threadId, bindingInstanceId);\n      const resumed = yield* adapter\n        .startSession({\n          threadId: input.binding.threadId,\n          provider: input.binding.provider,\n          providerInstanceId: bindingInstanceId,\n          ...(persistedCwd ? { cwd: persistedCwd } : {}),\n          ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),\n          ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),\n          runtimeMode: input.binding.runtimeMode ?? \"full-access\",\n        })\n        .pipe(Effect.onError(() => clearMcpSession(input.binding.threadId)));\n      if (resumed.provider !== adapter.provider) {\n        yield* clearMcpSession(input.binding.threadId);\n        return yield* toValidationError(\n          input.operation,\n          `Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,\n        );\n      }\n\n      yield* upsertSessionBinding(\n        { ...resumed, providerInstanceId: bindingInstanceId },\n        input.binding.threadId,\n      );\n      yield* analytics.record(\"provider.session.recovered\", {\n        provider: resumed.provider,\n        strategy: \"resume-thread\",\n        hasResumeCursor: resumed.resumeCursor !== undefined,\n      });\n      return { adapter, session: resumed } as const;\n    }).pipe(\n      withMetrics({\n        counter: providerSessionsTotal,\n        attributes: providerMetricAttributes(input.binding.provider, {\n          operation: \"recover\",\n        }),\n      }),\n    );\n  });\n\n  const resolveRoutableSession = Effect.fn(\"resolveRoutableSession\")(function* (input: {\n    readonly threadId: ThreadId;\n    readonly operation: string;\n    readonly allowRecovery: boolean;\n  }) {\n    const bindingOption = yield* directory.getBinding(input.threadId);\n    const binding = Option.getOrUndefined(bindingOption);\n    if (!binding) {\n      return yield* toValidationError(\n        input.operation,\n        `Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,\n      );\n    }\n    const instanceId = yield* requireBindingInstanceId(input.operation, binding);\n    const adapter = yield* registry.getByInstance(instanceId);\n\n    const hasRequestedSession = yield* adapter.hasSession(input.threadId);\n    if (hasRequestedSession) {\n      return {\n        adapter,\n        instanceId,\n        threadId: input.threadId,\n        runtimeMode: binding.runtimeMode,\n        isActive: true,\n      } as const;\n    }\n\n    if (!input.allowRecovery) {\n      return {\n        adapter,\n        instanceId,\n        threadId: input.threadId,\n        runtimeMode: binding.runtimeMode,\n        isActive: false,\n      } as const;\n    }\n\n    const recovered = yield* recoverSessionForThread({\n      binding,\n      operation: input.operation,\n    });\n    return {\n      adapter: recovered.adapter,\n      instanceId,\n      threadId: input.threadId,\n      runtimeMode: recovered.session.runtimeMode,\n      isActive: true,\n    } as const;\n  });\n\n  const stopStaleSessionsForThread = Effect.fn(\"stopStaleSessionsForThread\")(function* (input: {\n    readonly threadId: ThreadId;\n    readonly currentInstanceId: ProviderInstanceId;\n  }) {\n    const currentAdapters = yield* getAdapterEntries;\n    yield* Effect.forEach(\n      currentAdapters,\n      ([instanceId, adapter]) =>\n        instanceId === input.currentInstanceId\n          ? Effect.void\n          : Effect.gen(function* () {\n              const hasSession = yield* adapter.hasSession(input.threadId);\n              if (!hasSession) {\n                return;\n              }\n\n              yield* adapter.stopSession(input.threadId).pipe(\n                Effect.tap(() =>\n                  analytics.record(\"provider.session.stopped\", {\n                    provider: adapter.provider,\n                  }),\n                ),\n                Effect.catchCause((cause) =>\n                  Effect.logWarning(\"provider.session.stop-stale-failed\", {\n                    threadId: input.threadId,\n                    provider: adapter.provider,\n                    cause,\n                  }),\n                ),\n              );\n            }),\n      { discard: true },\n    );\n  });\n\n  const startSession: ProviderServiceMethod<\"startSession\"> = Effect.fn(\"startSession\")(\n    function* (threadId, rawInput) {\n      const parsed = yield* decodeInputOrValidationError({\n        operation: \"ProviderService.startSession\",\n        schema: ProviderSessionStartInput,\n        payload: rawInput,\n      });\n\n      const resolvedInstanceId = yield* requireBindingInstanceId(\n        \"ProviderService.startSession\",\n        parsed,\n      );\n      let metricProvider = parsed.provider ?? String(resolvedInstanceId);\n      yield* Effect.annotateCurrentSpan({\n        \"provider.operation\": \"start-session\",\n        \"provider.instance_id\": resolvedInstanceId,\n        \"provider.thread_id\": threadId,\n        \"provider.runtime_mode\": parsed.runtimeMode,\n      });\n      return yield* Effect.gen(function* () {\n        const instanceInfo = yield* registry.getInstanceInfo(resolvedInstanceId);\n        const resolvedProvider = instanceInfo.driverKind;\n        metricProvider = resolvedProvider;\n        if (parsed.provider !== undefined && parsed.provider !== resolvedProvider) {\n          return yield* toValidationError(\n            \"ProviderService.startSession\",\n            `Provider instance '${resolvedInstanceId}' belongs to driver '${resolvedProvider}', not '${parsed.provider}'.`,\n          );\n        }\n        const input = {\n          ...parsed,\n          threadId,\n          provider: resolvedProvider,\n        };\n        if (!instanceInfo.enabled) {\n          return yield* toValidationError(\n            \"ProviderService.startSession\",\n            `Provider instance '${resolvedInstanceId}' is disabled in Synaptic Code settings.`,\n          );\n        }\n        const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));\n        const effectiveResumeCursor =\n          input.resumeCursor ??\n          (persistedBinding?.providerInstanceId === resolvedInstanceId\n            ? persistedBinding.resumeCursor\n            : undefined);\n        const effectiveCwd =\n          input.cwd ??\n          (persistedBinding?.providerInstanceId === resolvedInstanceId\n            ? readPersistedCwd(persistedBinding.runtimePayload)\n            : undefined);\n        yield* Effect.annotateCurrentSpan({\n          \"provider.kind\": resolvedProvider,\n          \"provider.resume_cursor.source\":\n            input.resumeCursor !== undefined\n              ? \"request\"\n              : effectiveResumeCursor !== undefined &&\n                  persistedBinding?.providerInstanceId === resolvedInstanceId\n                ? \"persisted\"\n                : \"none\",\n          \"provider.resume_cursor.present\": effectiveResumeCursor !== undefined,\n          \"provider.cwd.source\":\n            input.cwd !== undefined\n              ? \"request\"\n              : effectiveCwd !== undefined &&\n                  persistedBinding?.providerInstanceId === resolvedInstanceId\n                ? \"persisted\"\n                : \"none\",\n          \"provider.cwd.effective\": effectiveCwd ?? \"\",\n        });\n        const adapter = yield* registry.getByInstance(resolvedInstanceId);\n        yield* prepareMcpSession(threadId, resolvedInstanceId);\n        const session = yield* adapter\n          .startSession({\n            ...input,\n            providerInstanceId: resolvedInstanceId,\n            ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}),\n            ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),\n          })\n          .pipe(Effect.onError(() => clearMcpSession(threadId)));\n\n        if (session.provider !== adapter.provider) {\n          yield* clearMcpSession(threadId);\n          return yield* toValidationError(\n            \"ProviderService.startSession\",\n            `Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,\n          );\n        }\n        const sessionWithInstance = {\n          ...session,\n          providerInstanceId: resolvedInstanceId,\n        };\n\n        yield* stopStaleSessionsForThread({\n          threadId,\n          currentInstanceId: resolvedInstanceId,\n        });\n        yield* upsertSessionBinding(sessionWithInstance, threadId, {\n          modelSelection: input.modelSelection,\n        });\n        yield* analytics.record(\"provider.session.started\", {\n          provider: sessionWithInstance.provider,\n          runtimeMode: input.runtimeMode,\n          hasResumeCursor: sessionWithInstance.resumeCursor !== undefined,\n          hasCwd: typeof effectiveCwd === \"string\" && effectiveCwd.trim().length > 0,\n          hasModel:\n            typeof input.modelSelection?.model === \"string\" &&\n            input.modelSelection.model.trim().length > 0,\n        });\n\n        // Changing runtime mode restarts the session, so the transition is only\n        // observable here, by diffing against the mode the previous session for\n        // this thread was bound to. Recording it separately is what makes the\n        // \"started supervised, switched to full access\" funnel answerable.\n        const previousRuntimeMode = persistedBinding?.runtimeMode;\n        if (previousRuntimeMode !== undefined && previousRuntimeMode !== input.runtimeMode) {\n          yield* analytics.record(\"provider.runtime_mode.changed\", {\n            provider: sessionWithInstance.provider,\n            from: previousRuntimeMode,\n            to: input.runtimeMode,\n          });\n        }\n\n        return sessionWithInstance;\n      }).pipe(\n        withMetrics({\n          counter: providerSessionsTotal,\n          attributes: () =>\n            providerMetricAttributes(metricProvider, {\n              operation: \"start\",\n            }),\n        }),\n      );\n    },\n  );\n\n  const sendTurn: ProviderServiceMethod<\"sendTurn\"> = Effect.fn(\"sendTurn\")(function* (rawInput) {\n    const parsed = yield* decodeInputOrValidationError({\n      operation: \"ProviderService.sendTurn\",\n      schema: ProviderSendTurnInput,\n      payload: rawInput,\n    });\n\n    const input = {\n      ...parsed,\n      attachments: parsed.attachments ?? [],\n    };\n    if (!input.input && input.attachments.length === 0) {\n      return yield* toValidationError(\n        \"ProviderService.sendTurn\",\n        \"Either input text or at least one attachment is required\",\n      );\n    }\n    yield* Effect.annotateCurrentSpan({\n      \"provider.operation\": \"send-turn\",\n      \"provider.thread_id\": input.threadId,\n      \"provider.interaction_mode\": input.interactionMode,\n      \"provider.attachment_count\": input.attachments.length,\n    });\n    let metricProvider = \"unknown\";\n    let metricModel = input.modelSelection?.model;\n    return yield* Effect.gen(function* () {\n      const routed = yield* resolveRoutableSession({\n        threadId: input.threadId,\n        operation: \"ProviderService.sendTurn\",\n        allowRecovery: true,\n      });\n      metricProvider = routed.adapter.provider;\n      metricModel = input.modelSelection?.model;\n      yield* Effect.annotateCurrentSpan({\n        \"provider.kind\": routed.adapter.provider,\n        ...(input.modelSelection?.model ? { \"provider.model\": input.modelSelection.model } : {}),\n      });\n      // A turn is the clearest sign a session is still alive. The MCP\n      // credential is minted once at session start and cannot be rotated into\n      // an already-spawned agent process, so we keep the existing token valid\n      // rather than issuing a new one: sessions that go a long time between\n      // browser tool calls used to lose the toolkit outright.\n      yield* McpSessionRegistry.touchActiveMcpThread(input.threadId);\n      const turn = yield* routed.adapter.sendTurn(input);\n      yield* directory.upsert({\n        threadId: input.threadId,\n        provider: routed.adapter.provider,\n        providerInstanceId: routed.instanceId,\n        status: \"running\",\n        ...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),\n        runtimePayload: {\n          ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),\n          activeTurnId: turn.turnId,\n          lastRuntimeEvent: \"provider.sendTurn\",\n          lastRuntimeEventAt: yield* nowIso,\n        },\n      });\n      yield* analytics.record(\"provider.turn.sent\", {\n        provider: routed.adapter.provider,\n        model: input.modelSelection?.model,\n        interactionMode: input.interactionMode,\n        // Session-start events alone skew runtime mode toward users who toggle\n        // often, since every toggle restarts the session. Recording it per turn\n        // gives a usage-weighted view and lets it cross with interactionMode.\n        runtimeMode: routed.runtimeMode,\n        attachmentCount: input.attachments.length,\n        hasInput: typeof input.input === \"string\" && input.input.trim().length > 0,\n      });\n      return turn;\n    }).pipe(\n      withMetrics({\n        counter: providerTurnsTotal,\n        timer: providerTurnDuration,\n        attributes: () =>\n          providerTurnMetricAttributes({\n            provider: metricProvider,\n            model: metricModel,\n            extra: {\n              operation: \"send\",\n            },\n          }),\n      }),\n    );\n  });\n\n  const interruptTurn: ProviderServiceMethod<\"interruptTurn\"> = Effect.fn(\"interruptTurn\")(\n    function* (rawInput) {\n      const input = yield* decodeInputOrValidationError({\n        operation: \"ProviderService.interruptTurn\",\n        schema: ProviderInterruptTurnInput,\n        payload: rawInput,\n      });\n      let metricProvider = \"unknown\";\n      return yield* Effect.gen(function* () {\n        const routed = yield* resolveRoutableSession({\n          threadId: input.threadId,\n          operation: \"ProviderService.interruptTurn\",\n          allowRecovery: true,\n        });\n        metricProvider = routed.adapter.provider;\n        yield* Effect.annotateCurrentSpan({\n          \"provider.operation\": \"interrupt-turn\",\n          \"provider.kind\": routed.adapter.provider,\n          \"provider.thread_id\": input.threadId,\n          \"provider.turn_id\": input.turnId,\n        });\n        yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);\n        yield* analytics.record(\"provider.turn.interrupted\", {\n          provider: routed.adapter.provider,\n        });\n      }).pipe(\n        withMetrics({\n          counter: providerTurnsTotal,\n          outcomeAttributes: () =>\n            providerMetricAttributes(metricProvider, {\n              operation: \"interrupt\",\n            }),\n        }),\n      );\n    },\n  );\n\n  const respondToRequest: ProviderServiceMethod<\"respondToRequest\"> = Effect.fn(\"respondToRequest\")(\n    function* (rawInput) {\n      const input = yield* decodeInputOrValidationError({\n        operation: \"ProviderService.respondToRequest\",\n        schema: ProviderRespondToRequestInput,\n        payload: rawInput,\n      });\n      let metricProvider = \"unknown\";\n      return yield* Effect.gen(function* () {\n        const routed = yield* resolveRoutableSession({\n          threadId: input.threadId,\n          operation: \"ProviderService.respondToRequest\",\n          allowRecovery: true,\n        });\n        metricProvider = routed.adapter.provider;\n        yield* Effect.annotateCurrentSpan({\n          \"provider.operation\": \"respond-to-request\",\n          \"provider.kind\": routed.adapter.provider,\n          \"provider.thread_id\": input.threadId,\n          \"provider.request_id\": input.requestId,\n        });\n        yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);\n        yield* analytics.record(\"provider.request.responded\", {\n          provider: routed.adapter.provider,\n          decision: input.decision,\n        });\n      }).pipe(\n        withMetrics({\n          counter: providerTurnsTotal,\n          outcomeAttributes: () =>\n            providerMetricAttributes(metricProvider, {\n              operation: \"approval-response\",\n            }),\n        }),\n      );\n    },\n  );\n\n  const respondToUserInput: ProviderServiceMethod<\"respondToUserInput\"> = Effect.fn(\n    \"respondToUserInput\",\n  )(function* (rawInput) {\n    const input = yield* decodeInputOrValidationError({\n      operation: \"ProviderService.respondToUserInput\",\n      schema: ProviderRespondToUserInputInput,\n      payload: rawInput,\n    });\n    let metricProvider = \"unknown\";\n    return yield* Effect.gen(function* () {\n      const routed = yield* resolveRoutableSession({\n        threadId: input.threadId,\n        operation: \"ProviderService.respondToUserInput\",\n        allowRecovery: true,\n      });\n      metricProvider = routed.adapter.provider;\n      yield* Effect.annotateCurrentSpan({\n        \"provider.operation\": \"respond-to-user-input\",\n        \"provider.kind\": routed.adapter.provider,\n        \"provider.thread_id\": input.threadId,\n        \"provider.request_id\": input.requestId,\n      });\n      yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);\n    }).pipe(\n      withMetrics({\n        counter: providerTurnsTotal,\n        outcomeAttributes: () =>\n          providerMetricAttributes(metricProvider, {\n            operation: \"user-input-response\",\n          }),\n      }),\n    );\n  });\n\n  const stopSession: ProviderServiceMethod<\"stopSession\"> = Effect.fn(\"stopSession\")(\n    function* (rawInput) {\n      const input = yield* decodeInputOrValidationError({\n        operation: \"ProviderService.stopSession\",\n        schema: ProviderStopSessionInput,\n        payload: rawInput,\n      });\n      let metricProvider = \"unknown\";\n      return yield* Effect.gen(function* () {\n        const routed = yield* resolveRoutableSession({\n          threadId: input.threadId,\n          operation: \"ProviderService.stopSession\",\n          allowRecovery: false,\n        });\n        metricProvider = routed.adapter.provider;\n        yield* Effect.annotateCurrentSpan({\n          \"provider.operation\": \"stop-session\",\n          \"provider.kind\": routed.adapter.provider,\n          \"provider.thread_id\": input.threadId,\n        });\n        if (routed.isActive) {\n          yield* routed.adapter.stopSession(routed.threadId);\n        }\n        yield* clearMcpSession(input.threadId);\n        yield* directory.upsert({\n          threadId: input.threadId,\n          provider: routed.adapter.provider,\n          providerInstanceId: routed.instanceId,\n          status: \"stopped\",\n          runtimePayload: {\n            activeTurnId: null,\n          },\n        });\n        yield* analytics.record(\"provider.session.stopped\", {\n          provider: routed.adapter.provider,\n        });\n      }).pipe(\n        withMetrics({\n          counter: providerSessionsTotal,\n          outcomeAttributes: () =>\n            providerMetricAttributes(metricProvider, {\n              operation: \"stop\",\n            }),\n        }),\n      );\n    },\n  );\n\n  const listSessions: ProviderServiceMethod<\"listSessions\"> = Effect.fn(\"listSessions\")(\n    function* () {\n      const currentAdapters = yield* getAdapterEntries;\n      const sessionsByProvider = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>\n        adapter.listSessions().pipe(\n          Effect.map((sessions) =>\n            sessions.map((session) => ({\n              ...session,\n              providerInstanceId: instanceId,\n            })),\n          ),\n        ),\n      );\n      const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);\n      const persistedBindings = yield* directory.listThreadIds().pipe(\n        Effect.flatMap((threadIds) =>\n          Effect.forEach(\n            threadIds,\n            (threadId) =>\n              directory\n                .getBinding(threadId)\n                .pipe(\n                  Effect.orElseSucceed(() =>\n                    Option.none<ProviderSessionDirectory.ProviderRuntimeBinding>(),\n                  ),\n                ),\n            { concurrency: \"unbounded\" },\n          ),\n        ),\n        Effect.orElseSucceed(\n          () => [] as Array<Option.Option<ProviderSessionDirectory.ProviderRuntimeBinding>>,\n        ),\n      );\n      const bindingsByThreadId = new Map<\n        ThreadId,\n        ProviderSessionDirectory.ProviderRuntimeBinding\n      >();\n      for (const bindingOption of persistedBindings) {\n        const binding = Option.getOrUndefined(bindingOption);\n        if (binding) {\n          bindingsByThreadId.set(binding.threadId, binding);\n        }\n      }\n\n      const sessions: ProviderSession[] = [];\n      for (const session of activeSessions) {\n        const binding = bindingsByThreadId.get(session.threadId);\n        if (!binding) {\n          sessions.push(session);\n          continue;\n        }\n\n        const overrides: {\n          resumeCursor?: ProviderSession[\"resumeCursor\"];\n          runtimeMode?: ProviderSession[\"runtimeMode\"];\n          providerInstanceId?: ProviderSession[\"providerInstanceId\"];\n        } = {};\n        overrides.providerInstanceId = dieOnMissingBindingInstanceId(\n          \"ProviderService.listSessions\",\n          binding,\n        );\n        if (binding.provider !== session.provider) {\n          return yield* Effect.die(\n            new Error(\n              `ProviderService.listSessions: thread '${session.threadId}' is active on provider '${session.provider}' but persisted binding names provider '${binding.provider}'.`,\n            ),\n          );\n        }\n        if (overrides.providerInstanceId !== session.providerInstanceId) {\n          return yield* Effect.die(\n            new Error(\n              `ProviderService.listSessions: thread '${session.threadId}' is active on provider instance '${session.providerInstanceId}' but persisted binding names '${overrides.providerInstanceId}'.`,\n            ),\n          );\n        }\n        if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {\n          overrides.resumeCursor = binding.resumeCursor;\n        }\n        if (binding.runtimeMode !== undefined) {\n          overrides.runtimeMode = binding.runtimeMode;\n        }\n        sessions.push(Object.assign({}, session, overrides));\n      }\n      return sessions;\n    },\n  );\n\n  const getCapabilities: ProviderServiceMethod<\"getCapabilities\"> = (instanceId) =>\n    registry.getByInstance(instanceId).pipe(Effect.map((adapter) => adapter.capabilities));\n\n  const getInstanceInfo: ProviderServiceMethod<\"getInstanceInfo\"> = (instanceId) =>\n    registry.getInstanceInfo(instanceId);\n\n  const rollbackConversation: ProviderServiceMethod<\"rollbackConversation\"> = Effect.fn(\n    \"rollbackConversation\",\n  )(function* (rawInput) {\n    const input = yield* decodeInputOrValidationError({\n      operation: \"ProviderService.rollbackConversation\",\n      schema: ProviderRollbackConversationInput,\n      payload: rawInput,\n    });\n    if (input.numTurns === 0) {\n      return;\n    }\n    let metricProvider = \"unknown\";\n    return yield* Effect.gen(function* () {\n      const routed = yield* resolveRoutableSession({\n        threadId: input.threadId,\n        operation: \"ProviderService.rollbackConversation\",\n        allowRecovery: true,\n      });\n      metricProvider = routed.adapter.provider;\n      yield* Effect.annotateCurrentSpan({\n        \"provider.operation\": \"rollback-conversation\",\n        \"provider.kind\": routed.adapter.provider,\n        \"provider.thread_id\": input.threadId,\n        \"provider.rollback_turns\": input.numTurns,\n      });\n      yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);\n      yield* analytics.record(\"provider.conversation.rolled_back\", {\n        provider: routed.adapter.provider,\n        turns: input.numTurns,\n      });\n    }).pipe(\n      withMetrics({\n        counter: providerTurnsTotal,\n        outcomeAttributes: () =>\n          providerMetricAttributes(metricProvider, {\n            operation: \"rollback\",\n          }),\n      }),\n    );\n  });\n\n  const runStopAll = Effect.fn(\"runStopAll\")(function* () {\n    const threadIds = yield* directory.listThreadIds();\n    const currentAdapters = yield* getAdapterEntries;\n    const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>\n      adapter.listSessions().pipe(\n        Effect.map((sessions) =>\n          sessions.map((session) => ({\n            ...session,\n            providerInstanceId: instanceId,\n          })),\n        ),\n      ),\n    ).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));\n    yield* Effect.forEach(activeSessions, (session) =>\n      Effect.flatMap(nowIso, (lastRuntimeEventAt) =>\n        upsertSessionBinding(session, session.threadId, {\n          lastRuntimeEvent: \"provider.stopAll\",\n          lastRuntimeEventAt,\n        }),\n      ),\n    ).pipe(Effect.asVoid);\n    yield* Effect.forEach(currentAdapters, ([, adapter]) => adapter.stopAll()).pipe(Effect.asVoid);\n    yield* McpSessionRegistry.revokeAllActiveMcpCredentials();\n    McpProviderSession.clearAllMcpProviderSessions();\n    const bindings = yield* directory.listBindings().pipe(Effect.orElseSucceed(() => []));\n    yield* Effect.forEach(bindings, (binding) =>\n      Effect.gen(function* () {\n        const providerInstanceId = dieOnMissingBindingInstanceId(\n          \"ProviderService.stopAll\",\n          binding,\n        );\n        return yield* directory.upsert({\n          threadId: binding.threadId,\n          provider: binding.provider,\n          providerInstanceId,\n          status: \"stopped\",\n          runtimePayload: {\n            activeTurnId: null,\n            lastRuntimeEvent: \"provider.stopAll\",\n            lastRuntimeEventAt: yield* nowIso,\n          },\n        });\n      }),\n    ).pipe(Effect.asVoid);\n    yield* analytics.record(\"provider.sessions.stopped_all\", {\n      sessionCount: threadIds.length,\n    });\n    yield* analytics.flush;\n  });\n\n  yield* Effect.addFinalizer(() =>\n    runStopAll().pipe(\n      Effect.catchCause((cause) =>\n        Effect.logWarning(\"failed to stop provider service\", {\n          errorTag: causeErrorTag(cause),\n        }),\n      ),\n    ),\n  );\n\n  return {\n    startSession,\n    sendTurn,\n    interruptTurn,\n    respondToRequest,\n    respondToUserInput,\n    stopSession,\n    listSessions,\n    getCapabilities,\n    getInstanceInfo,\n    rollbackConversation,\n    // Each access creates a fresh PubSub subscription so that multiple\n    // consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each\n    // independently receive all runtime events.\n    get streamEvents(): ProviderServiceMethod<\"streamEvents\"> {\n      return Stream.fromPubSub(runtimeEventPubSub);\n    },\n  } satisfies ProviderService.ProviderService[\"Service\"];\n});\n\nexport const ProviderServiceLive = Layer.effect(\n  ProviderService.ProviderService,\n  makeProviderService(),\n);\n\nexport function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {\n  return Layer.effect(ProviderService.ProviderService, makeProviderService(options));\n}\n","import * as Clock from \"effect/Clock\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schedule from \"effect/Schedule\";\n\nimport { ProjectionSnapshotQuery } from \"../../orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport { ProviderSessionDirectory } from \"../Services/ProviderSessionDirectory.ts\";\nimport {\n  ProviderSessionReaper,\n  type ProviderSessionReaperShape,\n} from \"../Services/ProviderSessionReaper.ts\";\nimport { forkParked } from \"../../serverActivation.ts\";\nimport { ProviderService } from \"../Services/ProviderService.ts\";\n\nconst DEFAULT_INACTIVITY_THRESHOLD_MS = 30 * 60 * 1000;\nconst DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;\n\nexport interface ProviderSessionReaperLiveOptions {\n  readonly inactivityThresholdMs?: number;\n  readonly sweepIntervalMs?: number;\n}\n\nconst makeProviderSessionReaper = (options?: ProviderSessionReaperLiveOptions) =>\n  Effect.gen(function* () {\n    const providerService = yield* ProviderService;\n    const directory = yield* ProviderSessionDirectory;\n    const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n\n    const inactivityThresholdMs = Math.max(\n      1,\n      options?.inactivityThresholdMs ?? DEFAULT_INACTIVITY_THRESHOLD_MS,\n    );\n    const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);\n\n    const sweep = Effect.gen(function* () {\n      const bindings = yield* directory.listBindings();\n      const now = yield* Clock.currentTimeMillis;\n      let reapedCount = 0;\n\n      for (const binding of bindings) {\n        if (binding.status === \"stopped\") {\n          continue;\n        }\n\n        const lastSeenMs = Date.parse(binding.lastSeenAt);\n        if (Number.isNaN(lastSeenMs)) {\n          yield* Effect.logWarning(\"provider.session.reaper.invalid-last-seen\", {\n            threadId: binding.threadId,\n            provider: binding.provider,\n            lastSeenAt: binding.lastSeenAt,\n          });\n          continue;\n        }\n\n        const idleDurationMs = now - lastSeenMs;\n        if (idleDurationMs < inactivityThresholdMs) {\n          continue;\n        }\n\n        const thread = yield* projectionSnapshotQuery\n          .getThreadShellById(binding.threadId)\n          .pipe(Effect.map(Option.getOrUndefined));\n        if (thread?.session?.activeTurnId != null) {\n          yield* Effect.logDebug(\"provider.session.reaper.skipped-active-turn\", {\n            threadId: binding.threadId,\n            activeTurnId: thread.session.activeTurnId,\n            idleDurationMs,\n          });\n          continue;\n        }\n\n        // The turn can settle while background work runs on (subagent\n        // fleets, workflow runs, Monitor watch loops). Those live inside the\n        // provider process, so stopping the session would kill them silently,\n        // and nothing bumps lastSeenAt between turns.\n        if (thread?.backgroundLiveness != null) {\n          yield* Effect.logDebug(\"provider.session.reaper.skipped-background-work\", {\n            threadId: binding.threadId,\n            backgroundLiveness: thread.backgroundLiveness,\n            idleDurationMs,\n          });\n          continue;\n        }\n\n        const reaped = yield* providerService.stopSession({ threadId: binding.threadId }).pipe(\n          Effect.tap(() =>\n            Effect.logInfo(\"provider.session.reaped\", {\n              threadId: binding.threadId,\n              provider: binding.provider,\n              idleDurationMs,\n              reason: \"inactivity_threshold\",\n            }),\n          ),\n          Effect.as(true),\n          Effect.catchCause((cause) =>\n            Effect.logWarning(\"provider.session.reaper.stop-failed\", {\n              threadId: binding.threadId,\n              provider: binding.provider,\n              idleDurationMs,\n              cause,\n            }).pipe(Effect.as(false)),\n          ),\n        );\n\n        if (reaped) {\n          reapedCount += 1;\n        }\n      }\n\n      if (reapedCount > 0) {\n        yield* Effect.logInfo(\"provider.session.reaper.sweep-complete\", {\n          reapedCount,\n          totalBindings: bindings.length,\n        });\n      }\n    });\n\n    const start: ProviderSessionReaperShape[\"start\"] = () =>\n      Effect.gen(function* () {\n        yield* forkParked(\n          sweep.pipe(\n            Effect.catch((error: unknown) =>\n              Effect.logWarning(\"provider.session.reaper.sweep-failed\", {\n                error,\n              }),\n            ),\n            Effect.catchDefect((defect: unknown) =>\n              Effect.logWarning(\"provider.session.reaper.sweep-defect\", {\n                defect,\n              }),\n            ),\n            Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs))),\n          ),\n        );\n\n        yield* Effect.logInfo(\"provider.session.reaper.started\", {\n          inactivityThresholdMs,\n          sweepIntervalMs,\n        });\n      });\n\n    return {\n      start,\n    } satisfies ProviderSessionReaperShape;\n  });\n\nexport const makeProviderSessionReaperLive = (options?: ProviderSessionReaperLiveOptions) =>\n  Layer.effect(ProviderSessionReaper, makeProviderSessionReaper(options));\n\nexport const ProviderSessionReaperLive = makeProviderSessionReaperLive();\n","import type {\n  ProviderDriverKind,\n  ModelCapabilities,\n  ServerProvider,\n  ServerProviderAuth,\n  ServerProviderSkill,\n  ServerProviderSlashCommand,\n  ServerProviderModel,\n  ServerProviderState,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as PlatformError from \"effect/PlatformError\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { normalizeCustomModelSlug } from \"@t3tools/shared/model\";\nimport { isWindowsCommandNotFound } from \"../processRunner.ts\";\nimport { createProviderVersionAdvisory } from \"./providerMaintenance.ts\";\nimport { collectUint8StreamText } from \"../stream/collectUint8StreamText.ts\";\n\nexport const DEFAULT_TIMEOUT_MS = 4_000;\n// Auth status checks involve disk/network lookups and can be slow on first run (especially Windows)\nexport const AUTH_PROBE_TIMEOUT_MS = 10_000;\n\nexport interface CommandResult {\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly code: number;\n}\n\nexport class ProviderCommandNotFoundError extends Schema.TaggedErrorClass<ProviderCommandNotFoundError>()(\n  \"ProviderCommandNotFoundError\",\n  {\n    binaryPath: Schema.String,\n    exitCode: Schema.Number,\n    stdoutLength: Schema.Number,\n    stderrLength: Schema.Number,\n  },\n) {\n  override get message(): string {\n    return `Provider command ${this.binaryPath} was not found (exit code ${this.exitCode}).`;\n  }\n}\n\nconst isProviderCommandNotFoundError = Schema.is(ProviderCommandNotFoundError);\n\nexport interface ProviderProbeResult {\n  readonly installed: boolean;\n  readonly version: string | null;\n  readonly status: Exclude<ServerProviderState, \"disabled\">;\n  readonly auth: ServerProviderAuth;\n  readonly message?: string;\n}\n\nexport interface ServerProviderPresentation {\n  readonly displayName: string;\n  readonly badgeLabel?: string;\n  readonly showInteractionModeToggle?: boolean;\n  readonly requiresNewThreadForModelChange?: boolean;\n}\n\nexport type ServerProviderDraft = Omit<ServerProvider, \"instanceId\" | \"driver\">;\n\nexport function nonEmptyTrimmed(value: string | undefined): string | undefined {\n  if (!value) return undefined;\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function isCommandMissingCause(error: unknown): boolean {\n  if (isProviderCommandNotFoundError(error)) return true;\n  return error instanceof PlatformError.PlatformError && error.reason._tag === \"NotFound\";\n}\n\nexport const spawnAndCollect = (binaryPath: string, command: ChildProcess.Command) =>\n  Effect.gen(function* () {\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const child = yield* spawner.spawn(command);\n    const [stdout, stderr, exitCode] = yield* Effect.all(\n      [\n        collectStreamAsString(child.stdout),\n        collectStreamAsString(child.stderr),\n        child.exitCode.pipe(Effect.map(Number)),\n      ],\n      { concurrency: \"unbounded\" },\n    );\n\n    const result: CommandResult = { stdout, stderr, code: exitCode };\n    if (yield* isWindowsCommandNotFound(exitCode, stderr)) {\n      return yield* new ProviderCommandNotFoundError({\n        binaryPath,\n        exitCode,\n        stdoutLength: stdout.length,\n        stderrLength: stderr.length,\n      });\n    }\n    return result;\n  }).pipe(Effect.scoped);\n\nexport function detailFromResult(\n  result: CommandResult & { readonly timedOut?: boolean },\n): string | undefined {\n  if (result.timedOut) return \"Timed out while running command.\";\n  const stderr = nonEmptyTrimmed(result.stderr);\n  if (stderr) return stderr;\n  const stdout = nonEmptyTrimmed(result.stdout);\n  if (stdout) return stdout;\n  if (result.code !== 0) {\n    return `Command exited with code ${result.code}.`;\n  }\n  return undefined;\n}\n\nexport function extractAuthBoolean(value: unknown): boolean | undefined {\n  if (globalThis.Array.isArray(value)) {\n    for (const entry of value) {\n      const nested = extractAuthBoolean(entry);\n      if (nested !== undefined) return nested;\n    }\n    return undefined;\n  }\n\n  if (!value || typeof value !== \"object\") return undefined;\n\n  const record = value as Record<string, unknown>;\n  for (const key of [\"authenticated\", \"isAuthenticated\", \"loggedIn\", \"isLoggedIn\"] as const) {\n    if (typeof record[key] === \"boolean\") return record[key];\n  }\n  for (const key of [\"auth\", \"status\", \"session\", \"account\"] as const) {\n    const nested = extractAuthBoolean(record[key]);\n    if (nested !== undefined) return nested;\n  }\n  return undefined;\n}\n\nexport function parseGenericCliVersion(output: string): string | null {\n  const match = output.match(/\\b(\\d+\\.\\d+\\.\\d+)\\b/);\n  return match?.[1] ?? null;\n}\n\nexport function providerModelsFromSettings(\n  builtInModels: ReadonlyArray<ServerProviderModel>,\n  customModels: ReadonlyArray<string>,\n  customModelCapabilities: ModelCapabilities,\n): ReadonlyArray<ServerProviderModel> {\n  const resolvedBuiltInModels = [...builtInModels];\n  const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));\n  const customEntries: ServerProviderModel[] = [];\n\n  for (const candidate of customModels) {\n    const normalized = normalizeCustomModelSlug(candidate);\n    if (!normalized || seen.has(normalized)) {\n      continue;\n    }\n    seen.add(normalized);\n    customEntries.push({\n      slug: normalized,\n      name: normalized,\n      isCustom: true,\n      capabilities: customModelCapabilities,\n    });\n  }\n\n  return [...resolvedBuiltInModels, ...customEntries];\n}\n\nexport function buildSelectOptionDescriptor(input: {\n  readonly id: string;\n  readonly label: string;\n  readonly options:\n    | ReadonlyArray<{ value: string; label: string; isDefault?: boolean | undefined }>\n    | undefined;\n  readonly description?: string;\n  readonly promptInjectedValues?: ReadonlyArray<string>;\n}) {\n  const options = (input.options ?? []).map((option) =>\n    option.isDefault\n      ? { id: option.value, label: option.label, isDefault: true }\n      : { id: option.value, label: option.label },\n  );\n  const currentValue = options.find((option) => option.isDefault)?.id;\n  return {\n    id: input.id,\n    label: input.label,\n    type: \"select\" as const,\n    options,\n    ...(currentValue ? { currentValue } : {}),\n    ...(input.description ? { description: input.description } : {}),\n    ...(input.promptInjectedValues && input.promptInjectedValues.length > 0\n      ? { promptInjectedValues: [...input.promptInjectedValues] }\n      : {}),\n  };\n}\n\nexport function buildBooleanOptionDescriptor(input: {\n  readonly id: string;\n  readonly label: string;\n  readonly currentValue?: boolean;\n  readonly description?: string;\n}) {\n  return {\n    id: input.id,\n    label: input.label,\n    type: \"boolean\" as const,\n    ...(input.description ? { description: input.description } : {}),\n    ...(typeof input.currentValue === \"boolean\" ? { currentValue: input.currentValue } : {}),\n  };\n}\n\nexport function buildServerProvider(input: {\n  driver?: ProviderDriverKind;\n  presentation: ServerProviderPresentation;\n  enabled: boolean;\n  checkedAt: string;\n  models: ReadonlyArray<ServerProviderModel>;\n  slashCommands?: ReadonlyArray<ServerProviderSlashCommand>;\n  skills?: ReadonlyArray<ServerProviderSkill>;\n  probe: ProviderProbeResult;\n}): ServerProviderDraft {\n  const versionAdvisory = input.driver\n    ? createProviderVersionAdvisory({\n        driver: input.driver,\n        currentVersion: input.probe.version,\n        checkedAt: input.checkedAt,\n      })\n    : undefined;\n  return {\n    displayName: input.presentation.displayName,\n    ...(input.presentation.badgeLabel ? { badgeLabel: input.presentation.badgeLabel } : {}),\n    ...(typeof input.presentation.showInteractionModeToggle === \"boolean\"\n      ? { showInteractionModeToggle: input.presentation.showInteractionModeToggle }\n      : {}),\n    ...(typeof input.presentation.requiresNewThreadForModelChange === \"boolean\"\n      ? { requiresNewThreadForModelChange: input.presentation.requiresNewThreadForModelChange }\n      : {}),\n    enabled: input.enabled,\n    installed: input.probe.installed,\n    version: input.probe.version,\n    status: input.enabled ? input.probe.status : \"disabled\",\n    auth: input.probe.auth,\n    checkedAt: input.checkedAt,\n    ...(input.probe.message ? { message: input.probe.message } : {}),\n    models: input.models,\n    slashCommands: [...(input.slashCommands ?? [])],\n    skills: [...(input.skills ?? [])],\n    ...(versionAdvisory ? { versionAdvisory } : {}),\n  };\n}\n\nexport const collectStreamAsString = <E>(\n  stream: Stream.Stream<Uint8Array, E>,\n): Effect.Effect<string, E> =>\n  collectUint8StreamText({ stream }).pipe(Effect.map((collected) => collected.text));\n","import * as NodeURL from \"node:url\";\n\nimport type { ChatAttachment, ProviderApprovalDecision, RuntimeMode } from \"@t3tools/contracts\";\nimport {\n  createOpencodeClient,\n  type Agent,\n  type FilePartInput,\n  type Model,\n  type OpencodeClient,\n  type PermissionRuleset,\n  type ProviderListResponse,\n  type QuestionAnswer,\n  type QuestionRequest,\n} from \"@opencode-ai/sdk/v2\";\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Data from \"effect/Data\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as P from \"effect/Predicate\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { isWindowsCommandNotFound } from \"../processRunner.ts\";\nimport { collectStreamAsString } from \"./providerSnapshot.ts\";\nimport * as NetService from \"@t3tools/shared/Net\";\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nconst encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));\nconst OPENCODE_EMPTY_CONFIG_CONTENT = \"{}\";\n\nconst OPENCODE_SERVER_READY_PREFIX = \"opencode server listening\";\nconst DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 30_000;\nconst DEFAULT_HOSTNAME = \"127.0.0.1\";\nexport interface OpenCodeServerProcess {\n  readonly url: string;\n  readonly exitCode: Effect.Effect<number, never>;\n}\n\nexport interface OpenCodeServerConnection {\n  readonly url: string;\n  readonly exitCode: Effect.Effect<number, never> | null;\n  readonly external: boolean;\n}\n\nconst OPENCODE_RUNTIME_ERROR_TAG = \"OpenCodeRuntimeError\";\nexport class OpenCodeRuntimeError extends Data.TaggedError(OPENCODE_RUNTIME_ERROR_TAG)<{\n  readonly operation: string;\n  readonly cause?: unknown;\n  readonly detail: string;\n}> {\n  static readonly is = (u: unknown): u is OpenCodeRuntimeError =>\n    P.isTagged(u, OPENCODE_RUNTIME_ERROR_TAG);\n}\n\nfunction encodeJsonStringForDiagnostics(input: unknown): string | undefined {\n  const result = encodeUnknownJsonStringExit(input);\n  return Exit.isSuccess(result) ? result.value : undefined;\n}\n\nexport function openCodeRuntimeErrorDetail(cause: unknown): string {\n  if (OpenCodeRuntimeError.is(cause)) return cause.detail;\n  if (cause instanceof Error && cause.message.trim().length > 0) return cause.message.trim();\n  if (cause && typeof cause === \"object\") {\n    // SDK v2 throws { response, request, error? } shapes — extract what's useful\n    const anyCause = cause as Record<string, unknown>;\n    const status = (anyCause.response as { status?: number } | undefined)?.status;\n    const body = anyCause.error ?? anyCause.data ?? anyCause.body;\n    const encodedBody = encodeJsonStringForDiagnostics(body ?? cause);\n    if (encodedBody) {\n      return `status=${status ?? \"?\"} body=${encodedBody}`;\n    }\n  }\n  return String(cause);\n}\n\nexport const runOpenCodeSdk = <A>(\n  operation: string,\n  fn: () => Promise<A>,\n): Effect.Effect<A, OpenCodeRuntimeError> =>\n  Effect.tryPromise({\n    try: fn,\n    catch: (cause) =>\n      new OpenCodeRuntimeError({ operation, detail: openCodeRuntimeErrorDetail(cause), cause }),\n  }).pipe(Effect.withSpan(`opencode.${operation}`));\n\nexport interface OpenCodeCommandResult {\n  readonly stdout: string;\n  readonly stderr: string;\n  readonly code: number;\n}\n\nexport interface OpenCodeInventory {\n  readonly providerList: ProviderListResponse;\n  readonly agents: ReadonlyArray<Agent>;\n}\n\nexport interface ParsedOpenCodeModelSlug {\n  readonly providerID: string;\n  readonly modelID: string;\n}\n\nexport interface OpenCodeRuntimeShape {\n  /**\n   * Spawns a local OpenCode server process. Its lifetime is bound to the caller's\n   * `Scope.Scope` — the child is killed automatically when that scope closes.\n   * Consumers that want a long-lived server must create and hold a scope explicitly\n   * (see {@link Scope.make}) and close it when done.\n   */\n  readonly startOpenCodeServerProcess: (input: {\n    readonly binaryPath: string;\n    readonly environment?: NodeJS.ProcessEnv;\n    readonly port?: number;\n    readonly hostname?: string;\n    readonly timeoutMs?: number;\n  }) => Effect.Effect<OpenCodeServerProcess, OpenCodeRuntimeError, Scope.Scope>;\n  /**\n   * Returns a handle to either an externally-managed OpenCode server (when\n   * `serverUrl` is provided — no lifetime is attached to the caller's scope) or a\n   * freshly spawned local server whose lifetime is bound to the caller's scope.\n   */\n  readonly connectToOpenCodeServer: (input: {\n    readonly binaryPath: string;\n    readonly serverUrl?: string | null;\n    readonly environment?: NodeJS.ProcessEnv;\n    readonly port?: number;\n    readonly hostname?: string;\n    readonly timeoutMs?: number;\n  }) => Effect.Effect<OpenCodeServerConnection, OpenCodeRuntimeError, Scope.Scope>;\n  readonly runOpenCodeCommand: (input: {\n    readonly binaryPath: string;\n    readonly args: ReadonlyArray<string>;\n    readonly environment?: NodeJS.ProcessEnv;\n  }) => Effect.Effect<OpenCodeCommandResult, OpenCodeRuntimeError>;\n  readonly createOpenCodeSdkClient: (input: {\n    readonly baseUrl: string;\n    readonly directory: string;\n    readonly serverPassword?: string;\n  }) => OpencodeClient;\n  readonly loadOpenCodeInventory: (\n    client: OpencodeClient,\n  ) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;\n  readonly loadInventoryFromCli: (input: {\n    readonly binaryPath: string;\n    readonly environment?: NodeJS.ProcessEnv;\n  }) => Effect.Effect<OpenCodeInventory, OpenCodeRuntimeError>;\n}\n\nfunction parseServerUrlFromOutput(output: string): string | null {\n  for (const line of output.split(\"\\n\")) {\n    if (!line.startsWith(OPENCODE_SERVER_READY_PREFIX)) {\n      continue;\n    }\n    const match = line.match(/on\\s+(https?:\\/\\/[^\\s]+)/);\n    return match?.[1] ?? null;\n  }\n  return null;\n}\n\nconst SLUG_LINE_RE = /^(\\S+\\/\\S+)\\s*$/;\nconst AGENT_HEADER_RE = /^(.+)\\s+\\((\\S+)\\)\\s*$/;\n\n// Agents that are always hidden in OpenCode but the CLI \"agent list\" command\n// does not expose the hidden flag. Keep in sync with OpenCode agent\n// definitions (in the OpenCode repo: packages/opencode/src/agent/agent.ts).\nconst KNOWN_HIDDEN_AGENTS = new Set([\"compaction\", \"summary\", \"title\"]);\n\n/** @internal */\nexport function parseModelsCliOutput(stdout: string): {\n  readonly providers: ReadonlyMap<\n    string,\n    { readonly id: string; readonly name: string; readonly models: { [key: string]: Model } }\n  >;\n  readonly connected: ReadonlyArray<string>;\n} {\n  const providers = new Map<\n    string,\n    { id: string; name: string; models: { [key: string]: Model } }\n  >();\n  const lines = stdout.split(\"\\n\");\n  let currentSlug: string | null = null;\n  const jsonLines: Array<string> = [];\n\n  const flushModel = () => {\n    if (currentSlug !== null && jsonLines.length > 0) {\n      const jsonStr = jsonLines.join(\"\\n\").trim();\n      if (jsonStr.length > 0) {\n        try {\n          const model = JSON.parse(jsonStr) as Model;\n          const separator = currentSlug.indexOf(\"/\");\n          if (separator > 0) {\n            const providerID = currentSlug.slice(0, separator);\n            const modelID = currentSlug.slice(separator + 1);\n            let provider = providers.get(providerID);\n            if (!provider) {\n              provider = { id: providerID, name: providerID, models: {} };\n              providers.set(providerID, provider);\n            }\n            provider.models[modelID] = model;\n          }\n        } catch {\n          // Skip unparseable model JSON\n        }\n      }\n    }\n    currentSlug = null;\n    jsonLines.length = 0;\n  };\n\n  for (const line of lines) {\n    const slugMatch = SLUG_LINE_RE.exec(line);\n    if (slugMatch) {\n      flushModel();\n      currentSlug = slugMatch[1]!;\n    } else if (currentSlug !== null) {\n      jsonLines.push(line);\n    }\n  }\n  flushModel();\n\n  return { providers, connected: [...providers.keys()] };\n}\n\n/** @internal */\nexport function parseAgentListCliOutput(stdout: string): ReadonlyArray<Agent> {\n  const agents: Array<Agent> = [];\n  const lines = stdout.split(\"\\n\");\n  let currentHeader: { name: string; mode: string } | null = null;\n  const blockLines: Array<string> = [];\n\n  const flushAgent = () => {\n    if (currentHeader !== null) {\n      const jsonStr = blockLines.join(\"\\n\").trim();\n      if (jsonStr.length > 0) {\n        try {\n          const permission = JSON.parse(jsonStr);\n          agents.push({\n            name: currentHeader.name,\n            mode: currentHeader.mode as Agent[\"mode\"],\n            hidden: KNOWN_HIDDEN_AGENTS.has(currentHeader.name),\n            permission,\n            options: {},\n          });\n        } catch {\n          // Skip unparseable agent\n        }\n      }\n    }\n    currentHeader = null;\n    blockLines.length = 0;\n  };\n\n  for (const line of lines) {\n    const match = AGENT_HEADER_RE.exec(line);\n    if (match) {\n      flushAgent();\n      currentHeader = { name: match[1]!, mode: match[2]! };\n    } else if (currentHeader !== null) {\n      blockLines.push(line);\n    }\n  }\n  flushAgent();\n\n  return agents;\n}\n\nexport function parseOpenCodeModelSlug(\n  slug: string | null | undefined,\n): ParsedOpenCodeModelSlug | null {\n  if (typeof slug !== \"string\") {\n    return null;\n  }\n\n  const trimmed = slug.trim();\n  const separator = trimmed.indexOf(\"/\");\n  if (separator <= 0 || separator === trimmed.length - 1) {\n    return null;\n  }\n\n  return {\n    providerID: trimmed.slice(0, separator),\n    modelID: trimmed.slice(separator + 1),\n  };\n}\n\nexport function openCodeQuestionId(\n  index: number,\n  question: QuestionRequest[\"questions\"][number],\n): string {\n  const header = question.header\n    .trim()\n    .toLowerCase()\n    .replace(/[^a-z0-9_-]+/g, \"-\");\n  return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;\n}\n\nexport function toOpenCodeFileParts(input: {\n  readonly attachments: ReadonlyArray<ChatAttachment> | undefined;\n  readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;\n}): Array<FilePartInput> {\n  const parts: Array<FilePartInput> = [];\n\n  for (const attachment of input.attachments ?? []) {\n    const attachmentPath = input.resolveAttachmentPath(attachment);\n    if (!attachmentPath) {\n      continue;\n    }\n\n    parts.push({\n      type: \"file\",\n      mime: attachment.mimeType,\n      filename: attachment.name,\n      url: NodeURL.pathToFileURL(attachmentPath).href,\n    });\n  }\n\n  return parts;\n}\n\nexport function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {\n  if (runtimeMode === \"full-access\") {\n    return [{ permission: \"*\", pattern: \"*\", action: \"allow\" }];\n  }\n\n  return [\n    { permission: \"*\", pattern: \"*\", action: \"ask\" },\n    { permission: \"bash\", pattern: \"*\", action: \"ask\" },\n    { permission: \"edit\", pattern: \"*\", action: \"ask\" },\n    { permission: \"webfetch\", pattern: \"*\", action: \"ask\" },\n    { permission: \"websearch\", pattern: \"*\", action: \"ask\" },\n    { permission: \"codesearch\", pattern: \"*\", action: \"ask\" },\n    { permission: \"external_directory\", pattern: \"*\", action: \"ask\" },\n    { permission: \"doom_loop\", pattern: \"*\", action: \"ask\" },\n    { permission: \"question\", pattern: \"*\", action: \"allow\" },\n  ];\n}\n\nexport function toOpenCodePermissionReply(\n  decision: ProviderApprovalDecision,\n): \"once\" | \"always\" | \"reject\" {\n  switch (decision) {\n    case \"accept\":\n      return \"once\";\n    case \"acceptForSession\":\n      return \"always\";\n    case \"decline\":\n    case \"cancel\":\n    default:\n      return \"reject\";\n  }\n}\n\nexport function toOpenCodeQuestionAnswers(\n  request: QuestionRequest,\n  answers: Record<string, unknown>,\n): Array<QuestionAnswer> {\n  return request.questions.map((question, index) => {\n    const raw =\n      answers[openCodeQuestionId(index, question)] ??\n      answers[question.header] ??\n      answers[question.question];\n    if (Array.isArray(raw)) {\n      return raw.filter((value): value is string => typeof value === \"string\");\n    }\n    if (typeof raw === \"string\") {\n      return raw.trim().length > 0 ? [raw] : [];\n    }\n    return [];\n  });\n}\n\nfunction ensureRuntimeError(\n  operation: OpenCodeRuntimeError[\"operation\"],\n  detail: string,\n  cause: unknown,\n): OpenCodeRuntimeError {\n  return OpenCodeRuntimeError.is(cause)\n    ? cause\n    : new OpenCodeRuntimeError({ operation, detail, cause });\n}\n\nconst makeOpenCodeRuntime = Effect.gen(function* () {\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const netService = yield* NetService.NetService;\n  const hostPlatform = yield* HostProcessPlatform;\n  const resolveCommand = (command: string, args: ReadonlyArray<string>, env?: NodeJS.ProcessEnv) =>\n    resolveSpawnCommand(command, args, env ? { env } : {});\n\n  const runOpenCodeCommand: OpenCodeRuntimeShape[\"runOpenCodeCommand\"] = (input) =>\n    Effect.gen(function* () {\n      const spawnCommand = yield* resolveCommand(input.binaryPath, input.args, input.environment);\n      const child = yield* spawner.spawn(\n        ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n          shell: spawnCommand.shell,\n          ...(input.environment ? { env: input.environment } : { extendEnv: true }),\n        }),\n      );\n      const [stdout, stderr, code] = yield* Effect.all(\n        [collectStreamAsString(child.stdout), collectStreamAsString(child.stderr), child.exitCode],\n        { concurrency: \"unbounded\" },\n      );\n      const exitCode = Number(code);\n      if (yield* isWindowsCommandNotFound(exitCode, stderr)) {\n        return yield* new OpenCodeRuntimeError({\n          operation: \"runOpenCodeCommand\",\n          detail: `spawn ${input.binaryPath} ENOENT`,\n        });\n      }\n      return {\n        stdout,\n        stderr,\n        code: exitCode,\n      } satisfies OpenCodeCommandResult;\n    }).pipe(\n      Effect.scoped,\n      Effect.mapError((cause) =>\n        ensureRuntimeError(\n          \"runOpenCodeCommand\",\n          `Failed to execute '${input.binaryPath} ${input.args.join(\" \")}': ${openCodeRuntimeErrorDetail(cause)}`,\n          cause,\n        ),\n      ),\n    );\n\n  const startOpenCodeServerProcess: OpenCodeRuntimeShape[\"startOpenCodeServerProcess\"] = (input) =>\n    Effect.gen(function* () {\n      // Bind this server's lifetime to the caller's scope. When the caller's\n      // scope closes, the spawned child is killed and all associated fibers\n      // are interrupted automatically — no `close()` method needed.\n      const runtimeScope = yield* Scope.Scope;\n\n      const hostname = input.hostname ?? DEFAULT_HOSTNAME;\n      const port =\n        input.port ??\n        (yield* netService.findAvailablePort(0).pipe(\n          Effect.mapError(\n            (cause) =>\n              new OpenCodeRuntimeError({\n                operation: \"startOpenCodeServerProcess\",\n                detail: `Failed to find available port: ${openCodeRuntimeErrorDetail(cause)}`,\n                cause,\n              }),\n          ),\n        ));\n      const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;\n      const args = [\"serve\", `--hostname=${hostname}`, `--port=${port}`];\n      const spawnCommand = yield* resolveCommand(input.binaryPath, args, input.environment);\n\n      const child = yield* spawner\n        .spawn(\n          ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n            detached: hostPlatform !== \"win32\",\n            shell: spawnCommand.shell,\n            env: {\n              ...input.environment,\n              OPENCODE_CONFIG_CONTENT: OPENCODE_EMPTY_CONFIG_CONTENT,\n            },\n            extendEnv: input.environment === undefined,\n          }),\n        )\n        .pipe(\n          Effect.provideService(Scope.Scope, runtimeScope),\n          Effect.mapError(\n            (cause) =>\n              new OpenCodeRuntimeError({\n                operation: \"startOpenCodeServerProcess\",\n                detail: `Failed to spawn OpenCode server process: ${openCodeRuntimeErrorDetail(cause)}`,\n                cause,\n              }),\n          ),\n        );\n\n      const killOpenCodeProcessGroup = (signal: NodeJS.Signals) =>\n        hostPlatform === \"win32\"\n          ? child.kill({ killSignal: signal, forceKillAfter: \"1 second\" }).pipe(Effect.asVoid)\n          : Effect.sync(() => {\n              try {\n                process.kill(-Number(child.pid), signal);\n              } catch {\n                // The direct child may already have exited after starting the\n                // server; the process group kill is best-effort cleanup for\n                // any serve process left in that group.\n              }\n            });\n      const terminateChild = killOpenCodeProcessGroup(\"SIGTERM\").pipe(\n        Effect.andThen(Effect.sleep(\"1 second\")),\n        Effect.andThen(killOpenCodeProcessGroup(\"SIGKILL\")),\n        Effect.ignore,\n      );\n      yield* Scope.addFinalizer(runtimeScope, terminateChild);\n\n      const stdoutRef = yield* Ref.make(\"\");\n      const stderrRef = yield* Ref.make(\"\");\n      const readyDeferred = yield* Deferred.make<string, OpenCodeRuntimeError>();\n\n      const setReadyFromStdoutChunk = (chunk: string) =>\n        Ref.updateAndGet(stdoutRef, (stdout) => `${stdout}${chunk}`).pipe(\n          Effect.flatMap((nextStdout) => {\n            const parsed = parseServerUrlFromOutput(nextStdout);\n            return parsed\n              ? Deferred.succeed(readyDeferred, parsed).pipe(Effect.ignore)\n              : Effect.void;\n          }),\n        );\n\n      const stdoutFiber = yield* child.stdout.pipe(\n        Stream.decodeText(),\n        Stream.runForEach(setReadyFromStdoutChunk),\n        Effect.ignore,\n        Effect.forkIn(runtimeScope),\n      );\n      const stderrFiber = yield* child.stderr.pipe(\n        Stream.decodeText(),\n        Stream.runForEach((chunk) => Ref.update(stderrRef, (stderr) => `${stderr}${chunk}`)),\n        Effect.ignore,\n        Effect.forkIn(runtimeScope),\n      );\n\n      const exitFiber = yield* child.exitCode.pipe(\n        Effect.flatMap((code) =>\n          Effect.gen(function* () {\n            const stdout = yield* Ref.get(stdoutRef);\n            const stderr = yield* Ref.get(stderrRef);\n            const exitCode = Number(code);\n            yield* Deferred.fail(\n              readyDeferred,\n              new OpenCodeRuntimeError({\n                operation: \"startOpenCodeServerProcess\",\n                detail: [\n                  `OpenCode server exited before startup completed (code: ${String(exitCode)}).`,\n                  stdout.trim() ? `stdout:\\n${stdout.trim()}` : null,\n                  stderr.trim() ? `stderr:\\n${stderr.trim()}` : null,\n                ]\n                  .filter(Boolean)\n                  .join(\"\\n\\n\"),\n                cause: { exitCode, stdout, stderr },\n              }),\n            ).pipe(Effect.ignore);\n          }),\n        ),\n        Effect.ignore,\n        Effect.forkIn(runtimeScope),\n      );\n\n      const readyExit = yield* Effect.exit(\n        Deferred.await(readyDeferred).pipe(Effect.timeoutOption(timeoutMs)),\n      );\n\n      // Startup-time fibers are no longer needed once ready has resolved (either\n      // way). The exit fiber is only interrupted on failure; on success it keeps\n      // the caller's `exitCode` effect observable until the scope closes.\n      yield* Fiber.interrupt(stdoutFiber).pipe(Effect.ignore);\n      yield* Fiber.interrupt(stderrFiber).pipe(Effect.ignore);\n\n      if (Exit.isFailure(readyExit)) {\n        yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);\n        const squashed = Cause.squash(readyExit.cause);\n        return yield* ensureRuntimeError(\n          \"startOpenCodeServerProcess\",\n          `Failed while waiting for OpenCode server startup: ${openCodeRuntimeErrorDetail(squashed)}`,\n          squashed,\n        );\n      }\n\n      const readyOption = readyExit.value;\n      if (Option.isNone(readyOption)) {\n        yield* Fiber.interrupt(exitFiber).pipe(Effect.ignore);\n        return yield* new OpenCodeRuntimeError({\n          operation: \"startOpenCodeServerProcess\",\n          detail: `Timed out waiting for OpenCode server start after ${timeoutMs}ms.`,\n        });\n      }\n\n      return {\n        url: readyOption.value,\n        exitCode: child.exitCode.pipe(\n          Effect.map(Number),\n          Effect.orElseSucceed(() => 0),\n        ),\n      } satisfies OpenCodeServerProcess;\n    });\n\n  const connectToOpenCodeServer: OpenCodeRuntimeShape[\"connectToOpenCodeServer\"] = (input) => {\n    const serverUrl = input.serverUrl?.trim();\n    if (serverUrl) {\n      // We don't own externally-configured servers — no scope interaction.\n      return Effect.succeed({\n        url: serverUrl,\n        exitCode: null,\n        external: true,\n      });\n    }\n\n    return startOpenCodeServerProcess({\n      binaryPath: input.binaryPath,\n      ...(input.environment !== undefined ? { environment: input.environment } : {}),\n      ...(input.port !== undefined ? { port: input.port } : {}),\n      ...(input.hostname !== undefined ? { hostname: input.hostname } : {}),\n      ...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),\n    }).pipe(\n      Effect.map((server) => ({\n        url: server.url,\n        exitCode: server.exitCode,\n        external: false,\n      })),\n    );\n  };\n\n  const createOpenCodeSdkClient: OpenCodeRuntimeShape[\"createOpenCodeSdkClient\"] = (input) =>\n    createOpencodeClient({\n      baseUrl: input.baseUrl,\n      directory: input.directory,\n      ...(input.serverPassword\n        ? {\n            headers: {\n              Authorization: `Basic ${Buffer.from(`opencode:${input.serverPassword}`, \"utf8\").toString(\"base64\")}`,\n            },\n          }\n        : {}),\n      throwOnError: true,\n    });\n\n  const loadProviders = (client: OpencodeClient) =>\n    runOpenCodeSdk(\"provider.list\", () => client.provider.list()).pipe(\n      Effect.filterMapOrFail(\n        (list) =>\n          list.data\n            ? Result.succeed(list.data)\n            : Result.fail(\n                new OpenCodeRuntimeError({\n                  operation: \"provider.list\",\n                  detail: \"OpenCode provider list was empty.\",\n                }),\n              ),\n        (result) => result,\n      ),\n    );\n\n  const loadAgents = (client: OpencodeClient) =>\n    runOpenCodeSdk(\"app.agents\", () => client.app.agents()).pipe(\n      Effect.map((result) => result.data ?? []),\n    );\n\n  const loadOpenCodeInventory: OpenCodeRuntimeShape[\"loadOpenCodeInventory\"] = (client) =>\n    Effect.all([loadProviders(client), loadAgents(client)], { concurrency: \"unbounded\" }).pipe(\n      Effect.map(([providerList, agents]) => ({ providerList, agents })),\n    );\n\n  const loadInventoryFromCli: OpenCodeRuntimeShape[\"loadInventoryFromCli\"] = (input) =>\n    Effect.gen(function* () {\n      const env = input.environment !== undefined ? { environment: input.environment } : ({} as {});\n\n      const runModelsCli = () =>\n        runOpenCodeCommand({\n          binaryPath: input.binaryPath,\n          args: [\"models\", \"--verbose\"],\n          ...env,\n        }).pipe(Effect.exit);\n      const runAgentsCli = () =>\n        runOpenCodeCommand({ binaryPath: input.binaryPath, args: [\"agent\", \"list\"], ...env }).pipe(\n          Effect.exit,\n        );\n\n      // First attempt — run both in parallel\n      let [modelsResult, agentsResult] = yield* Effect.all([runModelsCli(), runAgentsCli()], {\n        concurrency: \"unbounded\",\n      });\n\n      // Retry once after 1s on transient failures (e.g. SQLite \"database is locked\")\n      const needsModelsRetry = modelsResult._tag === \"Failure\" || modelsResult.value.code !== 0;\n      const needsAgentsRetry = agentsResult._tag === \"Failure\" || agentsResult.value.code !== 0;\n      if (needsModelsRetry || needsAgentsRetry) {\n        yield* Effect.sleep(\"1 second\");\n        const [m2, a2] = yield* Effect.all(\n          [\n            needsModelsRetry ? runModelsCli() : Effect.succeed(modelsResult),\n            needsAgentsRetry ? runAgentsCli() : Effect.succeed(agentsResult),\n          ],\n          { concurrency: \"unbounded\" },\n        );\n        modelsResult = m2;\n        agentsResult = a2;\n      }\n\n      if (modelsResult._tag === \"Failure\") {\n        const cause = Cause.squash(modelsResult.cause);\n        return yield* ensureRuntimeError(\n          \"loadInventoryFromCli\",\n          `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`,\n          cause,\n        );\n      }\n      if (modelsResult.value.code !== 0) {\n        return yield* new OpenCodeRuntimeError({\n          operation: \"loadInventoryFromCli\",\n          detail: `OpenCode models command exited with code ${modelsResult.value.code}.`,\n        });\n      }\n\n      const parsed = parseModelsCliOutput(modelsResult.value.stdout);\n      const connected = [...parsed.connected];\n      const allProviders: ProviderListResponse[\"all\"] = [...parsed.providers.values()].map(\n        (provider) => ({\n          id: provider.id,\n          name: provider.name,\n          source: \"config\" as const,\n          env: [],\n          options: {},\n          models: provider.models,\n        }),\n      );\n\n      // Agent metadata enriches model capabilities but is not required for an\n      // authoritative model inventory, so it may still degrade to an empty list.\n      let agents: ReadonlyArray<Agent> = [];\n      if (agentsResult._tag === \"Success\" && agentsResult.value.code === 0) {\n        agents = parseAgentListCliOutput(agentsResult.value.stdout);\n      }\n\n      return {\n        providerList: { all: allProviders, default: {}, connected },\n        agents,\n      };\n    });\n\n  return {\n    startOpenCodeServerProcess,\n    connectToOpenCodeServer,\n    runOpenCodeCommand,\n    createOpenCodeSdkClient,\n    loadOpenCodeInventory,\n    loadInventoryFromCli,\n  } satisfies OpenCodeRuntimeShape;\n});\n\nexport class OpenCodeRuntime extends Context.Service<OpenCodeRuntime, OpenCodeRuntimeShape>()(\n  \"t3/provider/opencodeRuntime\",\n) {}\n\nexport const OpenCodeRuntimeLive = Layer.effect(OpenCodeRuntime, makeOpenCodeRuntime).pipe(\n  Layer.provide(NetService.layer),\n);\n","import { TextGenerationError } from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\n\nconst isTextGenerationError = Schema.is(TextGenerationError);\n\n/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */\nexport function toJsonSchemaObject(schema: Schema.Top): unknown {\n  const document = Schema.toJsonSchemaDocument(schema);\n  if (document.definitions && Object.keys(document.definitions).length > 0) {\n    return { ...document.schema, $defs: document.definitions };\n  }\n  return document.schema;\n}\n\n/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */\nexport function limitSection(value: string, maxChars: number): string {\n  if (value.length <= maxChars) return value;\n  const truncated = value.slice(0, maxChars);\n  return `${truncated}\\n\\n[truncated]`;\n}\n\n/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */\nexport function sanitizeCommitSubject(raw: string): string {\n  const singleLine = raw.trim().split(/\\r?\\n/g)[0]?.trim() ?? \"\";\n  const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, \"\").trim();\n  if (withoutTrailingPeriod.length === 0) {\n    return \"Update project files\";\n  }\n\n  if (withoutTrailingPeriod.length <= 72) {\n    return withoutTrailingPeriod;\n  }\n  return withoutTrailingPeriod.slice(0, 72).trimEnd();\n}\n\n/** Normalise a raw PR title to a single line with a sensible fallback. */\nexport function sanitizePrTitle(raw: string): string {\n  const singleLine = raw.trim().split(/\\r?\\n/g)[0]?.trim() ?? \"\";\n  if (singleLine.length > 0) {\n    return singleLine;\n  }\n  return \"Update project changes\";\n}\n\n/** Normalise a raw thread title to a compact single-line sidebar-safe label. */\nexport function sanitizeThreadTitle(raw: string): string {\n  const normalized = raw\n    .trim()\n    .split(/\\r?\\n/g)[0]\n    ?.trim()\n    .replace(/^['\"`]+|['\"`]+$/g, \"\")\n    .trim()\n    .replace(/\\s+/g, \" \");\n\n  if (!normalized || normalized.trim().length === 0) {\n    return \"New thread\";\n  }\n\n  if (normalized.length <= 50) {\n    return normalized;\n  }\n\n  return `${normalized.slice(0, 47).trimEnd()}...`;\n}\n\n/** CLI name to human-readable label, e.g. \"codex\" → \"Codex CLI (`codex`)\" */\nfunction cliLabel(cliName: string): string {\n  const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);\n  return `${capitalized} CLI (\\`${cliName}\\`)`;\n}\n\n/**\n * Normalize an unknown error from a CLI text generation process into a\n * typed `TextGenerationError`. Parameterized by CLI name so both Codex\n * and Claude (and future providers) can share the same logic.\n */\nexport function normalizeCliError(\n  cliName: string,\n  operation: string,\n  error: unknown,\n  fallback: string,\n): TextGenerationError {\n  if (isTextGenerationError(error)) {\n    return error;\n  }\n\n  if (error instanceof Error) {\n    const lower = error.message.toLowerCase();\n    if (\n      error.message.includes(`Command not found: ${cliName}`) ||\n      lower.includes(`spawn ${cliName}`) ||\n      lower.includes(\"enoent\")\n    ) {\n      return new TextGenerationError({\n        operation,\n        detail: `${cliLabel(cliName)} is required but not available on PATH.`,\n        cause: error,\n      });\n    }\n    return new TextGenerationError({\n      operation,\n      detail: fallback,\n      cause: error,\n    });\n  }\n\n  return new TextGenerationError({\n    operation,\n    detail: fallback,\n    cause: error,\n  });\n}\n","/**\n * Shared prompt builders for text generation providers.\n *\n * Extracts the prompt construction logic that is identical across\n * Codex, Claude, and any future CLI-based text generation backends.\n *\n * @module textGenerationPrompts\n */\nimport * as Schema from \"effect/Schema\";\nimport type { ChatAttachment } from \"@t3tools/contracts\";\n\nimport { limitSection } from \"./TextGenerationUtils.ts\";\nimport type { TextGenerationPolicy } from \"./TextGenerationPolicy.ts\";\n\nconst EARLIER_CONTENT_TRUNCATION_MARKER = \"[Earlier content truncated]\\n\\n\";\n\nfunction policyInstruction(instruction: string | undefined): ReadonlyArray<string> {\n  const trimmed = instruction?.trim();\n  return trimmed ? [\"\", \"Additional instructions:\", limitSection(trimmed, 4_000)] : [];\n}\n\n// ---------------------------------------------------------------------------\n// Commit message\n// ---------------------------------------------------------------------------\n\nexport interface CommitMessagePromptInput {\n  branch: string | null;\n  stagedSummary: string;\n  stagedPatch: string;\n  includeBranch?: boolean;\n  policy?: TextGenerationPolicy | undefined;\n}\n\nexport function buildCommitMessagePrompt(input: CommitMessagePromptInput) {\n  const wantsBranch = input.includeBranch === true;\n\n  const prompt = [\n    \"You write concise git commit messages.\",\n    wantsBranch\n      ? \"Return a JSON object with keys: subject, body, branch.\"\n      : \"Return a JSON object with keys: subject, body.\",\n    \"Rules:\",\n    \"- subject must be imperative, <= 72 chars, and no trailing period\",\n    \"- body can be empty string or short bullet points\",\n    ...(wantsBranch\n      ? [\"- branch must be a short semantic git branch fragment for this change\"]\n      : []),\n    \"- capture the primary user-visible or developer-visible change\",\n    ...policyInstruction(input.policy?.commitInstructions),\n    \"\",\n    `Branch: ${input.branch ?? \"(detached)\"}`,\n    \"\",\n    \"Staged files:\",\n    limitSection(input.stagedSummary, 6_000),\n    \"\",\n    \"Staged patch:\",\n    limitSection(input.stagedPatch, 40_000),\n  ].join(\"\\n\");\n\n  if (wantsBranch) {\n    return {\n      prompt,\n      outputSchema: Schema.Struct({\n        subject: Schema.String,\n        body: Schema.String,\n        branch: Schema.String,\n      }),\n    };\n  }\n\n  return {\n    prompt,\n    outputSchema: Schema.Struct({\n      subject: Schema.String,\n      body: Schema.String,\n    }),\n  };\n}\n\n// ---------------------------------------------------------------------------\n// Change request content\n// ---------------------------------------------------------------------------\n\nexport interface PrContentPromptInput {\n  baseBranch: string;\n  headBranch: string;\n  commitSummary: string;\n  diffSummary: string;\n  diffPatch: string;\n  changeRequestTemplate?: string | undefined;\n  policy?: TextGenerationPolicy | undefined;\n}\n\nexport function buildPrContentPrompt(input: PrContentPromptInput) {\n  const changeRequestTemplate = input.changeRequestTemplate?.trim();\n  const bodyRules = changeRequestTemplate\n    ? [\n        \"- body must be markdown and follow the repository change request template structure\",\n        \"- fill in the template sections appropriately for this change\",\n        \"- drop HTML comments from the template in the generated body\",\n        \"- keep the template's markdown structure\",\n      ]\n    : [\n        \"- body must be markdown and include headings '## Summary' and '## Testing'\",\n        \"- under Summary, provide short bullet points\",\n        \"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate\",\n      ];\n  const prompt = [\n    \"You write source control change request content.\",\n    \"Return a JSON object with keys: title, body.\",\n    \"Rules:\",\n    \"- title should be concise and specific\",\n    ...bodyRules,\n    ...policyInstruction(input.policy?.changeRequestInstructions),\n    ...(changeRequestTemplate\n      ? [\"\", \"Repository change request template:\", limitSection(changeRequestTemplate, 8_000)]\n      : []),\n    \"\",\n    `Base branch: ${input.baseBranch}`,\n    `Head branch: ${input.headBranch}`,\n    \"\",\n    \"Commits:\",\n    limitSection(input.commitSummary, 12_000),\n    \"\",\n    \"Diff stat:\",\n    limitSection(input.diffSummary, 12_000),\n    \"\",\n    \"Diff patch:\",\n    limitSection(input.diffPatch, 40_000),\n  ].join(\"\\n\");\n\n  const outputSchema = Schema.Struct({\n    title: Schema.String,\n    body: Schema.String,\n  });\n\n  return { prompt, outputSchema };\n}\n\n// ---------------------------------------------------------------------------\n// Branch name\n// ---------------------------------------------------------------------------\n\nexport interface BranchNamePromptInput {\n  message: string;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  policy?: TextGenerationPolicy | undefined;\n}\n\ninterface PromptFromMessageInput {\n  instruction: string;\n  responseShape: string;\n  rules: ReadonlyArray<string>;\n  message: string;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  additionalInstructions?: string | undefined;\n}\n\nfunction buildPromptFromMessage(input: PromptFromMessageInput): string {\n  const attachmentLines = (input.attachments ?? []).map(\n    (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,\n  );\n\n  const promptSections = [\n    input.instruction,\n    input.responseShape,\n    \"Rules:\",\n    ...input.rules.map((rule) => `- ${rule}`),\n    \"\",\n    \"User message:\",\n    limitSection(input.message, 8_000),\n    ...policyInstruction(input.additionalInstructions),\n  ];\n  if (attachmentLines.length > 0) {\n    promptSections.push(\n      \"\",\n      \"Attachment metadata:\",\n      limitSection(attachmentLines.join(\"\\n\"), 4_000),\n    );\n  }\n\n  return promptSections.join(\"\\n\");\n}\n\nexport function buildBranchNamePrompt(input: BranchNamePromptInput) {\n  const prompt = buildPromptFromMessage({\n    instruction: \"You generate concise git branch names.\",\n    responseShape: \"Return a JSON object with key: branch.\",\n    rules: [\n      \"Branch should describe the requested work from the user message.\",\n      \"Keep it short and specific (2-6 words).\",\n      \"Use plain words only, no issue prefixes and no punctuation-heavy text.\",\n      \"If images are attached, use them as primary context for visual/UI issues.\",\n    ],\n    message: input.message,\n    attachments: input.attachments,\n    additionalInstructions: input.policy?.branchInstructions,\n  });\n  const outputSchema = Schema.Struct({\n    branch: Schema.String,\n  });\n\n  return { prompt, outputSchema };\n}\n\n// ---------------------------------------------------------------------------\n// Thread title\n// ---------------------------------------------------------------------------\n\nexport interface ThreadTitlePromptInput {\n  message: string;\n  previousTitle?: string | undefined;\n  attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  policy?: TextGenerationPolicy | undefined;\n}\n\n// Keep shared editorial rules in these two prompts in sync. Regeneration\n// intentionally adds guidance for thread history and the previous title.\nconst INITIAL_THREAD_TITLE_PROMPT = `Generate a title that will help the user recognize this Synaptic Code thread weeks later.\nReturn JSON with exactly one key: title.\n\nBefore answering, silently reduce the request to:\n- Subject: What system, feature, or problem is this really about?\n- Outcome: What does the user ultimately want to understand or change?\n- Incidental instructions: What only describes how the agent should do the work?\n\nTitle the subject and outcome. Discard incidental instructions.\n\nEditorial rules:\n- 3-8 words, fewer than 40 characters.\n- Use a compact noun phrase or clear action phrase.\n- Capture the umbrella goal when the request lists several symptoms or steps.\n- Name the product change, not the mock, plan, report, branch, or PR used to produce it.\n- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.\n- For reviews, name what is being reviewed and the relevant concern. Avoid generic titles such as \"Review PR 123\" when linked or attached context reveals the subject.\n- For research, name the question domain rather than the requested research process.\n- Do not claim the work is complete.\n- Do not copy and truncate the user's message.\n- Avoid project names already visible in the UI, quotes, labels, filler, and trailing punctuation.\n- Use attached images as primary context for UI issues.\n- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.`;\n\nfunction regenerateThreadTitlePrompt(previousTitle: string): string {\n  return `Regenerate the title for an existing Synaptic Code thread so the user can recognize it weeks later.\nThe previous title was ${JSON.stringify(previousTitle)}.\nReturn JSON with exactly one key: title.\n\nDetermine the title in this order:\n1. Read the USER messages first. Identify the latest explicit durable goal. The original subject remains the subject until the user clearly changes what the thread is about.\n2. Use ASSISTANT messages to resolve vague links, unnamed code, and discovered product nouns. Do not promote one assistant finding into the thread subject unless the user adopts it as a new goal.\n3. Compare that subject with the previous title. Preserve accurate scope words, especially when earlier content is truncated. Replace the previous title when it is generic, artifact-based, a completion update, or contradicted by the thread.\n4. Title the durable subject and desired outcome, not the current workflow state.\n\nEditorial rules:\n- 3-8 words, fewer than 40 characters.\n- Use a compact noun phrase or clear action phrase.\n- Preserve the umbrella subject when later messages focus on one finding, provider, platform, or implementation detail.\n- A thread progressing through research, planning, implementation, review, CI, merge, and monitoring has usually not changed subjects.\n- Ignore deliverables and operations such as mocks, plans, HTML, branches, PRs, tests, CI, commits, merging, and monitoring unless they are the actual topic.\n- Models, subagents, tools, output formats, and monitoring instructions do not belong in the title unless they are themselves the topic.\n- Treat final operational follow-ups and assistant completion summaries as weak evidence of subject.\n- For reviews, name the reviewed feature or system and its durable concern, not one finding from the review.\n- For research, name the question domain rather than the research process.\n- Do not claim the work is complete.\n- Do not copy and truncate a thread message.\n- Avoid project names already visible in the UI, PR numbers, quotes, labels, filler, and trailing punctuation.\n- Use attached images as primary context for UI issues.\n- When a URL or attachment is the only source of the subject, use available tools to inspect it. If it cannot be resolved, remain accurate rather than guessing.\n- Return a meaningfully improved title, not a cosmetic paraphrase of the previous title.\n\nExamples of the distinction:\n- A subagent-monitoring review that finds a Codex roster bug remains \"Review Subagent Monitoring Risks,\" not \"Codex Roster Bug Review.\"\n- A vague failing-test request later identified as a lazy thread-feed mismatch becomes \"Fix Lazy Thread Feed Test,\" not \"Prevent Mobile Feed Regressions.\"\n- A QR-sharing overhaul that ends with CI and merge work remains about QR sharing, not the PR lifecycle.`;\n}\n\nfunction preserveMessageEnd(message: string): string {\n  const alreadyTruncated = message.startsWith(EARLIER_CONTENT_TRUNCATION_MARKER);\n  const contents = alreadyTruncated\n    ? message.slice(EARLIER_CONTENT_TRUNCATION_MARKER.length)\n    : message;\n  if (!alreadyTruncated && contents.length <= 8_000) {\n    return contents;\n  }\n  return `${EARLIER_CONTENT_TRUNCATION_MARKER}${contents.slice(-8_000)}`;\n}\n\nfunction threadTitlePromptSuffix(input: ThreadTitlePromptInput): string {\n  const additionalInstructions = policyInstruction(input.policy?.threadTitleInstructions);\n  const attachmentLines = (input.attachments ?? []).map(\n    (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,\n  );\n\n  let suffix = \"\";\n  if (additionalInstructions.length > 0) {\n    suffix = `\\n${additionalInstructions.join(\"\\n\")}`;\n  }\n  if (attachmentLines.length > 0) {\n    suffix += `\\n\\nAttachment metadata:\\n${limitSection(attachmentLines.join(\"\\n\"), 4_000)}`;\n  }\n  return suffix;\n}\n\nexport function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {\n  let prompt: string;\n  if (input.previousTitle === undefined) {\n    const message = limitSection(input.message, 8_000);\n    prompt = `${INITIAL_THREAD_TITLE_PROMPT}\\n\\nUser message:\\n${message}${threadTitlePromptSuffix(input)}`;\n  } else {\n    const message = preserveMessageEnd(input.message);\n    prompt = `${regenerateThreadTitlePrompt(input.previousTitle)}\\n\\nThread contents:\\n${message}${threadTitlePromptSuffix(input)}`;\n  }\n  const outputSchema = Schema.Struct({\n    title: Schema.String,\n  });\n\n  return { prompt, outputSchema };\n}\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFS from \"node:fs\";\nimport * as NodePath from \"node:path\";\n\nimport { HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport { SpawnExecutableResolution } from \"@t3tools/shared/shell\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\n\n/**\n * Windows launcher-script extensions that Node cannot spawn without a shell\n * (`spawn EINVAL` since Node 20.12) and that the Claude Agent SDK therefore\n * cannot use as `pathToClaudeCodeExecutable`.\n */\nconst WINDOWS_SHIM_EXTENSIONS: ReadonlySet<string> = new Set([\".cmd\", \".bat\", \".ps1\"]);\n\n/**\n * Entry points of the npm `@anthropic-ai/claude-code` package relative to the\n * global `node_modules` directory that sits next to the npm launcher shim.\n * Newer package versions ship a native `bin/claude.exe`; older versions only\n * ship `cli.js`, which the SDK runs with a JavaScript runtime.\n */\nconst NPM_PACKAGE_ENTRY_CANDIDATES = [\n  [\"node_modules\", \"@anthropic-ai\", \"claude-code\", \"bin\", \"claude.exe\"],\n  [\"node_modules\", \"@anthropic-ai\", \"claude-code\", \"cli.js\"],\n] as const;\n\nexport type ExecutableFileCheck = (filePath: string) => boolean;\n\nfunction isExistingFile(filePath: string): boolean {\n  try {\n    return NodeFS.statSync(filePath).isFile();\n  } catch {\n    return false;\n  }\n}\n\n/** Injectable file-existence check so tests can run against a fake filesystem. */\nexport const ClaudeExecutableFileCheck = Context.Reference<ExecutableFileCheck>(\n  \"server/provider/Drivers/ClaudeExecutableFileCheck\",\n  {\n    defaultValue: () => isExistingFile,\n  },\n);\n\n/**\n * Resolves the configured Claude binary path into a value the Claude Agent\n * SDK can spawn directly via `pathToClaudeCodeExecutable`.\n *\n * The SDK spawns the given path without a shell and without Windows PATH /\n * PATHEXT resolution, so a bare command name like `claude` fails with\n * \"native binary not found\" and an npm `claude.cmd` shim fails with\n * `spawn EINVAL`. CLI probes avoid this via `resolveSpawnCommand`, which can\n * fall back to `shell: true`; the SDK offers no such escape hatch.\n *\n * On Windows this resolves the command against PATH/PATHEXT and, when the\n * result is an npm launcher shim, follows it to the real package entry\n * (`bin/claude.exe`, or `cli.js` for older package versions). On other\n * platforms the configured value is returned unchanged.\n */\nexport const resolveClaudeSdkExecutablePath = Effect.fn(\"resolveClaudeSdkExecutablePath\")(\n  function* (binaryPath: string, environment: NodeJS.ProcessEnv): Effect.fn.Return<string> {\n    const platform = yield* HostProcessPlatform;\n    if (platform !== \"win32\") {\n      return binaryPath;\n    }\n\n    const resolveExecutable = yield* SpawnExecutableResolution;\n    const isFile = yield* ClaudeExecutableFileCheck;\n    const resolved = resolveExecutable(binaryPath, platform, environment) ?? binaryPath;\n    const extension = NodePath.win32.extname(resolved).toLowerCase();\n    if (!WINDOWS_SHIM_EXTENSIONS.has(extension)) {\n      return resolved;\n    }\n\n    const shimDirectory = NodePath.win32.dirname(resolved);\n    for (const entrySegments of NPM_PACKAGE_ENTRY_CANDIDATES) {\n      const candidate = NodePath.win32.join(shimDirectory, ...entrySegments);\n      if (isFile(candidate)) {\n        return candidate;\n      }\n    }\n\n    yield* Effect.logWarning(\n      \"Claude launcher shim resolved but no known package entry was found next to it; the Claude Agent SDK cannot spawn launcher scripts directly.\",\n      { binaryPath, resolvedShimPath: resolved },\n    );\n    return binaryPath;\n  },\n);\n","/**\n * ClaudeSkills — filesystem discovery of Claude Code skills for the `$` picker.\n *\n * Claude Code loads skills from `<config dir>/skills` (user scope) and\n * `<cwd>/.claude/skills` (project scope), one directory per skill with a\n * `SKILL.md` carrying YAML frontmatter. The Agent SDK init handshake surfaces\n * skills only as slash commands without their filesystem paths, so the\n * provider snapshot scans the same locations directly, mirroring how the\n * Codex app-server reports its skills.\n *\n * @module provider/Drivers/ClaudeSkills\n */\nimport * as NodeOS from \"node:os\";\n\nimport type { ClaudeSettings, ServerProviderSkill } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { parse as parseYamlDocument } from \"yaml\";\n\nimport { expandHomePath } from \"../../pathExpansion.ts\";\n\ntype ClaudeSkillScope = \"user\" | \"project\";\n\nconst FRONTMATTER_PATTERN = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---(?:\\r?\\n|$)/;\n\ntype SkillFrontmatter =\n  | { readonly kind: \"missing\" }\n  | { readonly kind: \"malformed\" }\n  | { readonly kind: \"parsed\"; readonly name?: string; readonly description?: string };\n\nfunction parseSkillFrontmatter(contents: string): SkillFrontmatter {\n  const match = FRONTMATTER_PATTERN.exec(contents);\n  if (!match) {\n    return { kind: \"missing\" };\n  }\n\n  let parsed: unknown;\n  try {\n    parsed = parseYamlDocument(match[1] ?? \"\");\n  } catch {\n    return { kind: \"malformed\" };\n  }\n  if (typeof parsed !== \"object\" || parsed === null) {\n    return { kind: \"malformed\" };\n  }\n\n  const record = parsed as Record<string, unknown>;\n  const name = typeof record.name === \"string\" ? record.name.trim() : \"\";\n  const description = typeof record.description === \"string\" ? record.description.trim() : \"\";\n  return {\n    kind: \"parsed\",\n    ...(name ? { name } : {}),\n    ...(description ? { description } : {}),\n  };\n}\n\n/**\n * Resolve the Claude config directory the CLI would use, matching the\n * precedence the spawned CLI sees: the instance's `homePath` (exported as\n * `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`\n * already present in the process environment, then `~/.claude`.\n */\nconst resolveClaudeConfigDirPath = Effect.fn(\"resolveClaudeConfigDirPath\")(function* (\n  config: Pick<ClaudeSettings, \"homePath\">,\n  environment: NodeJS.ProcessEnv,\n  cwd?: string,\n): Effect.fn.Return<string, never, Path.Path> {\n  const path = yield* Path.Path;\n  const homePath = config.homePath.trim();\n  if (homePath.length > 0) {\n    return path.resolve(expandHomePath(homePath));\n  }\n  // No tilde expansion here: the spawned CLI receives this env var verbatim\n  // (env vars are never shell-expanded), so a literal `~` must stay literal\n  // for discovery to scan the same directory the runtime would. A relative\n  // value is resolved against the workspace cwd — the subprocess's own cwd —\n  // for the same reason.\n  const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? \"\";\n  if (environmentConfigDir.length > 0) {\n    return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);\n  }\n  return path.join(NodeOS.homedir(), \".claude\");\n});\n\n/**\n * Enumerate Claude Code skills from the user config dir and the workspace.\n * Discovery is best-effort: unreadable roots and malformed skill entries are\n * skipped so a broken skill never degrades the provider snapshot. On name\n * collisions the project-scoped skill wins, matching Claude Code's\n * most-specific-wins resolution.\n */\nexport const discoverClaudeSkills = Effect.fn(\"discoverClaudeSkills\")(function* (\n  config: Pick<ClaudeSettings, \"homePath\">,\n  cwd?: string,\n  environment?: NodeJS.ProcessEnv,\n): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);\n\n  const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [\n    { directory: path.join(configDirPath, \"skills\"), scope: \"user\" },\n    ...(cwd ? [{ directory: path.join(cwd, \".claude\", \"skills\"), scope: \"project\" as const }] : []),\n  ];\n\n  const skillsByName = new Map<string, ServerProviderSkill>();\n  for (const root of roots) {\n    const entries = yield* fileSystem\n      .readDirectory(root.directory)\n      .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));\n\n    for (const entry of [...entries].sort()) {\n      const skillPath = path.join(root.directory, entry, \"SKILL.md\");\n      const contents = yield* fileSystem\n        .readFileString(skillPath)\n        .pipe(Effect.orElseSucceed(() => undefined));\n      if (contents === undefined) {\n        continue;\n      }\n\n      const frontmatter = parseSkillFrontmatter(contents);\n      // Malformed frontmatter means the skill won't load in Claude Code\n      // either — skip it rather than surfacing a broken entry under its\n      // directory name.\n      if (frontmatter.kind === \"malformed\") {\n        continue;\n      }\n\n      const name = (frontmatter.kind === \"parsed\" ? frontmatter.name : undefined) ?? entry.trim();\n      if (!name) {\n        continue;\n      }\n\n      skillsByName.set(name, {\n        name,\n        path: skillPath,\n        enabled: true,\n        scope: root.scope,\n        ...(frontmatter.kind === \"parsed\" && frontmatter.description\n          ? { description: frontmatter.description }\n          : {}),\n      });\n    }\n  }\n\n  return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));\n});\n","import {\n  type ClaudeSettings,\n  type ModelCapabilities,\n  type ModelSelection,\n  type ServerProviderModel,\n  type ServerProviderSlashCommand,\n} from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Result from \"effect/Result\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport {\n  createModelCapabilities,\n  getModelSelectionStringOptionValue,\n  getProviderOptionCurrentValue,\n  getProviderOptionDescriptors,\n} from \"@t3tools/shared/model\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport { compareSemverVersions } from \"@t3tools/shared/semver\";\nimport {\n  query as claudeQuery,\n  type Options as ClaudeQueryOptions,\n  type SlashCommand as ClaudeSlashCommand,\n  type SDKUserMessage,\n  type SettingSource,\n} from \"@anthropic-ai/claude-agent-sdk\";\n\nimport {\n  buildBooleanOptionDescriptor,\n  buildSelectOptionDescriptor,\n  buildServerProvider,\n  DEFAULT_TIMEOUT_MS,\n  isCommandMissingCause,\n  parseGenericCliVersion,\n  providerModelsFromSettings,\n  spawnAndCollect,\n  type ServerProviderDraft,\n} from \"../providerSnapshot.ts\";\nimport { resolveClaudeSdkExecutablePath } from \"../Drivers/ClaudeExecutable.ts\";\nimport { makeClaudeEnvironment } from \"../Drivers/ClaudeHome.ts\";\nimport { discoverClaudeSkills } from \"../Drivers/ClaudeSkills.ts\";\n\nconst DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({\n  optionDescriptors: [],\n});\n\nconst CLAUDE_PRESENTATION = {\n  displayName: \"Claude\",\n  showInteractionModeToggle: true,\n} as const;\nconst MINIMUM_CLAUDE_OPUS_5_VERSION = \"2.1.219\";\nconst MINIMUM_CLAUDE_FABLE_5_VERSION = \"2.1.169\";\nconst MINIMUM_CLAUDE_OPUS_4_8_VERSION = \"2.1.154\";\nconst MINIMUM_CLAUDE_OPUS_4_7_VERSION = \"2.1.111\";\n\nconst CURRENT_CLAUDE_MODELS = new Set([\"claude-fable-5\", \"claude-opus-5\", \"claude-sonnet-5\"]);\n\nexport function isLegacyClaudeModel(model: string): boolean {\n  return !CURRENT_CLAUDE_MODELS.has(model);\n}\n\nconst CLAUDE_MODEL_CATALOG: ReadonlyArray<ServerProviderModel> = [\n  {\n    slug: \"claude-fable-5\",\n    name: \"Claude Fable 5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"xhigh\", label: \"Extra High\" },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultracode\", label: \"Ultracode\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          options: [\n            { value: \"200k\", label: \"200k\" },\n            { value: \"1m\", label: \"1M\", isDefault: true },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-5\",\n    name: \"Claude Opus 5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"xhigh\", label: \"Extra High\" },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultracode\", label: \"Ultracode\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          // Claude Code selects the 1M variant explicitly (`claude-opus-5[1m]`).\n          options: [\n            { value: \"200k\", label: \"200k\" },\n            { value: \"1m\", label: \"1M\", isDefault: true },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-4-8\",\n    name: \"Claude Opus 4.8\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"xhigh\", label: \"Extra High\" },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultracode\", label: \"Ultracode\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-4-7\",\n    name: \"Claude Opus 4.7\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\" },\n            { value: \"xhigh\", label: \"Extra High\", isDefault: true },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-4-6\",\n    name: \"Claude Opus 4.6\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          options: [\n            { value: \"200k\", label: \"200k\" },\n            { value: \"1m\", label: \"1M\", isDefault: true },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-opus-4-5\",\n    name: \"Claude Opus 4.5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"max\", label: \"Max\" },\n          ],\n        }),\n        buildBooleanOptionDescriptor({\n          id: \"fastMode\",\n          label: \"Fast Mode\",\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-sonnet-5\",\n    name: \"Claude Sonnet 5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"xhigh\", label: \"Extra High\" },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          // Sonnet is 200k-default in Claude Code (1M is opt-in there too).\n          options: [\n            { value: \"200k\", label: \"200k\", isDefault: true },\n            { value: \"1m\", label: \"1M\" },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-sonnet-4-6\",\n    name: \"Claude Sonnet 4.6\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildSelectOptionDescriptor({\n          id: \"effort\",\n          label: \"Reasoning\",\n          options: [\n            { value: \"low\", label: \"Low\" },\n            { value: \"medium\", label: \"Medium\" },\n            { value: \"high\", label: \"High\", isDefault: true },\n            { value: \"max\", label: \"Max\" },\n            { value: \"ultrathink\", label: \"Ultrathink\" },\n          ],\n          promptInjectedValues: [\"ultrathink\"],\n        }),\n        buildSelectOptionDescriptor({\n          id: \"contextWindow\",\n          label: \"Context Window\",\n          // Sonnet is 200k-default in Claude Code (1M is opt-in there too).\n          options: [\n            { value: \"200k\", label: \"200k\", isDefault: true },\n            { value: \"1m\", label: \"1M\" },\n          ],\n        }),\n      ],\n    }),\n  },\n  {\n    slug: \"claude-haiku-4-5\",\n    name: \"Claude Haiku 4.5\",\n    isCustom: false,\n    capabilities: createModelCapabilities({\n      optionDescriptors: [\n        buildBooleanOptionDescriptor({\n          id: \"thinking\",\n          label: \"Thinking\",\n        }),\n      ],\n    }),\n  },\n];\n\nconst BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = CLAUDE_MODEL_CATALOG.map((model) =>\n  isLegacyClaudeModel(model.slug) ? { ...model, isLegacy: true } : model,\n);\n\nfunction supportsClaudeOpus5(version: string | null | undefined): boolean {\n  return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_5_VERSION) >= 0 : false;\n}\n\nfunction supportsClaudeFable5(version: string | null | undefined): boolean {\n  return version ? compareSemverVersions(version, MINIMUM_CLAUDE_FABLE_5_VERSION) >= 0 : false;\n}\n\nfunction supportsClaudeOpus48(version: string | null | undefined): boolean {\n  return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_8_VERSION) >= 0 : false;\n}\n\nfunction supportsClaudeOpus47(version: string | null | undefined): boolean {\n  return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;\n}\n\nfunction getBuiltInClaudeModelsForVersion(\n  version: string | null | undefined,\n): ReadonlyArray<ServerProviderModel> {\n  return BUILT_IN_MODELS.filter((model) => {\n    if (model.slug === \"claude-opus-5\") {\n      return supportsClaudeOpus5(version);\n    }\n    if (model.slug === \"claude-fable-5\") {\n      return supportsClaudeFable5(version);\n    }\n    if (model.slug === \"claude-opus-4-8\") {\n      return supportsClaudeOpus48(version);\n    }\n    if (model.slug === \"claude-opus-4-7\") {\n      return supportsClaudeOpus47(version);\n    }\n    return true;\n  });\n}\n\nfunction formatClaudeOpus5UpgradeMessage(version: string | null): string {\n  const versionLabel = version ? `v${version}` : \"the installed version\";\n  return `Claude Code ${versionLabel} is too old for Claude Opus 5. Upgrade to v${MINIMUM_CLAUDE_OPUS_5_VERSION} or newer to access it.`;\n}\n\nfunction formatClaudeFable5UpgradeMessage(version: string | null): string {\n  const versionLabel = version ? `v${version}` : \"the installed version\";\n  return `Claude Code ${versionLabel} is too old for Claude Fable 5. Upgrade to v${MINIMUM_CLAUDE_FABLE_5_VERSION} or newer to access it.`;\n}\n\nfunction formatClaudeOpus48UpgradeMessage(version: string | null): string {\n  const versionLabel = version ? `v${version}` : \"the installed version\";\n  return `Claude Code ${versionLabel} is too old for Claude Opus 4.8. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_8_VERSION} or newer to access it.`;\n}\n\nfunction formatClaudeOpus47UpgradeMessage(version: string | null): string {\n  const versionLabel = version ? `v${version}` : \"the installed version\";\n  return `Claude Code ${versionLabel} is too old for Claude Opus 4.7. Upgrade to v${MINIMUM_CLAUDE_OPUS_4_7_VERSION} or newer to access it.`;\n}\n\nexport function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {\n  const slug = model?.trim();\n  return (\n    BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??\n    DEFAULT_CLAUDE_MODEL_CAPABILITIES\n  );\n}\n\nexport function resolveClaudeEffort(\n  caps: ModelCapabilities,\n  raw: string | null | undefined,\n): string | undefined {\n  const descriptors = getProviderOptionDescriptors({\n    caps,\n    ...(raw ? { selections: [{ id: \"effort\", value: raw }] } : {}),\n  });\n  const effortDescriptor = descriptors.find((descriptor) => descriptor.id === \"effort\");\n  const value = getProviderOptionCurrentValue(effortDescriptor);\n  return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Normalize a resolved Claude effort value into one suitable for the Claude\n * CLI's `--effort` flag.\n *\n * Mirrors the mapping used when invoking the Claude Agent SDK\n * ({@link getEffectiveClaudeAgentEffort} in ClaudeAdapter): `ultracode` is a\n * Claude Code setting that pairs with `xhigh`, `ultrathink` is filtered out\n * because it is a prompt-prefix mode, and older model compatibility mappings\n * are preserved for current Claude Code behavior.\n */\nexport function normalizeClaudeCliEffort(\n  effort: string | null | undefined,\n  model: string | null | undefined,\n): string | undefined {\n  if (!effort || effort === \"ultrathink\") {\n    return undefined;\n  }\n  if (effort === \"ultracode\") {\n    return \"xhigh\";\n  }\n  if (\n    effort === \"xhigh\" &&\n    model !== \"claude-fable-5\" &&\n    model !== \"claude-opus-5\" &&\n    model !== \"claude-opus-4-8\" &&\n    model !== \"claude-sonnet-5\"\n  ) {\n    return \"max\";\n  }\n  if (effort === \"max\" && model === \"claude-sonnet-4-6\") {\n    return \"high\";\n  }\n  return effort;\n}\n\nexport function isClaudeUltracodeEffort(effort: string | null | undefined): boolean {\n  return effort === \"ultracode\";\n}\n\nexport function resolveClaudeContextWindow(\n  modelSelection: ModelSelection | undefined,\n): string | undefined {\n  const caps = getClaudeModelCapabilities(modelSelection?.model);\n  const raw = getModelSelectionStringOptionValue(modelSelection, \"contextWindow\");\n  const descriptors = getProviderOptionDescriptors({\n    caps,\n    ...(raw ? { selections: [{ id: \"contextWindow\", value: raw }] } : {}),\n  });\n  const descriptor = descriptors.find((candidate) => candidate.id === \"contextWindow\");\n  const value = getProviderOptionCurrentValue(descriptor);\n  return typeof value === \"string\" ? value : undefined;\n}\n\nexport function resolveClaudeApiModelId(modelSelection: ModelSelection): string {\n  switch (resolveClaudeContextWindow(modelSelection)) {\n    case \"1m\":\n      return `${modelSelection.model}[1m]`;\n    default:\n      return modelSelection.model;\n  }\n}\n\nfunction toTitleCaseWords(value: string): string {\n  const parts: Array<string> = [];\n  for (const part of value.split(/[\\s_-]+/g)) {\n    if (part.length > 0) {\n      parts.push(part[0]!.toUpperCase() + part.slice(1).toLowerCase());\n    }\n  }\n  return parts.join(\" \");\n}\n\nfunction claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {\n  const normalized = subscriptionType?.toLowerCase().replace(/[\\s_-]+/g, \"\");\n  if (!normalized) return undefined;\n\n  switch (normalized) {\n    case \"claudemaxsubscription\":\n      return \"Max\";\n    case \"claudemax5xsubscription\":\n      return \"Max 5x\";\n    case \"claudemax20xsubscription\":\n      return \"Max 20x\";\n    case \"claudeenterprisesubscription\":\n      return \"Enterprise\";\n    case \"claudeteamsubscription\":\n      return \"Team\";\n    case \"claudeprosubscription\":\n      return \"Pro\";\n    case \"claudefreesubscription\":\n      return \"Free\";\n    case \"max\":\n    case \"maxplan\":\n      return \"Max\";\n    case \"max5\":\n      return \"Max 5x\";\n    case \"max20\":\n      return \"Max 20x\";\n    case \"enterprise\":\n      return \"Enterprise\";\n    case \"team\":\n      return \"Team\";\n    case \"pro\":\n      return \"Pro\";\n    case \"free\":\n      return \"Free\";\n    default:\n      return toTitleCaseWords(subscriptionType!);\n  }\n}\n\nfunction normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {\n  const normalized = authMethod?.toLowerCase().replace(/[\\s_-]+/g, \"\");\n  if (!normalized) return undefined;\n  if (\n    normalized === \"apikey\" ||\n    normalized === \"anthropicapikey\" ||\n    normalized === \"anthropicauthtoken\"\n  ) {\n    return \"apiKey\";\n  }\n  return undefined;\n}\n\nfunction formatClaudeSubscriptionAuthLabel(subscriptionType: string): string {\n  const subscriptionLabel =\n    claudeSubscriptionLabel(subscriptionType) ?? toTitleCaseWords(subscriptionType);\n  const normalized = subscriptionLabel.toLowerCase().replace(/[\\s_-]+/g, \"\");\n\n  if (normalized.startsWith(\"claude\") && normalized.endsWith(\"subscription\")) {\n    return subscriptionLabel;\n  }\n  if (normalized.startsWith(\"claude\")) {\n    return `${subscriptionLabel} Subscription`;\n  }\n  if (normalized.endsWith(\"subscription\")) {\n    return `Claude ${subscriptionLabel}`;\n  }\n  return `Claude ${subscriptionLabel} Subscription`;\n}\n\nfunction claudeAuthMetadata(input: {\n  readonly subscriptionType: string | undefined;\n  readonly authMethod: string | undefined;\n}): { readonly type: string; readonly label: string } | undefined {\n  if (normalizeClaudeAuthMethod(input.authMethod) === \"apiKey\") {\n    return {\n      type: \"apiKey\",\n      label: \"Claude API Key\",\n    };\n  }\n\n  if (input.subscriptionType) {\n    return {\n      type: input.subscriptionType,\n      label: formatClaudeSubscriptionAuthLabel(input.subscriptionType),\n    };\n  }\n\n  return undefined;\n}\n\nfunction apiProviderAuthMetadata(\n  apiProvider: string | undefined,\n): { readonly type: string; readonly label: string } | undefined {\n  return apiProvider === \"bedrock\" ? { type: \"bedrock\", label: \"Amazon Bedrock\" } : undefined;\n}\n\n// ── SDK capability probe ────────────────────────────────────────────\n\n// Amazon Bedrock initializes far slower than first-party auth: the SDK boots the\n// Bedrock backend and runs the `awsAuthRefresh` credential hook before returning\n// account info. The previous 8s budget expired mid-init, so the probe returned\n// `undefined` and left the provider unverified and unselectable in the picker.\nconst CAPABILITIES_PROBE_TIMEOUT_MS = 25_000;\n\n/**\n * Keep workspace-scoped command discovery intact while isolating the periodic\n * health check from configured MCP servers.\n */\nexport const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [\n  \"user\",\n  \"project\",\n  \"local\",\n] as const satisfies ReadonlyArray<SettingSource>;\n\n/** Build the exact SDK options used by the periodic Claude capability probe. */\nexport function buildClaudeCapabilitiesProbeQueryOptions(input: {\n  readonly executablePath: string;\n  readonly abortController: AbortController;\n  readonly environment: NodeJS.ProcessEnv;\n  readonly cwd: string | undefined;\n}): ClaudeQueryOptions {\n  return {\n    persistSession: false,\n    pathToClaudeCodeExecutable: input.executablePath,\n    abortController: input.abortController,\n    settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES],\n    allowedTools: [],\n    // Ignore MCP definitions from every filesystem setting source above. The\n    // SDK combines this empty explicit map with --strict-mcp-config.\n    mcpServers: {},\n    strictMcpConfig: true,\n    env: {\n      ...input.environment,\n      // Connected claude.ai MCP servers are discovered outside filesystem\n      // config; disable them independently for this health check.\n      ENABLE_CLAUDEAI_MCP_SERVERS: \"false\",\n    },\n    ...(input.cwd ? { cwd: input.cwd } : {}),\n    stderr: () => {},\n  };\n}\n\nfunction nonEmptyProbeString(value: string): string | undefined {\n  const candidate = value.trim();\n  return candidate ? candidate : undefined;\n}\n\ntype ClaudeCapabilitiesProbe = {\n  readonly email: string | undefined;\n  readonly subscriptionType: string | undefined;\n  readonly tokenSource: string | undefined;\n  /**\n   * Active API backend reported by the SDK's `AccountInfo`. Anthropic OAuth\n   * login only applies when `\"firstParty\"`; for Amazon Bedrock (`\"bedrock\"`)\n   * the subscription/token fields are absent and auth is external AWS creds.\n   */\n  readonly apiProvider: string | undefined;\n  readonly slashCommands: ReadonlyArray<ServerProviderSlashCommand>;\n};\n\nfunction parseClaudeInitializationCommands(\n  commands: ReadonlyArray<ClaudeSlashCommand> | undefined,\n): ReadonlyArray<ServerProviderSlashCommand> {\n  return dedupeSlashCommands(\n    (commands ?? []).flatMap((command) => {\n      const name = nonEmptyProbeString(command.name);\n      if (!name) {\n        return [];\n      }\n\n      const description = nonEmptyProbeString(command.description);\n      const argumentHint = nonEmptyProbeString(command.argumentHint);\n\n      return [\n        {\n          name,\n          ...(description ? { description } : {}),\n          ...(argumentHint ? { input: { hint: argumentHint } } : {}),\n        } satisfies ServerProviderSlashCommand,\n      ];\n    }),\n  );\n}\n\nfunction dedupeSlashCommands(\n  commands: ReadonlyArray<ServerProviderSlashCommand>,\n): ReadonlyArray<ServerProviderSlashCommand> {\n  const commandsByName = new Map<string, ServerProviderSlashCommand>();\n\n  for (const command of commands) {\n    const name = nonEmptyProbeString(command.name);\n    if (!name) {\n      continue;\n    }\n\n    const key = name.toLowerCase();\n    const existing = commandsByName.get(key);\n    if (!existing) {\n      commandsByName.set(key, {\n        ...command,\n        name,\n      });\n      continue;\n    }\n\n    commandsByName.set(key, {\n      ...existing,\n      ...(existing.description\n        ? {}\n        : command.description\n          ? { description: command.description }\n          : {}),\n      ...(existing.input?.hint\n        ? {}\n        : command.input?.hint\n          ? { input: { hint: command.input.hint } }\n          : {}),\n    });\n  }\n\n  return [...commandsByName.values()];\n}\n\nfunction waitForAbortSignal(signal: AbortSignal): Promise<void> {\n  if (signal.aborted) {\n    return Promise.resolve();\n  }\n  return new Promise((resolve) => {\n    signal.addEventListener(\"abort\", () => resolve(), { once: true });\n  });\n}\n\n/**\n * Probe account information by spawning a lightweight Claude Agent SDK\n * session and reading the initialization result.\n *\n * We pass a never-yielding AsyncIterable as the prompt so that no user\n * message is ever written to the subprocess stdin. This means the Claude\n * Code subprocess completes its local initialization IPC (returning\n * account info and slash commands) but never starts an API request to\n * Anthropic. We read the init data and then abort the subprocess.\n *\n * This is used as a fallback when `claude auth status` does not include\n * subscription type information.\n */\nconst probeClaudeCapabilities = (\n  claudeSettings: ClaudeSettings,\n  environment?: NodeJS.ProcessEnv,\n  cwd?: string,\n) => {\n  const abort = new AbortController();\n  return Effect.gen(function* () {\n    const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);\n    const executablePath = yield* resolveClaudeSdkExecutablePath(\n      claudeSettings.binaryPath,\n      claudeEnvironment,\n    );\n    return yield* Effect.tryPromise(async () => {\n      const q = claudeQuery({\n        // Never yield — we only need initialization data, not a conversation.\n        // This prevents any prompt from reaching the Anthropic API.\n        // oxlint-disable-next-line require-yield\n        prompt: (async function* (): AsyncGenerator<SDKUserMessage> {\n          await waitForAbortSignal(abort.signal);\n        })(),\n        options: buildClaudeCapabilitiesProbeQueryOptions({\n          executablePath,\n          abortController: abort,\n          environment: claudeEnvironment,\n          cwd,\n        }),\n      });\n      const init = await q.initializationResult();\n      const account = init.account as\n        | {\n            readonly email?: string;\n            readonly subscriptionType?: string;\n            readonly tokenSource?: string;\n            readonly apiProvider?: string;\n          }\n        | undefined;\n      return {\n        email: account?.email,\n        subscriptionType: account?.subscriptionType,\n        tokenSource: account?.tokenSource,\n        apiProvider: account?.apiProvider,\n        slashCommands: parseClaudeInitializationCommands(init.commands),\n      } satisfies ClaudeCapabilitiesProbe;\n    });\n  }).pipe(\n    Effect.ensuring(\n      Effect.sync(() => {\n        if (!abort.signal.aborted) abort.abort();\n      }),\n    ),\n    Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),\n    Effect.result,\n    Effect.map((result) => {\n      if (Result.isFailure(result)) return undefined;\n      return Option.isSome(result.success) ? result.success.value : undefined;\n    }),\n  );\n};\n\nconst runClaudeCommand = Effect.fn(\"runClaudeCommand\")(function* (\n  claudeSettings: ClaudeSettings,\n  args: ReadonlyArray<string>,\n  environment?: NodeJS.ProcessEnv,\n) {\n  const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);\n  const spawnCommand = yield* resolveSpawnCommand(claudeSettings.binaryPath, args, {\n    env: claudeEnvironment,\n  });\n  const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n    env: claudeEnvironment,\n    shell: spawnCommand.shell,\n  });\n  return yield* spawnAndCollect(claudeSettings.binaryPath, command);\n});\n\nexport const checkClaudeProviderStatus = Effect.fn(\"checkClaudeProviderStatus\")(function* (\n  claudeSettings: ClaudeSettings,\n  resolveCapabilities?: (\n    claudeSettings: ClaudeSettings,\n  ) => Effect.Effect<ClaudeCapabilitiesProbe | undefined>,\n  environment?: NodeJS.ProcessEnv,\n  cwd?: string,\n): Effect.fn.Return<\n  ServerProviderDraft,\n  never,\n  ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path\n> {\n  const resolvedEnvironment = environment ?? process.env;\n  const checkedAt = DateTime.formatIso(yield* DateTime.now);\n  const allModels = providerModelsFromSettings(\n    BUILT_IN_MODELS,\n    claudeSettings.customModels,\n    DEFAULT_CLAUDE_MODEL_CAPABILITIES,\n  );\n\n  if (!claudeSettings.enabled) {\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: false,\n      checkedAt,\n      models: allModels,\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Claude is disabled in Synaptic Code settings.\",\n      },\n    });\n  }\n\n  const versionProbe = yield* runClaudeCommand(\n    claudeSettings,\n    [\"--version\"],\n    resolvedEnvironment,\n  ).pipe(Effect.timeoutOption(DEFAULT_TIMEOUT_MS), Effect.result);\n\n  if (Result.isFailure(versionProbe)) {\n    const error = versionProbe.failure;\n    yield* Effect.logWarning(\"Claude Agent CLI health check failed.\", {\n      errorTag: error._tag,\n    });\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: claudeSettings.enabled,\n      checkedAt,\n      models: allModels,\n      probe: {\n        installed: !isCommandMissingCause(error),\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: isCommandMissingCause(error)\n          ? \"Claude Agent CLI (`claude`) is not installed or not on PATH.\"\n          : \"Failed to execute Claude Agent CLI health check.\",\n      },\n    });\n  }\n\n  if (Option.isNone(versionProbe.success)) {\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: claudeSettings.enabled,\n      checkedAt,\n      models: allModels,\n      probe: {\n        installed: true,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message:\n          \"Claude Agent CLI is installed but failed to run. Timed out while running command.\",\n      },\n    });\n  }\n\n  const version = versionProbe.success.value;\n  const parsedVersion = parseGenericCliVersion(`${version.stdout}\\n${version.stderr}`);\n  if (version.code !== 0) {\n    yield* Effect.logWarning(\"Claude Agent CLI version probe exited with a non-zero status.\", {\n      exitCode: version.code,\n      stdoutLength: version.stdout.length,\n      stderrLength: version.stderr.length,\n    });\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: claudeSettings.enabled,\n      checkedAt,\n      models: allModels,\n      probe: {\n        installed: true,\n        version: parsedVersion,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: \"Claude Agent CLI is installed but failed to run.\",\n      },\n    });\n  }\n\n  const models = providerModelsFromSettings(\n    getBuiltInClaudeModelsForVersion(parsedVersion),\n    claudeSettings.customModels,\n    DEFAULT_CLAUDE_MODEL_CAPABILITIES,\n  );\n  const versionUpgradeMessage = supportsClaudeOpus5(parsedVersion)\n    ? undefined\n    : supportsClaudeFable5(parsedVersion)\n      ? formatClaudeOpus5UpgradeMessage(parsedVersion)\n      : supportsClaudeOpus48(parsedVersion)\n        ? formatClaudeFable5UpgradeMessage(parsedVersion)\n        : supportsClaudeOpus47(parsedVersion)\n          ? formatClaudeOpus48UpgradeMessage(parsedVersion)\n          : formatClaudeOpus47UpgradeMessage(parsedVersion);\n\n  const capabilities = resolveCapabilities\n    ? yield* resolveCapabilities(claudeSettings).pipe(Effect.orElseSucceed(() => undefined))\n    : undefined;\n  const skills = yield* discoverClaudeSkills(claudeSettings, cwd, resolvedEnvironment);\n  const slashCommands = capabilities?.slashCommands ?? [];\n  const dedupedSlashCommands = dedupeSlashCommands(slashCommands);\n\n  if (!capabilities) {\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: claudeSettings.enabled,\n      checkedAt,\n      models,\n      slashCommands: dedupedSlashCommands,\n      skills,\n      probe: {\n        installed: true,\n        version: parsedVersion,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Could not verify Claude authentication status from initialization result.\",\n      },\n    });\n  }\n\n  const authMetadata =\n    claudeAuthMetadata({\n      subscriptionType: capabilities.subscriptionType,\n      authMethod: capabilities.tokenSource,\n    }) ?? apiProviderAuthMetadata(capabilities.apiProvider);\n  return buildServerProvider({\n    presentation: CLAUDE_PRESENTATION,\n    enabled: claudeSettings.enabled,\n    checkedAt,\n    models,\n    slashCommands: dedupedSlashCommands,\n    skills,\n    probe: {\n      installed: true,\n      version: parsedVersion,\n      status: \"ready\",\n      auth: {\n        status: \"authenticated\",\n        ...(capabilities.email ? { email: capabilities.email } : {}),\n        ...(authMetadata ? authMetadata : {}),\n      },\n      ...(versionUpgradeMessage ? { message: versionUpgradeMessage } : {}),\n    },\n  });\n});\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\nexport const makePendingClaudeProvider = (\n  claudeSettings: ClaudeSettings,\n): Effect.Effect<ServerProviderDraft> =>\n  Effect.gen(function* () {\n    const checkedAt = yield* nowIso;\n    const models = providerModelsFromSettings(\n      BUILT_IN_MODELS,\n      claudeSettings.customModels,\n      DEFAULT_CLAUDE_MODEL_CAPABILITIES,\n    );\n\n    if (!claudeSettings.enabled) {\n      return buildServerProvider({\n        presentation: CLAUDE_PRESENTATION,\n        enabled: false,\n        checkedAt,\n        models,\n        probe: {\n          installed: false,\n          version: null,\n          status: \"warning\",\n          auth: { status: \"unknown\" },\n          message: \"Claude is disabled in Synaptic Code settings.\",\n        },\n      });\n    }\n\n    return buildServerProvider({\n      presentation: CLAUDE_PRESENTATION,\n      enabled: true,\n      checkedAt,\n      models,\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Claude provider status has not been checked in this session yet.\",\n      },\n    });\n  });\n\nexport { probeClaudeCapabilities };\n","/**\n * ClaudeTextGeneration – Text generation layer using the Claude CLI.\n *\n * Implements the same TextGeneration service contract as CodexTextGeneration but\n * delegates to the `claude` CLI (`claude -p`) with structured JSON output\n * instead of the `codex exec` CLI.\n *\n * @module ClaudeTextGeneration\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { type ClaudeSettings, type ModelSelection } from \"@t3tools/contracts\";\nimport { sanitizeBranchFragment, sanitizeFeatureBranchName } from \"@t3tools/shared/git\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\nimport { TextGenerationError } from \"@t3tools/contracts\";\nimport * as TextGeneration from \"./TextGeneration.ts\";\nimport {\n  buildBranchNamePrompt,\n  buildCommitMessagePrompt,\n  buildPrContentPrompt,\n  buildThreadTitlePrompt,\n} from \"./TextGenerationPrompts.ts\";\nimport {\n  normalizeCliError,\n  sanitizeCommitSubject,\n  sanitizePrTitle,\n  sanitizeThreadTitle,\n  toJsonSchemaObject,\n} from \"./TextGenerationUtils.ts\";\nimport {\n  getModelSelectionStringOptionValue,\n  getProviderOptionDescriptors,\n} from \"@t3tools/shared/model\";\nimport {\n  getClaudeModelCapabilities,\n  isClaudeUltracodeEffort,\n  normalizeClaudeCliEffort,\n  resolveClaudeApiModelId,\n  resolveClaudeEffort,\n} from \"../provider/Layers/ClaudeProvider.ts\";\nimport { makeClaudeEnvironment } from \"../provider/Drivers/ClaudeHome.ts\";\n\nconst CLAUDE_TIMEOUT_MS = 180_000;\n\n/**\n * Schema for the wrapper JSON returned by `claude -p --output-format json`.\n * We only care about `structured_output`.\n */\nconst ClaudeOutputEnvelope = Schema.Struct({\n  structured_output: Schema.Unknown,\n});\n\nconst encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));\nconst decodeClaudeOutputEnvelope = Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope));\n\nexport const makeClaudeTextGeneration = Effect.fn(\"makeClaudeTextGeneration\")(function* (\n  claudeSettings: ClaudeSettings,\n  environment?: NodeJS.ProcessEnv,\n) {\n  const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);\n\n  const readStreamAsString = <E>(\n    operation: string,\n    stream: Stream.Stream<Uint8Array, E>,\n  ): Effect.Effect<string, TextGenerationError> =>\n    stream.pipe(\n      Stream.decodeText(),\n      Stream.runFold(\n        () => \"\",\n        (acc, chunk) => acc + chunk,\n      ),\n      Effect.mapError((cause) =>\n        normalizeCliError(\"claude\", operation, cause, \"Failed to collect process output\"),\n      ),\n    );\n\n  const encodeJsonForOperation = (\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\",\n    value: unknown,\n    detail: string,\n  ): Effect.Effect<string, TextGenerationError> =>\n    encodeJsonString(value).pipe(\n      Effect.mapError(\n        (cause) =>\n          new TextGenerationError({\n            operation,\n            detail,\n            cause,\n          }),\n      ),\n    );\n\n  /**\n   * Spawn the Claude CLI with structured JSON output and return the parsed,\n   * schema-validated result.\n   */\n  const runClaudeJson = Effect.fn(\"runClaudeJson\")(function* <S extends Schema.Top>({\n    operation,\n    cwd,\n    prompt,\n    outputSchemaJson,\n    modelSelection,\n  }: {\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\";\n    cwd: string;\n    prompt: string;\n    outputSchemaJson: S;\n    modelSelection: ModelSelection;\n  }): Effect.fn.Return<S[\"Type\"], TextGenerationError, S[\"DecodingServices\"]> {\n    const jsonSchemaStr = yield* encodeJsonForOperation(\n      operation,\n      toJsonSchemaObject(outputSchemaJson),\n      \"Failed to encode structured output schema.\",\n    );\n    const caps = getClaudeModelCapabilities(modelSelection.model);\n    const descriptors = getProviderOptionDescriptors({\n      caps,\n      selections: modelSelection.options,\n    });\n    const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);\n    const rawEffortSelection = getModelSelectionStringOptionValue(modelSelection, \"effort\");\n    const resolvedEffort = resolveClaudeEffort(caps, rawEffortSelection);\n    const cliEffort = normalizeClaudeCliEffort(resolvedEffort, modelSelection.model);\n    const ultracode = isClaudeUltracodeEffort(resolvedEffort);\n    const thinkingDescriptor = findDescriptor(\"thinking\");\n    const fastModeDescriptor = findDescriptor(\"fastMode\");\n    const thinking =\n      thinkingDescriptor?.type === \"boolean\" ? thinkingDescriptor.currentValue : undefined;\n    const fastMode =\n      fastModeDescriptor?.type === \"boolean\" ? fastModeDescriptor.currentValue : undefined;\n    const settings = {\n      ...(typeof thinking === \"boolean\" ? { alwaysThinkingEnabled: thinking } : {}),\n      ...(fastMode ? { fastMode: true } : {}),\n      ...(ultracode ? { ultracode: true } : {}),\n    };\n    const settingsJson =\n      Object.keys(settings).length > 0\n        ? yield* encodeJsonForOperation(\n            operation,\n            settings,\n            \"Failed to encode Claude CLI settings.\",\n          )\n        : undefined;\n\n    const runClaudeCommand = Effect.fn(\"runClaudeJson.runClaudeCommand\")(function* () {\n      const spawnCommand = yield* resolveSpawnCommand(\n        claudeSettings.binaryPath || \"claude\",\n        [\n          \"-p\",\n          \"--output-format\",\n          \"json\",\n          \"--json-schema\",\n          jsonSchemaStr,\n          \"--model\",\n          resolveClaudeApiModelId(modelSelection),\n          ...(cliEffort ? [\"--effort\", cliEffort] : []),\n          ...(settingsJson ? [\"--settings\", settingsJson] : []),\n          \"--dangerously-skip-permissions\",\n        ],\n        { env: claudeEnvironment },\n      );\n      const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        env: claudeEnvironment,\n        cwd,\n        shell: spawnCommand.shell,\n        stdin: {\n          stream: Stream.encodeText(Stream.make(prompt)),\n        },\n      });\n\n      const child = yield* commandSpawner\n        .spawn(command)\n        .pipe(\n          Effect.mapError((cause) =>\n            normalizeCliError(\"claude\", operation, cause, \"Failed to spawn Claude CLI process\"),\n          ),\n        );\n\n      const [stdout, stderr, exitCode] = yield* Effect.all(\n        [\n          readStreamAsString(operation, child.stdout),\n          readStreamAsString(operation, child.stderr),\n          child.exitCode.pipe(\n            Effect.mapError((cause) =>\n              normalizeCliError(\"claude\", operation, cause, \"Failed to read Claude CLI exit code\"),\n            ),\n          ),\n        ],\n        { concurrency: \"unbounded\" },\n      );\n\n      if (exitCode !== 0) {\n        const stderrDetail = stderr.trim();\n        const stdoutDetail = stdout.trim();\n        const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;\n        return yield* new TextGenerationError({\n          operation,\n          detail:\n            detail.length > 0\n              ? `Claude CLI command failed: ${detail}`\n              : `Claude CLI command failed with code ${exitCode}.`,\n        });\n      }\n\n      return stdout;\n    });\n\n    const rawStdout = yield* runClaudeCommand().pipe(\n      Effect.scoped,\n      Effect.timeoutOption(CLAUDE_TIMEOUT_MS),\n      Effect.flatMap(\n        Option.match({\n          onNone: () =>\n            Effect.fail(\n              new TextGenerationError({ operation, detail: \"Claude CLI request timed out.\" }),\n            ),\n          onSome: (value) => Effect.succeed(value),\n        }),\n      ),\n    );\n\n    const envelope = yield* decodeClaudeOutputEnvelope(rawStdout).pipe(\n      Effect.catchTags({\n        SchemaError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation,\n              detail: \"Claude CLI returned unexpected output format.\",\n              cause,\n            }),\n          ),\n      }),\n    );\n\n    const decodeOutput = Schema.decodeEffect(outputSchemaJson);\n    return yield* decodeOutput(envelope.structured_output).pipe(\n      Effect.catchTags({\n        SchemaError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation,\n              detail: \"Claude returned invalid structured output.\",\n              cause,\n            }),\n          ),\n      }),\n    );\n  });\n\n  // ---------------------------------------------------------------------------\n  // TextGeneration service methods\n  // ---------------------------------------------------------------------------\n\n  const generateCommitMessage: TextGeneration.TextGeneration[\"Service\"][\"generateCommitMessage\"] =\n    Effect.fn(\"ClaudeTextGeneration.generateCommitMessage\")(function* (input) {\n      const { prompt, outputSchema } = buildCommitMessagePrompt({\n        branch: input.branch,\n        stagedSummary: input.stagedSummary,\n        stagedPatch: input.stagedPatch,\n        includeBranch: input.includeBranch === true,\n        policy: input.policy,\n      });\n\n      const generated = yield* runClaudeJson({\n        operation: \"generateCommitMessage\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        subject: sanitizeCommitSubject(generated.subject),\n        body: generated.body.trim(),\n        ...(\"branch\" in generated && typeof generated.branch === \"string\"\n          ? { branch: sanitizeFeatureBranchName(generated.branch) }\n          : {}),\n      };\n    });\n\n  const generatePrContent: TextGeneration.TextGeneration[\"Service\"][\"generatePrContent\"] =\n    Effect.fn(\"ClaudeTextGeneration.generatePrContent\")(function* (input) {\n      const { prompt, outputSchema } = buildPrContentPrompt({\n        baseBranch: input.baseBranch,\n        headBranch: input.headBranch,\n        commitSummary: input.commitSummary,\n        diffSummary: input.diffSummary,\n        diffPatch: input.diffPatch,\n        policy: input.policy,\n        changeRequestTemplate: input.changeRequestTemplate,\n      });\n\n      const generated = yield* runClaudeJson({\n        operation: \"generatePrContent\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizePrTitle(generated.title),\n        body: generated.body.trim(),\n      };\n    });\n\n  const generateBranchName: TextGeneration.TextGeneration[\"Service\"][\"generateBranchName\"] =\n    Effect.fn(\"ClaudeTextGeneration.generateBranchName\")(function* (input) {\n      const { prompt, outputSchema } = buildBranchNamePrompt({\n        message: input.message,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runClaudeJson({\n        operation: \"generateBranchName\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        branch: sanitizeBranchFragment(generated.branch),\n      };\n    });\n\n  const generateThreadTitle: TextGeneration.TextGeneration[\"Service\"][\"generateThreadTitle\"] =\n    Effect.fn(\"ClaudeTextGeneration.generateThreadTitle\")(function* (input) {\n      const { prompt, outputSchema } = buildThreadTitlePrompt({\n        message: input.message,\n        previousTitle: input.previousTitle,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runClaudeJson({\n        operation: \"generateThreadTitle\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizeThreadTitle(generated.title),\n      };\n    });\n\n  return {\n    generateCommitMessage,\n    generatePrContent,\n    generateBranchName,\n    generateThreadTitle,\n  } satisfies TextGeneration.TextGeneration[\"Service\"];\n});\n","export interface ParsedCliArgs {\n  readonly flags: Record<string, string | null>;\n  readonly positionals: string[];\n}\n\nexport interface ParseCliArgsOptions {\n  readonly booleanFlags?: readonly string[];\n}\n\nexport function tokenizeCliArgs(args?: string): ReadonlyArray<string> {\n  const input = args?.trim();\n  if (!input) return [];\n\n  const tokens: string[] = [];\n  let current = \"\";\n  let quote: \"'\" | '\"' | undefined;\n  let quoted = false;\n\n  for (let index = 0; index < input.length; index++) {\n    const char = input[index];\n    if (char === undefined) continue;\n\n    if (quote) {\n      if (char === quote) {\n        quote = undefined;\n        quoted = true;\n      } else if (char === \"\\\\\" && quote === '\"') {\n        const next = input[index + 1];\n        if (next !== undefined && ['\"', \"\\\\\", \"$\", \"`\"].includes(next)) {\n          current += next;\n          index++;\n        } else {\n          current += char;\n        }\n      } else {\n        current += char;\n      }\n      continue;\n    }\n\n    if (char === \"'\" || char === '\"') {\n      quote = char;\n      quoted = true;\n    } else if (/\\s/.test(char)) {\n      if (current || quoted) {\n        tokens.push(current);\n        current = \"\";\n        quoted = false;\n      }\n    } else if (char === \"\\\\\") {\n      const next = input[index + 1];\n      if (next !== undefined && /\\s/.test(next)) {\n        current += next;\n        index++;\n      } else {\n        current += char;\n      }\n    } else {\n      current += char;\n    }\n  }\n\n  if (current || quoted) tokens.push(current);\n  return tokens;\n}\n\n/**\n * Parse CLI-style arguments into flags and positionals.\n *\n * Accepts a string (quote-aware tokenized) or a pre-split argv array.\n * Supports `--key value`, `--key=value`, and `--flag` (boolean) syntax.\n *\n *   parseCliArgs(\"\")\n *     → { flags: {}, positionals: [] }\n *\n *   parseCliArgs(\"--chrome\")\n *     → { flags: { chrome: null }, positionals: [] }\n *\n *   parseCliArgs(\"--chrome --effort high\")\n *     → { flags: { chrome: null, effort: \"high\" }, positionals: [] }\n *\n *   parseCliArgs(\"--effort=high\")\n *     → { flags: { effort: \"high\" }, positionals: [] }\n *\n *   parseCliArgs([\"1.2.3\", \"--root\", \"/path\", \"--github-output\"], { booleanFlags: [\"github-output\"] })\n *     → { flags: { root: \"/path\", \"github-output\": null }, positionals: [\"1.2.3\"] }\n */\nexport function parseCliArgs(\n  args: string | readonly string[],\n  options?: ParseCliArgsOptions,\n): ParsedCliArgs {\n  const tokens = typeof args === \"string\" ? tokenizeCliArgs(args) : Array.from(args);\n  const booleanSet = options?.booleanFlags ? new Set(options.booleanFlags) : undefined;\n\n  const flags: Record<string, string | null> = {};\n  const positionals: string[] = [];\n\n  for (let i = 0; i < tokens.length; i++) {\n    const token = tokens[i]!;\n\n    if (token.startsWith(\"--\")) {\n      const rest = token.slice(2);\n      if (!rest) continue;\n\n      // Handle --key=value syntax\n      const eqIndex = rest.indexOf(\"=\");\n      if (eqIndex !== -1) {\n        flags[rest.slice(0, eqIndex)] = rest.slice(eqIndex + 1);\n        continue;\n      }\n\n      // Known boolean flag — never consumes next token\n      if (booleanSet?.has(rest)) {\n        flags[rest] = null;\n        continue;\n      }\n\n      // Handle --key value or --flag (boolean)\n      const next = tokens[i + 1];\n      if (next !== undefined && !next.startsWith(\"--\")) {\n        flags[rest] = next;\n        i++;\n      } else {\n        flags[rest] = null;\n      }\n    } else {\n      positionals.push(token);\n    }\n  }\n\n  return { flags, positionals };\n}\n","/**\n * ClaudeAdapterLive - Scoped live implementation for the Claude Agent provider adapter.\n *\n * Wraps `@anthropic-ai/claude-agent-sdk` query sessions behind the generic\n * provider adapter contract and emits canonical runtime events.\n *\n * @module ClaudeAdapterLive\n */\nimport {\n  type CanUseTool,\n  query,\n  type Options as ClaudeQueryOptions,\n  type PermissionMode,\n  type PermissionResult,\n  type PermissionUpdate,\n  type SDKMessage,\n  type SDKControlGetContextUsageResponse,\n  type SDKResultMessage,\n  type SettingSource,\n  type SDKUserMessage,\n  type ModelUsage,\n} from \"@anthropic-ai/claude-agent-sdk\";\nimport { parseCliArgs } from \"@t3tools/shared/cliArgs\";\nimport {\n  ApprovalRequestId,\n  type CanonicalItemType,\n  type CanonicalRequestType,\n  type ClaudeSettings,\n  EventId,\n  type ProviderApprovalDecision,\n  ProviderDriverKind,\n  ProviderInstanceId,\n  type ModelSelection,\n  ProviderItemId,\n  type ProviderRuntimeEvent,\n  type ProviderRuntimeTurnStatus,\n  type ProviderSendTurnInput,\n  type ProviderSession,\n  type ThreadTokenUsageSnapshot,\n  type ProviderUserInputAnswers,\n  type RuntimeContentStreamKind,\n  RuntimeItemId,\n  RuntimeRequestId,\n  RuntimeTaskId,\n  type RuntimeTaskStatus,\n  type RuntimeTaskUsage,\n  type TaskAgentLinkage,\n  type TaskRunHandles,\n  ThreadId,\n  TurnId,\n  type UserInputQuestion,\n} from \"@t3tools/contracts\";\nimport {\n  applyClaudePromptEffortPrefix,\n  getModelSelectionBooleanOptionValue,\n  getModelSelectionStringOptionValue,\n  getProviderOptionDescriptors,\n  resolvePromptInjectedEffort,\n} from \"@t3tools/shared/model\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\n\nimport { resolveAttachmentPath } from \"../../attachmentStore.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport * as McpProviderSession from \"../../mcp/McpProviderSession.ts\";\nimport { resolveClaudeSdkExecutablePath } from \"../Drivers/ClaudeExecutable.ts\";\nimport { makeClaudeEnvironment } from \"../Drivers/ClaudeHome.ts\";\nimport {\n  getClaudeModelCapabilities,\n  isClaudeUltracodeEffort,\n  normalizeClaudeCliEffort,\n  resolveClaudeApiModelId,\n  resolveClaudeContextWindow,\n  resolveClaudeEffort,\n} from \"./ClaudeProvider.ts\";\nimport {\n  ProviderAdapterProcessError,\n  ProviderAdapterRequestError,\n  ProviderAdapterSessionClosedError,\n  ProviderAdapterSessionNotFoundError,\n  ProviderAdapterValidationError,\n  type ProviderAdapterError,\n} from \"../Errors.ts\";\nimport { type ClaudeAdapterShape } from \"../Services/ClaudeAdapter.ts\";\nimport { type EventNdjsonLogger, makeEventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\nconst encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));\nconst decodeUnknownJsonStringExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));\n\nconst PROVIDER = ProviderDriverKind.make(\"claudeAgent\");\ntype ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, \"assistant_text\" | \"reasoning_text\">;\ntype ClaudeToolResultStreamKind = Extract<\n  RuntimeContentStreamKind,\n  \"command_output\" | \"file_change_output\"\n>;\ntype ClaudeSdkEffort = NonNullable<ClaudeQueryOptions[\"effort\"]>;\n\nfunction encodeJsonStringForDiagnostics(input: unknown): string | undefined {\n  const result = encodeUnknownJsonStringExit(input);\n  return Exit.isSuccess(result) ? result.value : undefined;\n}\n\ntype PromptQueueItem =\n  | {\n      readonly type: \"message\";\n      readonly message: SDKUserMessage;\n    }\n  | {\n      readonly type: \"terminate\";\n    };\n\ninterface ClaudeResumeState {\n  readonly threadId?: ThreadId;\n  readonly resume?: string;\n  readonly resumeSessionAt?: string;\n  readonly turnCount?: number;\n}\n\ninterface ClaudeTurnState {\n  readonly turnId: TurnId;\n  readonly startedAt: string;\n  /**\n   * True for turns auto-started by assistant output arriving without an\n   * active turn (background agent/subagent responses between user prompts).\n   * Synthetic turns are auto-closed by the next sendTurn; real turns are\n   * steered instead (the queued message continues the same turn).\n   */\n  readonly synthetic?: boolean;\n  readonly items: Array<unknown>;\n  readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;\n  readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;\n  readonly capturedProposedPlanKeys: Set<string>;\n  nextSyntheticAssistantBlockIndex: number;\n}\n\ninterface AssistantTextBlockState {\n  readonly itemId: string;\n  readonly blockIndex: number;\n  emittedTextDelta: boolean;\n  fallbackText: string;\n  streamClosed: boolean;\n  completionEmitted: boolean;\n}\n\ninterface PendingApproval {\n  readonly requestType: CanonicalRequestType;\n  readonly detail?: string;\n  readonly suggestions?: ReadonlyArray<PermissionUpdate>;\n  readonly decision: Deferred.Deferred<ProviderApprovalDecision>;\n}\n\ninterface PendingUserInput {\n  readonly questions: ReadonlyArray<UserInputQuestion>;\n  readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;\n}\n\ninterface ToolInFlight {\n  readonly itemId: string;\n  readonly itemType: CanonicalItemType;\n  readonly toolName: string;\n  readonly title: string;\n  readonly detail?: string;\n  readonly input: Record<string, unknown>;\n  readonly partialInputJson: string;\n  readonly lastEmittedInputFingerprint?: string;\n  /** Owning agent when this tool ran inside a subagent (see attribution note). */\n  readonly agentId?: string;\n  readonly parentToolUseId?: string;\n}\n\ninterface ClaudeTaskState {\n  readonly id: string;\n  subject: string;\n  status: PlanStep[\"status\"];\n  readonly blockedBy: Set<string>;\n}\n\n/**\n * Agent identity captured from task_started and repeated on every subsequent\n * task.* payload, so client folds can reconstruct an agent even when its\n * start row aged out of activity retention.\n */\ninterface ClaudeTaskAgentState {\n  readonly taskId: string;\n  toolUseId: string | undefined;\n  description: string | undefined;\n  subagentType: string | undefined;\n  taskType: string | undefined;\n  workflowName: string | undefined;\n  skipTranscript: boolean;\n  runHandles: TaskRunHandles | undefined;\n  /** Set when this task was launched from inside a subagent. */\n  owningAgentId: string | undefined;\n  /** Seeded from the launching tool's input; refined by the subagent's own\n   * assistant snapshots (authoritative API model). */\n  model: string | undefined;\n  effort: string | undefined;\n}\n\ninterface ClaudeSessionContext {\n  session: ProviderSession;\n  readonly promptQueue: Queue.Queue<PromptQueueItem>;\n  readonly query: ClaudeQueryRuntime;\n  streamFiber: Fiber.Fiber<void, Error> | undefined;\n  readonly startedAt: string;\n  readonly basePermissionMode: PermissionMode | undefined;\n  currentApiModelId: string | undefined;\n  /** Effective effort for the session's turns; subagents without an explicit\n   * effort override inherit this. */\n  currentEffort: string | undefined;\n  resumeSessionId: string | undefined;\n  readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;\n  readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;\n  readonly turns: Array<{\n    id: TurnId;\n    items: Array<unknown>;\n  }>;\n  readonly inFlightTools: Map<number, ToolInFlight>;\n  readonly claudeTasks: Map<string, ClaudeTaskState>;\n  readonly taskAgents: Map<string, ClaudeTaskAgentState>;\n  /**\n   * Last emitted workflow-member fingerprint per member slot. A coordinator\n   * task_progress repeats the FULL member array every tick; without a\n   * material-transition filter one provider tick fans out into up to 100\n   * runtime events (event-log writes, queue pressure, client reducer work)\n   * even when nothing changed for most members.\n   */\n  readonly workflowMemberFingerprints: Map<string, string>;\n  /** Task ids that have started and not yet reached a terminal state. */\n  readonly liveTaskIds: Set<string>;\n  turnState: ClaudeTurnState | undefined;\n  lastKnownContextWindow: number | undefined;\n  lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;\n  lastKnownTotalProcessedTokens: number | undefined;\n  lastAssistantUuid: string | undefined;\n  lastThreadStartedId: string | undefined;\n  stopped: boolean;\n}\n\ninterface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {\n  readonly interrupt: () => Promise<void>;\n  /** SDK Query.stopTask — present on real queries; optional for test doubles. */\n  readonly stopTask?: (taskId: string) => Promise<void>;\n  readonly setModel: (model?: string) => Promise<void>;\n  readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;\n  readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;\n  readonly getContextUsage?: () => Promise<SDKControlGetContextUsageResponse>;\n  readonly close: () => void;\n}\n\nexport interface ClaudeAdapterLiveOptions {\n  readonly instanceId?: ProviderInstanceId;\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly createQuery?: (input: {\n    readonly prompt: AsyncIterable<SDKUserMessage>;\n    readonly options: ClaudeQueryOptions;\n  }) => ClaudeQueryRuntime;\n  readonly nativeEventLogPath?: string;\n  readonly nativeEventLogger?: EventNdjsonLogger;\n}\n\nfunction isUuid(value: string): boolean {\n  return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);\n}\n\nfunction isSyntheticClaudeThreadId(value: string): boolean {\n  return value.startsWith(\"claude-thread-\");\n}\n\nfunction hasDurableClaudeSessionId(message: SDKMessage): boolean {\n  if (message.type !== \"system\") {\n    return true;\n  }\n\n  return (\n    message.subtype !== \"hook_started\" &&\n    message.subtype !== \"hook_progress\" &&\n    message.subtype !== \"hook_response\"\n  );\n}\n\nfunction toMessage(cause: unknown, fallback: string): string {\n  if (cause instanceof Error && cause.message.length > 0) {\n    return cause.message;\n  }\n  return fallback;\n}\n\nfunction normalizeClaudeStreamMessages(\n  cause: Cause.Cause<ProviderAdapterProcessError>,\n): ReadonlyArray<string> {\n  const errors: Array<string> = [];\n  for (const error of Cause.prettyErrors(cause)) {\n    const message = error.message.trim();\n    if (message.length > 0) {\n      errors.push(message);\n    }\n  }\n  if (errors.length > 0) {\n    return errors;\n  }\n\n  const squashed = toMessage(Cause.squash(cause), \"\").trim();\n  return squashed.length > 0 ? [squashed] : [];\n}\n\nfunction getEffectiveClaudeAgentEffort(\n  effort: string | null | undefined,\n  model: string | null | undefined,\n): ClaudeSdkEffort | null {\n  const normalized = normalizeClaudeCliEffort(effort, model);\n  return normalized ? (normalized as ClaudeSdkEffort) : null;\n}\n\nfunction isClaudeInterruptedMessage(message: string): boolean {\n  const normalized = message.toLowerCase();\n  return (\n    normalized.includes(\"all fibers interrupted without error\") ||\n    normalized.includes(\"request was aborted\") ||\n    normalized.includes(\"interrupted by user\")\n  );\n}\n\nfunction isClaudeInterruptedCause(cause: Cause.Cause<ProviderAdapterProcessError>): boolean {\n  return (\n    Cause.hasInterruptsOnly(cause) ||\n    normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage) ||\n    cause.reasons.some(\n      (reason) =>\n        Cause.isFailReason(reason) && isClaudeInterruptedMessage(toMessage(reason.error.cause, \"\")),\n    )\n  );\n}\n\nfunction resultErrorsText(result: SDKResultMessage): string {\n  return \"errors\" in result && Array.isArray(result.errors)\n    ? result.errors.join(\" \").toLowerCase()\n    : \"\";\n}\n\n/**\n * First user-facing error from a non-success result. \"[ede_diagnostic] ...\"\n * entries are CLI-internal telemetry (the CLI hides them from its own UI too),\n * so they must never become the error banner.\n */\nfunction resultUserFacingError(result: SDKResultMessage): string | undefined {\n  if (result.subtype === \"success\" || !Array.isArray(result.errors)) {\n    return undefined;\n  }\n  return result.errors.find((error) => !error.startsWith(\"[ede_diagnostic]\"));\n}\n\nfunction isInterruptedResult(result: SDKResultMessage): boolean {\n  // The CLI stamps user aborts explicitly: interrupting mid-tool-call yields\n  // \"aborted_tools\" (with an internal \"[ede_diagnostic] ...\" error and\n  // is_error: true), interrupting mid-stream yields \"aborted_streaming\".\n  if (\n    result.terminal_reason === \"aborted_tools\" ||\n    result.terminal_reason === \"aborted_streaming\"\n  ) {\n    return true;\n  }\n\n  const errors = resultErrorsText(result);\n  if (errors.includes(\"interrupt\")) {\n    return true;\n  }\n\n  return (\n    result.subtype === \"error_during_execution\" &&\n    result.is_error === false &&\n    (errors.includes(\"request was aborted\") ||\n      errors.includes(\"interrupted by user\") ||\n      errors.includes(\"aborted\"))\n  );\n}\n\nfunction asRuntimeItemId(value: string): RuntimeItemId {\n  return RuntimeItemId.make(value);\n}\n\nfunction maxClaudeContextWindowFromModelUsage(\n  modelUsage: Record<string, ModelUsage> | undefined,\n): number | undefined {\n  if (!modelUsage) return undefined;\n\n  let maxContextWindow: number | undefined;\n  for (const value of Object.values(modelUsage)) {\n    const contextWindow = value.contextWindow;\n    maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow);\n  }\n\n  return maxContextWindow;\n}\n\nfunction selectedClaudeContextWindow(\n  modelSelection: ModelSelection | undefined,\n): number | undefined {\n  switch (modelSelection?.model) {\n    case \"claude-opus-4-8\":\n    case \"claude-opus-4-7\":\n      // Always 1M at the API; these models expose no contextWindow option.\n      return 1_000_000;\n  }\n\n  switch (resolveClaudeContextWindow(modelSelection)) {\n    case \"1m\":\n      return 1_000_000;\n    case \"200k\":\n      return 200_000;\n    default:\n      return undefined;\n  }\n}\n\nfunction finiteNonNegativeInteger(value: unknown): number | undefined {\n  return typeof value === \"number\" && Number.isFinite(value) && value >= 0\n    ? Math.round(value)\n    : undefined;\n}\n\nfunction finitePositiveInteger(value: unknown): number | undefined {\n  return typeof value === \"number\" && Number.isFinite(value) && value > 0\n    ? Math.round(value)\n    : undefined;\n}\n\nfunction claudeUsageInputTokens(usage: Record<string, unknown>): number {\n  return (\n    (finiteNonNegativeInteger(usage.input_tokens) ?? 0) +\n    (finiteNonNegativeInteger(usage.cache_creation_input_tokens) ?? 0) +\n    (finiteNonNegativeInteger(usage.cache_read_input_tokens) ?? 0)\n  );\n}\n\nfunction claudeUsageOutputTokens(usage: Record<string, unknown>): number {\n  return finiteNonNegativeInteger(usage.output_tokens) ?? 0;\n}\n\nfunction lastClaudeUsageIteration(\n  value: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n  const iterations = Array.isArray(value.iterations) ? value.iterations : [];\n  return iterations.findLast(\n    (iteration): iteration is Record<string, unknown> =>\n      iteration !== null && typeof iteration === \"object\" && !Array.isArray(iteration),\n  );\n}\n\nfunction claudeTotalProcessedTokens(value: unknown): number | undefined {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n    return undefined;\n  }\n\n  const usage = value as Record<string, unknown>;\n  const explicitTotal = finiteNonNegativeInteger(usage.total_tokens);\n  if (explicitTotal !== undefined && explicitTotal > 0) {\n    return explicitTotal;\n  }\n\n  const total = claudeUsageInputTokens(usage) + claudeUsageOutputTokens(usage);\n  return total > 0 ? total : undefined;\n}\n\nfunction makeClaudeTokenUsageSnapshot(input: {\n  readonly activeTokens: number;\n  readonly inputTokens?: number;\n  readonly outputTokens?: number;\n  readonly contextWindow?: number;\n  readonly totalProcessedTokens?: number;\n  readonly lastUsedTokens?: number;\n  readonly compactsAutomatically?: boolean;\n}): ThreadTokenUsageSnapshot | undefined {\n  const activeTokens = finiteNonNegativeInteger(input.activeTokens);\n  if (activeTokens === undefined || activeTokens <= 0) {\n    return undefined;\n  }\n\n  const maxTokens = finitePositiveInteger(input.contextWindow);\n  const usedTokens = maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens;\n  const lastUsedTokens =\n    finiteNonNegativeInteger(input.lastUsedTokens) ??\n    (maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens);\n  const totalProcessedTokens = finiteNonNegativeInteger(input.totalProcessedTokens);\n  const inputTokens = finiteNonNegativeInteger(input.inputTokens);\n  const outputTokens = finiteNonNegativeInteger(input.outputTokens);\n\n  return {\n    usedTokens,\n    lastUsedTokens,\n    ...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens\n      ? { totalProcessedTokens }\n      : {}),\n    ...(inputTokens !== undefined && inputTokens > 0 ? { inputTokens } : {}),\n    ...(outputTokens !== undefined && outputTokens > 0 ? { outputTokens } : {}),\n    ...(maxTokens !== undefined ? { maxTokens } : {}),\n    ...(input.compactsAutomatically !== undefined\n      ? { compactsAutomatically: input.compactsAutomatically }\n      : {}),\n  };\n}\n\nfunction normalizeClaudeActiveTokenUsage(\n  value: unknown,\n  contextWindow?: number,\n  totalProcessedTokens?: number,\n): ThreadTokenUsageSnapshot | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n\n  const usage = value as Record<string, unknown>;\n  const activeUsage = lastClaudeUsageIteration(usage) ?? usage;\n  const inputTokens = claudeUsageInputTokens(activeUsage);\n  const outputTokens = claudeUsageOutputTokens(activeUsage);\n  const activeTokens = claudeTotalProcessedTokens(activeUsage) ?? inputTokens + outputTokens;\n  if (activeTokens <= 0) {\n    return undefined;\n  }\n\n  return makeClaudeTokenUsageSnapshot({\n    activeTokens,\n    inputTokens,\n    outputTokens,\n    ...(contextWindow !== undefined ? { contextWindow } : {}),\n    ...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),\n  });\n}\n\nfunction normalizeClaudeContextUsageApiSnapshot(\n  value: SDKControlGetContextUsageResponse,\n  totalProcessedTokens?: number,\n): ThreadTokenUsageSnapshot | undefined {\n  return makeClaudeTokenUsageSnapshot({\n    activeTokens: value.totalTokens,\n    contextWindow: value.maxTokens,\n    ...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),\n    compactsAutomatically: value.isAutoCompactEnabled,\n  });\n}\n\nfunction compactBoundaryTokenUsageSnapshot(\n  message: Record<string, unknown>,\n  contextWindow?: number,\n  totalProcessedTokens?: number,\n): ThreadTokenUsageSnapshot | undefined {\n  const metadata = message.compact_metadata;\n  if (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) {\n    return undefined;\n  }\n\n  const compactMetadata = metadata as Record<string, unknown>;\n  const postTokens = finiteNonNegativeInteger(compactMetadata.post_tokens);\n  if (postTokens === undefined || postTokens <= 0) {\n    return undefined;\n  }\n\n  const preTokens = finiteNonNegativeInteger(compactMetadata.pre_tokens);\n  return makeClaudeTokenUsageSnapshot({\n    activeTokens: postTokens,\n    ...(preTokens !== undefined ? { lastUsedTokens: preTokens } : {}),\n    ...(contextWindow !== undefined ? { contextWindow } : {}),\n    ...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),\n  });\n}\n\nfunction normalizeClaudeTaskProgressTokenUsage(\n  value: unknown,\n  context: ClaudeSessionContext,\n): ThreadTokenUsageSnapshot | undefined {\n  const totalTokens = claudeTotalProcessedTokens(value);\n  if (totalTokens === undefined || totalTokens <= 0) {\n    return undefined;\n  }\n\n  const lastUsedTokens = context.lastKnownTokenUsage?.usedTokens;\n  const activeTokens =\n    lastUsedTokens !== undefined ? Math.max(totalTokens, lastUsedTokens) : totalTokens;\n  if (lastUsedTokens !== undefined && activeTokens === lastUsedTokens) {\n    return undefined;\n  }\n\n  const usage = value as Record<string, unknown>;\n  const snapshot = makeClaudeTokenUsageSnapshot({\n    activeTokens,\n    ...(context.lastKnownContextWindow !== undefined\n      ? { contextWindow: context.lastKnownContextWindow }\n      : {}),\n    totalProcessedTokens: Math.max(\n      totalTokens,\n      context.lastKnownTotalProcessedTokens ?? totalTokens,\n    ),\n  });\n  if (!snapshot) {\n    return undefined;\n  }\n\n  const toolUses = finiteNonNegativeInteger(usage.tool_uses);\n  const durationMs = finiteNonNegativeInteger(usage.duration_ms);\n  return {\n    ...snapshot,\n    ...(toolUses !== undefined ? { toolUses } : {}),\n    ...(durationMs !== undefined ? { durationMs } : {}),\n  };\n}\n\nfunction asCanonicalTurnId(value: TurnId): TurnId {\n  return value;\n}\n\nfunction asRuntimeRequestId(value: ApprovalRequestId): RuntimeRequestId {\n  return RuntimeRequestId.make(value);\n}\n\nfunction readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undefined {\n  if (!resumeCursor || typeof resumeCursor !== \"object\") {\n    return undefined;\n  }\n  const cursor = resumeCursor as {\n    threadId?: unknown;\n    resume?: unknown;\n    sessionId?: unknown;\n    resumeSessionAt?: unknown;\n    turnCount?: unknown;\n  };\n\n  const threadIdCandidate = typeof cursor.threadId === \"string\" ? cursor.threadId : undefined;\n  const threadId =\n    threadIdCandidate && !isSyntheticClaudeThreadId(threadIdCandidate)\n      ? ThreadId.make(threadIdCandidate)\n      : undefined;\n  const resumeCandidate =\n    typeof cursor.resume === \"string\"\n      ? cursor.resume\n      : typeof cursor.sessionId === \"string\"\n        ? cursor.sessionId\n        : undefined;\n  const resume = resumeCandidate && isUuid(resumeCandidate) ? resumeCandidate : undefined;\n  const resumeSessionAt =\n    typeof cursor.resumeSessionAt === \"string\" ? cursor.resumeSessionAt : undefined;\n  const turnCountValue = typeof cursor.turnCount === \"number\" ? cursor.turnCount : undefined;\n\n  return {\n    ...(threadId ? { threadId } : {}),\n    ...(resume ? { resume } : {}),\n    ...(resumeSessionAt ? { resumeSessionAt } : {}),\n    ...(turnCountValue !== undefined && Number.isInteger(turnCountValue) && turnCountValue >= 0\n      ? { turnCount: turnCountValue }\n      : {}),\n  };\n}\n\nfunction classifyToolItemType(toolName: string): CanonicalItemType {\n  const normalized = toolName.toLowerCase();\n  if (normalized.includes(\"agent\")) {\n    return \"collab_agent_tool_call\";\n  }\n  if (\n    normalized === \"task\" ||\n    normalized === \"agent\" ||\n    normalized.includes(\"subagent\") ||\n    normalized.includes(\"sub-agent\")\n  ) {\n    return \"collab_agent_tool_call\";\n  }\n  if (\n    normalized.includes(\"bash\") ||\n    normalized.includes(\"command\") ||\n    normalized.includes(\"shell\") ||\n    normalized.includes(\"terminal\")\n  ) {\n    return \"command_execution\";\n  }\n  if (\n    normalized.includes(\"edit\") ||\n    normalized.includes(\"write\") ||\n    normalized.includes(\"file\") ||\n    normalized.includes(\"patch\") ||\n    normalized.includes(\"replace\") ||\n    normalized.includes(\"create\") ||\n    normalized.includes(\"delete\")\n  ) {\n    return \"file_change\";\n  }\n  if (normalized.includes(\"mcp\")) {\n    return \"mcp_tool_call\";\n  }\n  if (normalized.includes(\"websearch\") || normalized.includes(\"web search\")) {\n    return \"web_search\";\n  }\n  if (normalized.includes(\"image\")) {\n    return \"image_view\";\n  }\n  return \"dynamic_tool_call\";\n}\n\nfunction isReadOnlyToolName(toolName: string): boolean {\n  const normalized = toolName.toLowerCase();\n  return (\n    normalized === \"read\" ||\n    normalized.includes(\"read file\") ||\n    normalized.includes(\"view\") ||\n    normalized.includes(\"grep\") ||\n    normalized.includes(\"glob\") ||\n    normalized.includes(\"search\")\n  );\n}\n\nfunction classifyRequestType(toolName: string): CanonicalRequestType {\n  if (isReadOnlyToolName(toolName)) {\n    return \"file_read_approval\";\n  }\n  const itemType = classifyToolItemType(toolName);\n  return itemType === \"command_execution\"\n    ? \"command_execution_approval\"\n    : itemType === \"file_change\"\n      ? \"file_change_approval\"\n      : \"dynamic_tool_call\";\n}\n\nfunction isTodoTool(toolName: string): boolean {\n  return toolName.toLowerCase().includes(\"todowrite\");\n}\n\ntype PlanStep = {\n  step: string;\n  status: \"pending\" | \"inProgress\" | \"completed\";\n};\n\nfunction extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep[] | null {\n  // TodoWrite format: { todos: [{ content, status, activeForm? }] }\n  const todos = input.todos;\n  if (!Array.isArray(todos) || todos.length === 0) {\n    return null;\n  }\n  return todos\n    .filter((t): t is Record<string, unknown> => t !== null && typeof t === \"object\")\n    .map((todo) => ({\n      step:\n        typeof todo.content === \"string\" && todo.content.trim().length > 0\n          ? todo.content.trim()\n          : \"Task\",\n      status:\n        todo.status === \"completed\"\n          ? \"completed\"\n          : todo.status === \"in_progress\"\n            ? \"inProgress\"\n            : \"pending\",\n    }));\n}\n\nfunction isClaudeTaskTool(toolName: string): boolean {\n  return toolName === \"TaskCreate\" || toolName === \"TaskUpdate\" || toolName === \"TaskList\";\n}\n\nfunction normalizeClaudeTaskStatus(value: unknown): PlanStep[\"status\"] {\n  return value === \"completed\" ? \"completed\" : value === \"in_progress\" ? \"inProgress\" : \"pending\";\n}\n\nfunction readString(value: unknown): string | undefined {\n  return typeof value === \"string\" && value.trim().length > 0 ? value.trim() : undefined;\n}\n\nfunction readStringArray(value: unknown): Array<string> {\n  return Array.isArray(value)\n    ? value.filter((entry): entry is string => typeof entry === \"string\" && entry.length > 0)\n    : [];\n}\n\nfunction readClaudeToolUseResult(message: SDKMessage): Record<string, unknown> | undefined {\n  if (message.type !== \"user\") {\n    return undefined;\n  }\n  const result = (message as { readonly tool_use_result?: unknown }).tool_use_result;\n  return result !== null && typeof result === \"object\" && !Array.isArray(result)\n    ? (result as Record<string, unknown>)\n    : undefined;\n}\n\nfunction readClaudeTaskFromResult(\n  result: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n  const task = result?.task;\n  return task !== null && typeof task === \"object\" && !Array.isArray(task)\n    ? (task as Record<string, unknown>)\n    : undefined;\n}\n\nfunction applyClaudeTaskToolResult(\n  tasks: Map<string, ClaudeTaskState>,\n  tool: ToolInFlight,\n  result: Record<string, unknown> | undefined,\n): boolean {\n  if (!isClaudeTaskTool(tool.toolName)) {\n    return false;\n  }\n\n  let changed = false;\n  if (tool.toolName === \"TaskList\") {\n    const resultTasks = result?.tasks;\n    if (!Array.isArray(resultTasks)) {\n      return false;\n    }\n    tasks.clear();\n    for (const entry of resultTasks) {\n      if (entry === null || typeof entry !== \"object\" || Array.isArray(entry)) {\n        continue;\n      }\n      const task = entry as Record<string, unknown>;\n      const id = readString(task.id);\n      const subject = readString(task.subject);\n      if (!id || !subject) {\n        continue;\n      }\n      tasks.set(id, {\n        id,\n        subject,\n        status: normalizeClaudeTaskStatus(task.status),\n        blockedBy: new Set(readStringArray(task.blockedBy)),\n      });\n    }\n    return tasks.size > 0;\n  }\n\n  if (tool.toolName === \"TaskCreate\") {\n    const resultTask = readClaudeTaskFromResult(result);\n    const id = readString(resultTask?.id);\n    const subject = readString(resultTask?.subject) ?? readString(tool.input.subject);\n    if (!id || !subject) {\n      return false;\n    }\n    tasks.set(id, {\n      id,\n      subject,\n      status: normalizeClaudeTaskStatus(tool.input.status),\n      blockedBy: new Set(readStringArray(tool.input.blockedBy)),\n    });\n    return true;\n  }\n\n  const taskId = readString(tool.input.taskId) ?? readString(result?.taskId);\n  if (!taskId) {\n    return false;\n  }\n  const task = tasks.get(taskId);\n  if (!task) {\n    return false;\n  }\n  const subject = readString(tool.input.subject);\n  if (subject && task.subject !== subject) {\n    task.subject = subject;\n    changed = true;\n  }\n  if (typeof tool.input.status === \"string\") {\n    const status = normalizeClaudeTaskStatus(tool.input.status);\n    if (task.status !== status) {\n      task.status = status;\n      changed = true;\n    }\n  }\n  for (const dependency of readStringArray(tool.input.addBlockedBy)) {\n    if (!task.blockedBy.has(dependency)) {\n      task.blockedBy.add(dependency);\n      changed = true;\n    }\n  }\n  for (const dependency of readStringArray(tool.input.removeBlockedBy)) {\n    if (task.blockedBy.delete(dependency)) {\n      changed = true;\n    }\n  }\n  return changed;\n}\n\nfunction planStepsFromClaudeTasks(tasks: Map<string, ClaudeTaskState>): PlanStep[] {\n  return Array.from(tasks.values()).map((task) => {\n    const blockedBy = Array.from(task.blockedBy);\n    const blockedSuffix = blockedBy.length > 0 ? ` (blocked by #${blockedBy.join(\", #\")})` : \"\";\n    return {\n      step: `${task.subject}${blockedSuffix}`,\n      status: task.status,\n    };\n  });\n}\n\n/** Only http/https survive; anything else (javascript:, file:, …) is dropped. */\nfunction sanitizeSessionUrl(value: unknown): string | undefined {\n  if (typeof value !== \"string\") {\n    return undefined;\n  }\n  const trimmed = value.trim();\n  if (!/^https?:\\/\\//i.test(trimmed)) {\n    return undefined;\n  }\n  return trimmed;\n}\n\nfunction nonNegativeInt(value: unknown): number | undefined {\n  return typeof value === \"number\" && Number.isFinite(value) && value >= 0\n    ? Math.floor(value)\n    : undefined;\n}\n\nfunction trimmedString(value: unknown): string | undefined {\n  if (typeof value !== \"string\") {\n    return undefined;\n  }\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * SDK task usage ({total_tokens, tool_uses, duration_ms}, sometimes with\n * input/output/cache breakdowns) → the typed contract shape. Unknown or\n * malformed input yields undefined rather than a partial guess.\n */\nfunction normalizeTaskUsage(usage: unknown): RuntimeTaskUsage | undefined {\n  if (typeof usage !== \"object\" || usage === null) {\n    return undefined;\n  }\n  const record = usage as Record<string, unknown>;\n  const totalTokens = nonNegativeInt(record.total_tokens);\n  if (totalTokens === undefined) {\n    return undefined;\n  }\n  const inputTokens = nonNegativeInt(record.input_tokens);\n  const cachedInputTokens = nonNegativeInt(record.cache_read_input_tokens);\n  const outputTokens = nonNegativeInt(record.output_tokens);\n  const toolUses = nonNegativeInt(record.tool_uses);\n  const durationMs = nonNegativeInt(record.duration_ms);\n  return {\n    totalTokens,\n    ...(inputTokens !== undefined ? { inputTokens } : {}),\n    ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),\n    ...(outputTokens !== undefined ? { outputTokens } : {}),\n    ...(toolUses !== undefined ? { toolUses } : {}),\n    ...(durationMs !== undefined ? { durationMs } : {}),\n  };\n}\n\n/** SDK task_updated patch status → the shared wire vocabulary. */\nconst CLAUDE_TASK_PATCH_STATUS: Record<string, RuntimeTaskStatus> = {\n  pending: \"pending\",\n  running: \"running\",\n  completed: \"completed\",\n  failed: \"failed\",\n  killed: \"cancelled\",\n  paused: \"idle\",\n};\n\n/**\n * Resolves a stream message's parent_tool_use_id to the owning agent's\n * taskId. The Task tool's tool_use_id is remembered on task_started; any\n * subagent-forwarded block carries that id as its parent. Returns undefined\n * for parent-conversation traffic.\n */\nfunction agentIdForParentToolUse(\n  agents: Map<string, ClaudeTaskAgentState>,\n  parentToolUseId: string | null | undefined,\n): string | undefined {\n  if (parentToolUseId === null || parentToolUseId === undefined) {\n    return undefined;\n  }\n  for (const agent of agents.values()) {\n    if (agent.toolUseId === parentToolUseId) {\n      return agent.taskId;\n    }\n  }\n  return undefined;\n}\n\n/**\n * Linkage bundle repeated on every task.* payload for `taskId`. Reads the\n * remembered identity (from task_started) so progress/terminal rows are\n * self-describing even when the start row ages out of activity retention.\n */\nfunction taskLinkageFor(\n  agents: Map<string, ClaudeTaskAgentState>,\n  taskId: string,\n): TaskAgentLinkage {\n  const agent = agents.get(taskId);\n  if (!agent) {\n    return {};\n  }\n  return {\n    ...(agent.taskType ? { taskType: agent.taskType } : {}),\n    ...(agent.owningAgentId ? { agentId: agent.owningAgentId } : {}),\n    ...(agent.description ? { title: agent.description } : {}),\n    ...(agent.subagentType ? { role: agent.subagentType } : {}),\n    ...(agent.model ? { model: agent.model } : {}),\n    ...(agent.effort ? { effort: agent.effort } : {}),\n    ...(agent.toolUseId ? { toolUseId: agent.toolUseId } : {}),\n    ...(agent.workflowName ? { workflowName: agent.workflowName } : {}),\n    ...(agent.runHandles ? { runHandles: agent.runHandles } : {}),\n  };\n}\n\nconst WORKFLOW_PHASE_CAP = 64;\nconst WORKFLOW_AGENT_CAP = 100;\n\ninterface ClaudeWorkflowAgentEntry {\n  readonly index: number;\n  readonly state: string;\n  readonly label: string | undefined;\n  readonly phaseIndex: number | undefined;\n  readonly phaseTitle: string | undefined;\n  readonly model: string | undefined;\n  readonly attempt: number | undefined;\n  readonly lastToolName: string | undefined;\n  readonly startedAt: string | undefined;\n  readonly error: string | undefined;\n  readonly tokens: number | undefined;\n  readonly toolCalls: number | undefined;\n}\n\ninterface ClaudeWorkflowProgress {\n  readonly phases: ReadonlyArray<{ index: number; title: string }>;\n  readonly agents: ReadonlyArray<ClaudeWorkflowAgentEntry>;\n}\n\n/**\n * Defensive parse of the SDK's undeclared-but-real workflow_progress array on\n * task_progress messages (wire-confirmed; absent from sdk.d.ts). Unknown\n * shapes are skipped per-entry; phases and agents dedupe by index before\n * caps; a vanished field never throws. If the array disappears upstream the\n * caller keeps the coordinator row and plain task lifecycle.\n */\nfunction parseWorkflowProgress(value: unknown): ClaudeWorkflowProgress | undefined {\n  if (!Array.isArray(value) || value.length === 0) {\n    return undefined;\n  }\n  const phasesByIndex = new Map<number, string>();\n  const agentsByIndex = new Map<number, ClaudeWorkflowAgentEntry>();\n  for (const entry of value) {\n    if (typeof entry !== \"object\" || entry === null) {\n      continue;\n    }\n    const record = entry as Record<string, unknown>;\n    const entryType = trimmedString(record.type);\n    if (entryType === \"workflow_phase\") {\n      const index = nonNegativeInt(record.index);\n      const title = trimmedString(record.title);\n      if (index !== undefined && title && !phasesByIndex.has(index)) {\n        phasesByIndex.set(index, title);\n      }\n      continue;\n    }\n    if (entryType !== \"workflow_agent\") {\n      continue;\n    }\n    const index = nonNegativeInt(record.index);\n    const state = trimmedString(record.state);\n    if (index === undefined || !state || agentsByIndex.has(index)) {\n      continue;\n    }\n    agentsByIndex.set(index, {\n      index,\n      state,\n      label: trimmedString(record.label),\n      phaseIndex: nonNegativeInt(record.phaseIndex),\n      phaseTitle: trimmedString(record.phaseTitle),\n      model: trimmedString(record.model),\n      attempt: nonNegativeInt(record.attempt),\n      lastToolName: trimmedString(record.lastToolName),\n      startedAt: trimmedString(record.startedAt),\n      error: trimmedString(record.error),\n      tokens: nonNegativeInt(record.tokens),\n      toolCalls: nonNegativeInt(record.toolCalls),\n    });\n  }\n  if (phasesByIndex.size === 0 && agentsByIndex.size === 0) {\n    return undefined;\n  }\n  const phases = Array.from(phasesByIndex.entries())\n    .map(([index, title]) => ({ index, title }))\n    .toSorted((a, b) => a.index - b.index)\n    .slice(0, WORKFLOW_PHASE_CAP);\n  const agents = Array.from(agentsByIndex.values())\n    .toSorted((a, b) => a.index - b.index)\n    .slice(0, WORKFLOW_AGENT_CAP);\n  return { phases, agents };\n}\n\n/**\n * Workflow member states from workflow_progress → shared task status.\n * Unknown states read running after startedAt, pending before it.\n */\nfunction workflowAgentStatus(entry: ClaudeWorkflowAgentEntry): RuntimeTaskStatus {\n  switch (entry.state) {\n    case \"queued\":\n    case \"pending\":\n      return \"pending\";\n    case \"start\":\n    case \"running\":\n      return entry.startedAt === undefined ? \"pending\" : \"running\";\n    case \"done\":\n      return \"completed\";\n    case \"error\":\n      return \"failed\";\n    default:\n      return entry.startedAt === undefined ? \"pending\" : \"running\";\n  }\n}\n\nfunction summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {\n  const commandValue = input.command ?? input.cmd;\n  const command = typeof commandValue === \"string\" ? commandValue : undefined;\n  if (command && command.trim().length > 0) {\n    return `${toolName}: ${command.trim().slice(0, 400)}`;\n  }\n\n  // For agent/subagent tools, prefer the human-readable description or prompt\n  // over raw JSON. The structured subagent_type is carried separately on the\n  // task.* payloads (role) — the label is display-only.\n  const itemType = classifyToolItemType(toolName);\n  if (itemType === \"collab_agent_tool_call\") {\n    const description =\n      typeof input.description === \"string\" ? input.description.trim() : undefined;\n    const prompt = typeof input.prompt === \"string\" ? input.prompt.trim() : undefined;\n    const label = description || (prompt ? prompt.slice(0, 200) : undefined);\n    if (label) {\n      return label;\n    }\n  }\n\n  const serialized = encodeJsonStringForDiagnostics(input) ?? \"[unserializable input]\";\n  if (serialized.length <= 400) {\n    return `${toolName}: ${serialized}`;\n  }\n  return `${toolName}: ${serialized.slice(0, 397)}...`;\n}\n\nfunction titleForTool(itemType: CanonicalItemType): string {\n  switch (itemType) {\n    case \"command_execution\":\n      return \"Command run\";\n    case \"file_change\":\n      return \"File change\";\n    case \"mcp_tool_call\":\n      return \"MCP tool call\";\n    case \"collab_agent_tool_call\":\n      return \"Subagent task\";\n    case \"web_search\":\n      return \"Web search\";\n    case \"image_view\":\n      return \"Image view\";\n    case \"dynamic_tool_call\":\n      return \"Tool call\";\n    default:\n      return \"Item\";\n  }\n}\n\nconst SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = new Set([\n  \"image/gif\",\n  \"image/jpeg\",\n  \"image/png\",\n  \"image/webp\",\n]);\nconst CLAUDE_SETTING_SOURCES = [\n  \"user\",\n  \"project\",\n  \"local\",\n] as const satisfies ReadonlyArray<SettingSource>;\n\nfunction buildPromptText(\n  input: ProviderSendTurnInput,\n  boundInstanceId: ProviderInstanceId,\n): string {\n  const rawEffort =\n    input.modelSelection?.instanceId === boundInstanceId\n      ? getModelSelectionStringOptionValue(input.modelSelection, \"effort\")\n      : null;\n  const claudeModel =\n    input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection.model : undefined;\n  const caps = getClaudeModelCapabilities(claudeModel);\n\n  const promptEffort = resolvePromptInjectedEffort(caps, rawEffort);\n  return applyClaudePromptEffortPrefix(input.input?.trim() ?? \"\", promptEffort);\n}\n\nfunction buildUserMessage(input: {\n  readonly sdkContent: Array<Record<string, unknown>>;\n}): SDKUserMessage {\n  return {\n    type: \"user\",\n    session_id: \"\",\n    parent_tool_use_id: null,\n    message: {\n      role: \"user\",\n      content: input.sdkContent as unknown as SDKUserMessage[\"message\"][\"content\"],\n    },\n  } as SDKUserMessage;\n}\n\nfunction buildClaudeImageContentBlock(input: {\n  readonly mimeType: string;\n  readonly bytes: Uint8Array;\n}): Record<string, unknown> {\n  return {\n    type: \"image\",\n    source: {\n      type: \"base64\",\n      media_type: input.mimeType,\n      data: Buffer.from(input.bytes).toString(\"base64\"),\n    },\n  };\n}\n\nconst buildUserMessageEffect = Effect.fn(\"buildUserMessageEffect\")(function* (\n  input: ProviderSendTurnInput,\n  dependencies: {\n    readonly fileSystem: FileSystem.FileSystem;\n    readonly attachmentsDir: string;\n    readonly boundInstanceId: ProviderInstanceId;\n  },\n) {\n  const text = buildPromptText(input, dependencies.boundInstanceId);\n  const sdkContent: Array<Record<string, unknown>> = [];\n\n  if (text.length > 0) {\n    sdkContent.push({ type: \"text\", text });\n  }\n\n  for (const attachment of input.attachments ?? []) {\n    if (attachment.type !== \"image\") {\n      continue;\n    }\n\n    if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) {\n      return yield* new ProviderAdapterRequestError({\n        provider: PROVIDER,\n        method: \"turn/start\",\n        detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`,\n      });\n    }\n\n    const attachmentPath = resolveAttachmentPath({\n      attachmentsDir: dependencies.attachmentsDir,\n      attachment,\n    });\n    if (!attachmentPath) {\n      return yield* new ProviderAdapterRequestError({\n        provider: PROVIDER,\n        method: \"turn/start\",\n        detail: `Invalid attachment id '${attachment.id}'.`,\n      });\n    }\n\n    const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"turn/start\",\n            detail: \"Failed to read attachment file.\",\n            cause,\n          }),\n      ),\n    );\n\n    sdkContent.push(\n      buildClaudeImageContentBlock({\n        mimeType: attachment.mimeType,\n        bytes,\n      }),\n    );\n  }\n\n  return buildUserMessage({ sdkContent });\n});\n\nfunction turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus {\n  if (result.subtype === \"success\") {\n    return \"completed\";\n  }\n\n  const errors = resultErrorsText(result);\n  if (isInterruptedResult(result)) {\n    return \"interrupted\";\n  }\n  if (errors.includes(\"cancel\")) {\n    return \"cancelled\";\n  }\n  return \"failed\";\n}\n\nfunction streamKindFromDeltaType(deltaType: string): ClaudeTextStreamKind {\n  return deltaType.includes(\"thinking\") ? \"reasoning_text\" : \"assistant_text\";\n}\n\nfunction nativeProviderRefs(\n  _context: ClaudeSessionContext,\n  options?: {\n    readonly providerItemId?: string | undefined;\n  },\n): NonNullable<ProviderRuntimeEvent[\"providerRefs\"]> {\n  if (options?.providerItemId) {\n    return {\n      providerItemId: ProviderItemId.make(options.providerItemId),\n    };\n  }\n  return {};\n}\n\nfunction extractAssistantTextBlocks(message: SDKMessage): Array<string> {\n  if (message.type !== \"assistant\") {\n    return [];\n  }\n\n  const content = (message.message as { content?: unknown } | undefined)?.content;\n  if (!Array.isArray(content)) {\n    return [];\n  }\n\n  const fragments: string[] = [];\n  for (const block of content) {\n    if (!block || typeof block !== \"object\") {\n      continue;\n    }\n    const candidate = block as { type?: unknown; text?: unknown };\n    if (\n      candidate.type === \"text\" &&\n      typeof candidate.text === \"string\" &&\n      candidate.text.length > 0\n    ) {\n      fragments.push(candidate.text);\n    }\n  }\n\n  return fragments;\n}\n\nfunction extractContentBlockText(block: unknown): string {\n  if (!block || typeof block !== \"object\") {\n    return \"\";\n  }\n\n  const candidate = block as { type?: unknown; text?: unknown };\n  return candidate.type === \"text\" && typeof candidate.text === \"string\" ? candidate.text : \"\";\n}\n\nfunction extractTextContent(value: unknown): string {\n  if (typeof value === \"string\") {\n    return value;\n  }\n\n  if (Array.isArray(value)) {\n    return value.map((entry) => extractTextContent(entry)).join(\"\");\n  }\n\n  if (!value || typeof value !== \"object\") {\n    return \"\";\n  }\n\n  const record = value as {\n    text?: unknown;\n    content?: unknown;\n  };\n\n  if (typeof record.text === \"string\") {\n    return record.text;\n  }\n\n  return extractTextContent(record.content);\n}\n\nfunction extractExitPlanModePlan(value: unknown): string | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n\n  const record = value as {\n    plan?: unknown;\n  };\n  return typeof record.plan === \"string\" && record.plan.trim().length > 0\n    ? record.plan.trim()\n    : undefined;\n}\n\nfunction exitPlanCaptureKey(input: {\n  readonly toolUseId?: string | undefined;\n  readonly planMarkdown: string;\n}): string {\n  return input.toolUseId && input.toolUseId.length > 0\n    ? `tool:${input.toolUseId}`\n    : `plan:${input.planMarkdown}`;\n}\n\nfunction tryParseJsonRecord(value: string): Record<string, unknown> | undefined {\n  const result = decodeUnknownJsonStringExit(value);\n  if (!Exit.isSuccess(result)) {\n    return undefined;\n  }\n  const parsed = result.value;\n  return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n    ? (parsed as Record<string, unknown>)\n    : undefined;\n}\n\nfunction toolInputFingerprint(input: Record<string, unknown>): string | undefined {\n  return encodeJsonStringForDiagnostics(input);\n}\n\nfunction toolResultStreamKind(itemType: CanonicalItemType): ClaudeToolResultStreamKind | undefined {\n  switch (itemType) {\n    case \"command_execution\":\n      return \"command_output\";\n    case \"file_change\":\n      return \"file_change_output\";\n    default:\n      return undefined;\n  }\n}\n\nfunction toolResultBlocksFromUserMessage(message: SDKMessage): Array<{\n  readonly toolUseId: string;\n  readonly block: Record<string, unknown>;\n  readonly text: string;\n  readonly isError: boolean;\n}> {\n  if (message.type !== \"user\") {\n    return [];\n  }\n\n  const content = (message.message as { content?: unknown } | undefined)?.content;\n  if (!Array.isArray(content)) {\n    return [];\n  }\n\n  const blocks: Array<{\n    readonly toolUseId: string;\n    readonly block: Record<string, unknown>;\n    readonly text: string;\n    readonly isError: boolean;\n  }> = [];\n\n  for (const entry of content) {\n    if (!entry || typeof entry !== \"object\") {\n      continue;\n    }\n\n    const block = entry as Record<string, unknown>;\n    if (block.type !== \"tool_result\") {\n      continue;\n    }\n\n    const toolUseId = typeof block.tool_use_id === \"string\" ? block.tool_use_id : undefined;\n    if (!toolUseId) {\n      continue;\n    }\n\n    blocks.push({\n      toolUseId,\n      block,\n      text: extractTextContent(block.content),\n      isError: block.is_error === true,\n    });\n  }\n\n  return blocks;\n}\n\nfunction toSessionError(\n  threadId: ThreadId,\n  cause: unknown,\n): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined {\n  const normalized = toMessage(cause, \"\").toLowerCase();\n  if (normalized.includes(\"unknown session\") || normalized.includes(\"not found\")) {\n    return new ProviderAdapterSessionNotFoundError({\n      provider: PROVIDER,\n      threadId,\n      cause,\n    });\n  }\n  if (normalized.includes(\"closed\")) {\n    return new ProviderAdapterSessionClosedError({\n      provider: PROVIDER,\n      threadId,\n      cause,\n    });\n  }\n  return undefined;\n}\n\nfunction toRequestError(threadId: ThreadId, method: string, cause: unknown): ProviderAdapterError {\n  const sessionError = toSessionError(threadId, cause);\n  if (sessionError) {\n    return sessionError;\n  }\n  return new ProviderAdapterRequestError({\n    provider: PROVIDER,\n    method,\n    detail: `${method} failed`,\n    cause,\n  });\n}\n\nfunction sdkMessageType(value: unknown): string | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n  const record = value as { type?: unknown };\n  return typeof record.type === \"string\" ? record.type : undefined;\n}\n\nfunction sdkMessageSubtype(value: unknown): string | undefined {\n  if (!value || typeof value !== \"object\") {\n    return undefined;\n  }\n  const record = value as { subtype?: unknown };\n  return typeof record.subtype === \"string\" ? record.subtype : undefined;\n}\n\nfunction sdkNativeMethod(message: SDKMessage): string {\n  const subtype = sdkMessageSubtype(message);\n  if (subtype) {\n    return `claude/${message.type}/${subtype}`;\n  }\n\n  if (message.type === \"stream_event\") {\n    const streamType = sdkMessageType(message.event);\n    if (streamType) {\n      const deltaType =\n        streamType === \"content_block_delta\"\n          ? sdkMessageType((message.event as { delta?: unknown }).delta)\n          : undefined;\n      if (deltaType) {\n        return `claude/${message.type}/${streamType}/${deltaType}`;\n      }\n      return `claude/${message.type}/${streamType}`;\n    }\n  }\n\n  return `claude/${message.type}`;\n}\n\n// Discriminator/identity keys carry no human-readable content; everything else\n// on an unmodeled SDK message is potentially worth surfacing in the work log.\nconst SDK_MESSAGE_NOISE_KEYS = new Set([\n  \"type\",\n  \"subtype\",\n  \"uuid\",\n  \"parent_uuid\",\n  \"session_id\",\n  \"parent_tool_use_id\",\n  \"request_id\",\n]);\n\n// Pull the salient scalar content out of a message the adapter doesn't model\n// yet, so the work-log row shows what actually arrived (e.g. a notification's\n// text) instead of an opaque \"unhandled subtype\" placeholder. Nested structures\n// are left to the full payload retained in the event's `detail`.\nfunction previewUnknownSdkContent(message: unknown): string | undefined {\n  if (!message || typeof message !== \"object\") {\n    return undefined;\n  }\n  const parts: string[] = [];\n  for (const [key, value] of Object.entries(message as Record<string, unknown>)) {\n    if (SDK_MESSAGE_NOISE_KEYS.has(key)) {\n      continue;\n    }\n    if (typeof value === \"string\") {\n      const trimmed = value.trim();\n      if (trimmed.length > 0) {\n        parts.push(`${key}: ${trimmed}`);\n      }\n    } else if (typeof value === \"number\" || typeof value === \"boolean\") {\n      parts.push(`${key}: ${String(value)}`);\n    }\n  }\n  if (parts.length === 0) {\n    return undefined;\n  }\n  const joined = parts.join(\" · \");\n  return joined.length > 280 ? `${joined.slice(0, 279)}…` : joined;\n}\n\nfunction describeUnknownSdkMessage(kind: string, message: unknown): string {\n  const preview = previewUnknownSdkContent(message);\n  return preview ? `${kind} — ${preview}` : `${kind} (no displayable text content)`;\n}\n\nfunction sdkNativeItemId(message: SDKMessage): string | undefined {\n  if (message.type === \"assistant\") {\n    const maybeId = (message.message as { id?: unknown }).id;\n    if (typeof maybeId === \"string\") {\n      return maybeId;\n    }\n    return undefined;\n  }\n\n  if (message.type === \"user\") {\n    return toolResultBlocksFromUserMessage(message)[0]?.toolUseId;\n  }\n\n  if (message.type === \"stream_event\") {\n    const event = message.event as {\n      type?: unknown;\n      content_block?: { id?: unknown };\n    };\n    if (event.type === \"content_block_start\" && typeof event.content_block?.id === \"string\") {\n      return event.content_block.id;\n    }\n  }\n\n  return undefined;\n}\n\nexport const makeClaudeAdapter = Effect.fn(\"makeClaudeAdapter\")(function* (\n  claudeSettings: ClaudeSettings,\n  options?: ClaudeAdapterLiveOptions,\n) {\n  const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make(\"claudeAgent\");\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const serverConfig = yield* ServerConfig;\n  const crypto = yield* Crypto.Crypto;\n  const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, options?.environment).pipe(\n    Effect.provideService(Path.Path, path),\n  );\n  const claudeSdkExecutablePath = yield* resolveClaudeSdkExecutablePath(\n    claudeSettings.binaryPath,\n    claudeEnvironment,\n  );\n  const nativeEventLogger =\n    options?.nativeEventLogger ??\n    (options?.nativeEventLogPath !== undefined\n      ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {\n          stream: \"native\",\n        })\n      : undefined);\n  const managedNativeEventLogger =\n    options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n\n  const createQuery =\n    options?.createQuery ??\n    ((input: {\n      readonly prompt: AsyncIterable<SDKUserMessage>;\n      readonly options: ClaudeQueryOptions;\n    }) =>\n      query({\n        prompt: input.prompt,\n        options: input.options,\n      }) as ClaudeQueryRuntime);\n\n  const sessions = new Map<ThreadId, ClaudeSessionContext>();\n  const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();\n\n  const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n  const randomUUIDv4 = crypto.randomUUIDv4.pipe(\n    Effect.mapError(\n      (cause) =>\n        new ProviderAdapterRequestError({\n          provider: PROVIDER,\n          method: \"crypto/randomUUIDv4\",\n          detail: \"Failed to generate Claude runtime identifier.\",\n          cause,\n        }),\n    ),\n  );\n  const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));\n  const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });\n\n  const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>\n    Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);\n\n  const logNativeSdkMessage = Effect.fnUntraced(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (!nativeEventLogger) {\n      return;\n    }\n\n    const observedAt = yield* nowIso;\n    const itemId = sdkNativeItemId(message);\n\n    yield* nativeEventLogger.write(\n      {\n        observedAt,\n        event: {\n          id:\n            \"uuid\" in message && typeof message.uuid === \"string\"\n              ? message.uuid\n              : yield* randomUUIDv4,\n          kind: \"notification\",\n          provider: PROVIDER,\n          createdAt: observedAt,\n          method: sdkNativeMethod(message),\n          ...(typeof message.session_id === \"string\"\n            ? { providerThreadId: message.session_id }\n            : {}),\n          ...(context.turnState\n            ? {\n                turnId: asCanonicalTurnId(context.turnState.turnId),\n              }\n            : {}),\n          ...(itemId ? { itemId: ProviderItemId.make(itemId) } : {}),\n          payload: message,\n        },\n      },\n      context.session.threadId,\n    );\n  });\n\n  const snapshotThread = Effect.fn(\"snapshotThread\")(function* (context: ClaudeSessionContext) {\n    const threadId = context.session.threadId;\n    if (!threadId) {\n      return yield* new ProviderAdapterValidationError({\n        provider: PROVIDER,\n        operation: \"readThread\",\n        issue: \"Session thread id is not initialized yet.\",\n      });\n    }\n    return {\n      threadId,\n      turns: context.turns.map((turn) => ({\n        id: turn.id,\n        items: [...turn.items],\n      })),\n    };\n  });\n\n  const updateResumeCursor = Effect.fn(\"updateResumeCursor\")(function* (\n    context: ClaudeSessionContext,\n  ) {\n    const threadId = context.session.threadId;\n    if (!threadId) return;\n\n    const resumeCursor = {\n      threadId,\n      ...(context.resumeSessionId ? { resume: context.resumeSessionId } : {}),\n      ...(context.lastAssistantUuid ? { resumeSessionAt: context.lastAssistantUuid } : {}),\n      turnCount: context.turns.length,\n    };\n\n    context.session = {\n      ...context.session,\n      resumeCursor,\n      updatedAt: yield* nowIso,\n    };\n  });\n\n  const ensureAssistantTextBlock = Effect.fn(\"ensureAssistantTextBlock\")(function* (\n    context: ClaudeSessionContext,\n    blockIndex: number,\n    options?: {\n      readonly fallbackText?: string;\n      readonly streamClosed?: boolean;\n    },\n  ) {\n    const turnState = context.turnState;\n    if (!turnState) {\n      return undefined;\n    }\n\n    const existing = turnState.assistantTextBlocks.get(blockIndex);\n    if (existing && !existing.completionEmitted) {\n      if (existing.fallbackText.length === 0 && options?.fallbackText) {\n        existing.fallbackText = options.fallbackText;\n      }\n      if (options?.streamClosed) {\n        existing.streamClosed = true;\n      }\n      return { blockIndex, block: existing };\n    }\n\n    const block: AssistantTextBlockState = {\n      itemId: yield* randomUUIDv4,\n      blockIndex,\n      emittedTextDelta: false,\n      fallbackText: options?.fallbackText ?? \"\",\n      streamClosed: options?.streamClosed ?? false,\n      completionEmitted: false,\n    };\n    turnState.assistantTextBlocks.set(blockIndex, block);\n    turnState.assistantTextBlockOrder.push(block);\n    return { blockIndex, block };\n  });\n\n  const createSyntheticAssistantTextBlock = Effect.fn(\"createSyntheticAssistantTextBlock\")(\n    function* (context: ClaudeSessionContext, fallbackText: string) {\n      const turnState = context.turnState;\n      if (!turnState) {\n        return undefined;\n      }\n\n      const blockIndex = turnState.nextSyntheticAssistantBlockIndex;\n      turnState.nextSyntheticAssistantBlockIndex -= 1;\n      return yield* ensureAssistantTextBlock(context, blockIndex, {\n        fallbackText,\n        streamClosed: true,\n      });\n    },\n  );\n\n  const completeAssistantTextBlock = Effect.fn(\"completeAssistantTextBlock\")(function* (\n    context: ClaudeSessionContext,\n    block: AssistantTextBlockState,\n    options?: {\n      readonly force?: boolean;\n      readonly rawMethod?: string;\n      readonly rawPayload?: unknown;\n    },\n  ) {\n    const turnState = context.turnState;\n    if (!turnState || block.completionEmitted) {\n      return;\n    }\n\n    if (!options?.force && !block.streamClosed) {\n      return;\n    }\n\n    if (!block.emittedTextDelta && block.fallbackText.length > 0) {\n      const deltaStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"content.delta\",\n        eventId: deltaStamp.eventId,\n        provider: PROVIDER,\n        createdAt: deltaStamp.createdAt,\n        threadId: context.session.threadId,\n        turnId: turnState.turnId,\n        itemId: asRuntimeItemId(block.itemId),\n        payload: {\n          streamKind: \"assistant_text\",\n          delta: block.fallbackText,\n        },\n        providerRefs: nativeProviderRefs(context),\n        ...(options?.rawMethod || options?.rawPayload\n          ? {\n              raw: {\n                source: \"claude.sdk.message\" as const,\n                ...(options.rawMethod ? { method: options.rawMethod } : {}),\n                payload: options?.rawPayload,\n              },\n            }\n          : {}),\n      });\n    }\n\n    block.completionEmitted = true;\n    if (turnState.assistantTextBlocks.get(block.blockIndex) === block) {\n      turnState.assistantTextBlocks.delete(block.blockIndex);\n    }\n\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"item.completed\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      itemId: asRuntimeItemId(block.itemId),\n      threadId: context.session.threadId,\n      turnId: turnState.turnId,\n      payload: {\n        itemType: \"assistant_message\",\n        status: \"completed\",\n        title: \"Assistant message\",\n        ...(block.fallbackText.length > 0 ? { detail: block.fallbackText } : {}),\n      },\n      providerRefs: nativeProviderRefs(context),\n      ...(options?.rawMethod || options?.rawPayload\n        ? {\n            raw: {\n              source: \"claude.sdk.message\" as const,\n              ...(options.rawMethod ? { method: options.rawMethod } : {}),\n              payload: options?.rawPayload,\n            },\n          }\n        : {}),\n    });\n  });\n\n  const backfillAssistantTextBlocksFromSnapshot = Effect.fn(\n    \"backfillAssistantTextBlocksFromSnapshot\",\n  )(function* (context: ClaudeSessionContext, message: SDKMessage) {\n    const turnState = context.turnState;\n    if (!turnState) {\n      return;\n    }\n\n    const snapshotTextBlocks = extractAssistantTextBlocks(message);\n    if (snapshotTextBlocks.length === 0) {\n      return;\n    }\n\n    const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({\n      blockIndex: block.blockIndex,\n      block,\n    }));\n\n    for (const [position, text] of snapshotTextBlocks.entries()) {\n      const existingEntry = orderedBlocks[position];\n      const entry =\n        existingEntry ??\n        (yield* createSyntheticAssistantTextBlock(context, text).pipe(\n          Effect.map((created) => {\n            if (!created) {\n              return undefined;\n            }\n            orderedBlocks.push(created);\n            return created;\n          }),\n        ));\n      if (!entry) {\n        continue;\n      }\n\n      if (entry.block.fallbackText.length === 0) {\n        entry.block.fallbackText = text;\n      }\n\n      if (entry.block.streamClosed && !entry.block.completionEmitted) {\n        yield* completeAssistantTextBlock(context, entry.block, {\n          rawMethod: \"claude/assistant\",\n          rawPayload: message,\n        });\n      }\n    }\n  });\n\n  const ensureThreadId = Effect.fn(\"ensureThreadId\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (typeof message.session_id !== \"string\" || message.session_id.length === 0) {\n      return;\n    }\n    if (!hasDurableClaudeSessionId(message)) {\n      return;\n    }\n    const nextThreadId = message.session_id;\n    context.resumeSessionId = message.session_id;\n    yield* updateResumeCursor(context);\n\n    if (context.lastThreadStartedId !== nextThreadId) {\n      context.lastThreadStartedId = nextThreadId;\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"thread.started\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        payload: {\n          providerThreadId: nextThreadId,\n        },\n        providerRefs: {},\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/thread/started\",\n          payload: {\n            session_id: message.session_id,\n          },\n        },\n      });\n    }\n  });\n\n  const emitRuntimeError = Effect.fn(\"emitRuntimeError\")(function* (\n    context: ClaudeSessionContext,\n    message: string,\n    cause?: unknown,\n  ) {\n    if (cause !== undefined) {\n      void cause;\n    }\n    const turnState = context.turnState;\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"runtime.error\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),\n      payload: {\n        message,\n        class: \"provider_error\",\n        ...(cause !== undefined ? { detail: cause } : {}),\n      },\n      providerRefs: nativeProviderRefs(context),\n    });\n  });\n\n  const emitRuntimeWarning = Effect.fn(\"emitRuntimeWarning\")(function* (\n    context: ClaudeSessionContext,\n    message: string,\n    detail?: unknown,\n  ) {\n    const turnState = context.turnState;\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"runtime.warning\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),\n      payload: {\n        message,\n        ...(detail !== undefined ? { detail } : {}),\n      },\n      providerRefs: nativeProviderRefs(context),\n    });\n  });\n\n  const emitThreadTokenUsage = Effect.fn(\"emitThreadTokenUsage\")(function* (\n    context: ClaudeSessionContext,\n    usage: ThreadTokenUsageSnapshot | undefined,\n    options?: {\n      readonly rawMethod?: string;\n      readonly rawPayload?: unknown;\n    },\n  ) {\n    if (!usage) {\n      return;\n    }\n\n    context.lastKnownTokenUsage = usage;\n    context.lastKnownTotalProcessedTokens =\n      usage.totalProcessedTokens ?? context.lastKnownTotalProcessedTokens;\n\n    const turnState = context.turnState;\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"thread.token-usage.updated\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(turnState ? { turnId: turnState.turnId } : {}),\n      payload: {\n        usage,\n      },\n      providerRefs: nativeProviderRefs(context),\n      ...(options?.rawMethod || options?.rawPayload\n        ? {\n            raw: {\n              source: \"claude.sdk.message\" as const,\n              ...(options.rawMethod ? { method: options.rawMethod } : {}),\n              payload: options.rawPayload,\n            },\n          }\n        : {}),\n    });\n  });\n\n  const queryCurrentContextUsage = Effect.fn(\"queryCurrentContextUsage\")(function* (\n    context: ClaudeSessionContext,\n    totalProcessedTokens?: number,\n  ) {\n    if (!context.query.getContextUsage) {\n      return undefined;\n    }\n\n    const usage = yield* Effect.promise(async () => {\n      try {\n        return await context.query.getContextUsage?.();\n      } catch {\n        return undefined;\n      }\n    });\n    if (!usage) {\n      return undefined;\n    }\n\n    context.lastKnownContextWindow = usage.maxTokens;\n    return normalizeClaudeContextUsageApiSnapshot(usage, totalProcessedTokens);\n  });\n\n  const emitProposedPlanCompleted = Effect.fn(\"emitProposedPlanCompleted\")(function* (\n    context: ClaudeSessionContext,\n    input: {\n      readonly planMarkdown: string;\n      readonly toolUseId?: string | undefined;\n      readonly rawSource: \"claude.sdk.message\" | \"claude.sdk.permission\";\n      readonly rawMethod: string;\n      readonly rawPayload: unknown;\n    },\n  ) {\n    const turnState = context.turnState;\n    const planMarkdown = input.planMarkdown.trim();\n    if (!turnState || planMarkdown.length === 0) {\n      return;\n    }\n\n    const captureKey = exitPlanCaptureKey({\n      toolUseId: input.toolUseId,\n      planMarkdown,\n    });\n    if (turnState.capturedProposedPlanKeys.has(captureKey)) {\n      return;\n    }\n    turnState.capturedProposedPlanKeys.add(captureKey);\n\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"turn.proposed.completed\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      turnId: turnState.turnId,\n      payload: {\n        planMarkdown,\n      },\n      providerRefs: nativeProviderRefs(context, {\n        providerItemId: input.toolUseId,\n      }),\n      raw: {\n        source: input.rawSource,\n        method: input.rawMethod,\n        payload: input.rawPayload,\n      },\n    });\n  });\n\n  const emitClaudeTaskPlanUpdated = Effect.fn(\"emitClaudeTaskPlanUpdated\")(function* (\n    context: ClaudeSessionContext,\n    input: {\n      readonly toolUseId: string;\n      readonly rawMethod: string;\n      readonly rawPayload: unknown;\n    },\n  ) {\n    const plan = planStepsFromClaudeTasks(context.claudeTasks);\n    if (plan.length === 0) {\n      return;\n    }\n\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"turn.plan.updated\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n      payload: {\n        explanation: \"Claude Tasks\",\n        plan,\n      },\n      providerRefs: nativeProviderRefs(context, {\n        providerItemId: input.toolUseId,\n      }),\n      raw: {\n        source: \"claude.sdk.message\",\n        method: input.rawMethod,\n        payload: input.rawPayload,\n      },\n    });\n  });\n\n  const completeTurn = Effect.fn(\"completeTurn\")(function* (\n    context: ClaudeSessionContext,\n    status: ProviderRuntimeTurnStatus,\n    errorMessage?: string,\n    result?: SDKResultMessage,\n  ) {\n    const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);\n    if (resultContextWindow !== undefined) {\n      context.lastKnownContextWindow = resultContextWindow;\n    }\n\n    const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;\n    const accumulatedTotalProcessedTokens = claudeTotalProcessedTokens(result?.usage);\n    if (accumulatedTotalProcessedTokens !== undefined) {\n      context.lastKnownTotalProcessedTokens = accumulatedTotalProcessedTokens;\n    }\n\n    const contextUsageSnapshot = yield* queryCurrentContextUsage(\n      context,\n      accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,\n    );\n    const resultUsageRecord =\n      result?.usage && typeof result.usage === \"object\" && !Array.isArray(result.usage)\n        ? (result.usage as Record<string, unknown>)\n        : undefined;\n    const hasResultUsageIteration =\n      resultUsageRecord !== undefined && lastClaudeUsageIteration(resultUsageRecord) !== undefined;\n    const resultHasActiveUsage =\n      resultUsageRecord !== undefined &&\n      (hasResultUsageIteration ||\n        claudeUsageInputTokens(resultUsageRecord) + claudeUsageOutputTokens(resultUsageRecord) > 0);\n    const resultTotalOnly =\n      resultUsageRecord !== undefined &&\n      !resultHasActiveUsage &&\n      claudeTotalProcessedTokens(resultUsageRecord) !== undefined;\n    const resultIterationSnapshot = resultUsageRecord\n      ? normalizeClaudeActiveTokenUsage(\n          resultUsageRecord,\n          maxTokens,\n          accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,\n        )\n      : undefined;\n    const lastGoodUsage = context.lastKnownTokenUsage;\n    const usageSnapshot: ThreadTokenUsageSnapshot | undefined =\n      contextUsageSnapshot ??\n      (resultTotalOnly && lastGoodUsage\n        ? {\n            ...lastGoodUsage,\n            ...(typeof maxTokens === \"number\" && Number.isFinite(maxTokens) && maxTokens > 0\n              ? { maxTokens }\n              : {}),\n            ...(typeof accumulatedTotalProcessedTokens === \"number\" &&\n            Number.isFinite(accumulatedTotalProcessedTokens) &&\n            accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens\n              ? {\n                  totalProcessedTokens: accumulatedTotalProcessedTokens,\n                }\n              : {}),\n          }\n        : resultIterationSnapshot) ??\n      (lastGoodUsage\n        ? {\n            ...lastGoodUsage,\n            ...(typeof maxTokens === \"number\" && Number.isFinite(maxTokens) && maxTokens > 0\n              ? { maxTokens }\n              : {}),\n            ...(typeof accumulatedTotalProcessedTokens === \"number\" &&\n            Number.isFinite(accumulatedTotalProcessedTokens) &&\n            accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens\n              ? {\n                  totalProcessedTokens: accumulatedTotalProcessedTokens,\n                }\n              : {}),\n          }\n        : undefined);\n\n    const turnState = context.turnState;\n    if (!turnState) {\n      yield* emitThreadTokenUsage(context, usageSnapshot, {\n        rawMethod: \"claude/result\",\n        rawPayload: result ?? { status },\n      });\n\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"turn.completed\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        payload: {\n          state: status,\n          ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),\n          ...(result?.usage ? { usage: result.usage } : {}),\n          ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),\n          ...(typeof result?.total_cost_usd === \"number\"\n            ? { totalCostUsd: result.total_cost_usd }\n            : {}),\n          ...(errorMessage ? { errorMessage } : {}),\n        },\n        providerRefs: {},\n      });\n      return;\n    }\n\n    for (const [index, tool] of context.inFlightTools.entries()) {\n      const toolStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"item.completed\",\n        eventId: toolStamp.eventId,\n        provider: PROVIDER,\n        createdAt: toolStamp.createdAt,\n        threadId: context.session.threadId,\n        turnId: turnState.turnId,\n        itemId: asRuntimeItemId(tool.itemId),\n        payload: {\n          itemType: tool.itemType,\n          status: status === \"completed\" ? \"completed\" : \"failed\",\n          title: tool.title,\n          ...(tool.detail ? { detail: tool.detail } : {}),\n          data: {\n            toolName: tool.toolName,\n            input: tool.input,\n          },\n        },\n        providerRefs: nativeProviderRefs(context, {\n          providerItemId: tool.itemId,\n        }),\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/result\",\n          payload: result ?? { status },\n        },\n      });\n      context.inFlightTools.delete(index);\n    }\n    // Clear any remaining stale entries (e.g. from interrupted content blocks)\n    context.inFlightTools.clear();\n\n    for (const block of turnState.assistantTextBlockOrder) {\n      yield* completeAssistantTextBlock(context, block, {\n        force: true,\n        rawMethod: \"claude/result\",\n        rawPayload: result ?? { status },\n      });\n    }\n\n    context.turns.push({\n      id: turnState.turnId,\n      items: [...turnState.items],\n    });\n\n    yield* emitThreadTokenUsage(context, usageSnapshot, {\n      rawMethod: \"claude/result\",\n      rawPayload: result ?? { status },\n    });\n\n    const stamp = yield* makeEventStamp();\n    yield* offerRuntimeEvent({\n      type: \"turn.completed\",\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      turnId: turnState.turnId,\n      payload: {\n        state: status,\n        ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),\n        ...(result?.usage ? { usage: result.usage } : {}),\n        ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),\n        ...(typeof result?.total_cost_usd === \"number\"\n          ? { totalCostUsd: result.total_cost_usd }\n          : {}),\n        ...(errorMessage ? { errorMessage } : {}),\n      },\n      providerRefs: nativeProviderRefs(context),\n    });\n\n    const updatedAt = yield* nowIso;\n    context.turnState = undefined;\n    context.session = {\n      ...context.session,\n      status: \"ready\",\n      activeTurnId: undefined,\n      updatedAt,\n      ...(status === \"failed\" && errorMessage ? { lastError: errorMessage } : {}),\n    };\n    yield* updateResumeCursor(context);\n  });\n\n  const handleStreamEvent = Effect.fn(\"handleStreamEvent\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"stream_event\") {\n      return;\n    }\n\n    const { event } = message;\n\n    // Subagent-owned stream traffic (parent_tool_use_id set) must not write\n    // into the parent transcript: with forwardSubagentText off the SDK still\n    // forwards subagent tool_use/tool_result blocks and their wrapping\n    // text/thinking deltas, and emitting them interleaved N subagents'\n    // narration into the chat (live-test finding). Their results reach the\n    // UI via the task.* lifecycle; their tool blocks are attributed and\n    // re-homed by the quiet-timeline filter.\n    const streamParentToolUseId = (message as { parent_tool_use_id?: string | null })\n      .parent_tool_use_id;\n    if (streamParentToolUseId !== null && streamParentToolUseId !== undefined) {\n      // Drop only the subagent's narration (text/thinking); tool_use blocks\n      // and their input_json_delta frames must flow so attributed tool items\n      // keep their inputs (review finding: dropping deltas emptied inputs).\n      const dropStart =\n        event.type === \"content_block_start\" &&\n        event.content_block.type !== \"tool_use\" &&\n        event.content_block.type !== \"server_tool_use\" &&\n        event.content_block.type !== \"mcp_tool_use\";\n      const dropDelta =\n        event.type === \"content_block_delta\" &&\n        (event.delta.type === \"text_delta\" || event.delta.type === \"thinking_delta\");\n      if (dropStart || dropDelta) {\n        return;\n      }\n    }\n\n    if (event.type === \"message_delta\") {\n      if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {\n        return;\n      }\n\n      const snapshot = normalizeClaudeActiveTokenUsage(\n        event.usage,\n        context.lastKnownContextWindow,\n        context.lastKnownTotalProcessedTokens,\n      );\n      yield* emitThreadTokenUsage(context, snapshot, {\n        rawMethod: \"claude/stream_event/message_delta\",\n        rawPayload: message,\n      });\n      return;\n    }\n\n    if (event.type === \"content_block_delta\") {\n      if (\n        (event.delta.type === \"text_delta\" || event.delta.type === \"thinking_delta\") &&\n        context.turnState\n      ) {\n        const deltaText =\n          event.delta.type === \"text_delta\"\n            ? event.delta.text\n            : typeof event.delta.thinking === \"string\"\n              ? event.delta.thinking\n              : \"\";\n        if (deltaText.length === 0) {\n          return;\n        }\n        const streamKind = streamKindFromDeltaType(event.delta.type);\n        const assistantBlockEntry =\n          event.delta.type === \"text_delta\"\n            ? yield* ensureAssistantTextBlock(context, event.index)\n            : context.turnState.assistantTextBlocks.get(event.index)\n              ? {\n                  blockIndex: event.index,\n                  block: context.turnState.assistantTextBlocks.get(\n                    event.index,\n                  ) as AssistantTextBlockState,\n                }\n              : undefined;\n        if (assistantBlockEntry?.block && event.delta.type === \"text_delta\") {\n          assistantBlockEntry.block.emittedTextDelta = true;\n        }\n        const stamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"content.delta\",\n          eventId: stamp.eventId,\n          provider: PROVIDER,\n          createdAt: stamp.createdAt,\n          threadId: context.session.threadId,\n          turnId: context.turnState.turnId,\n          ...(assistantBlockEntry?.block\n            ? {\n                itemId: asRuntimeItemId(assistantBlockEntry.block.itemId),\n              }\n            : {}),\n          payload: {\n            streamKind,\n            delta: deltaText,\n          },\n          providerRefs: nativeProviderRefs(context),\n          raw: {\n            source: \"claude.sdk.message\",\n            method: \"claude/stream_event/content_block_delta\",\n            payload: message,\n          },\n        });\n        return;\n      }\n\n      if (event.delta.type === \"input_json_delta\") {\n        const tool = context.inFlightTools.get(event.index);\n        if (!tool || typeof event.delta.partial_json !== \"string\") {\n          return;\n        }\n\n        const partialInputJson = tool.partialInputJson + event.delta.partial_json;\n        const parsedInput = tryParseJsonRecord(partialInputJson);\n        const detail = parsedInput ? summarizeToolRequest(tool.toolName, parsedInput) : tool.detail;\n        let nextTool: ToolInFlight = {\n          ...tool,\n          partialInputJson,\n          ...(parsedInput ? { input: parsedInput } : {}),\n          ...(detail ? { detail } : {}),\n        };\n\n        const nextFingerprint =\n          parsedInput && Object.keys(parsedInput).length > 0\n            ? toolInputFingerprint(parsedInput)\n            : undefined;\n        context.inFlightTools.set(event.index, nextTool);\n\n        if (\n          !parsedInput ||\n          !nextFingerprint ||\n          tool.lastEmittedInputFingerprint === nextFingerprint\n        ) {\n          return;\n        }\n\n        nextTool = {\n          ...nextTool,\n          lastEmittedInputFingerprint: nextFingerprint,\n        };\n        context.inFlightTools.set(event.index, nextTool);\n\n        const stamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"item.updated\",\n          eventId: stamp.eventId,\n          provider: PROVIDER,\n          createdAt: stamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState\n            ? {\n                turnId: asCanonicalTurnId(context.turnState.turnId),\n              }\n            : {}),\n          itemId: asRuntimeItemId(nextTool.itemId),\n          payload: {\n            itemType: nextTool.itemType,\n            status: \"inProgress\",\n            title: nextTool.title,\n            ...(nextTool.detail ? { detail: nextTool.detail } : {}),\n            ...(nextTool.agentId ? { agentId: nextTool.agentId } : {}),\n            ...(nextTool.parentToolUseId ? { parentToolUseId: nextTool.parentToolUseId } : {}),\n            data: {\n              toolName: nextTool.toolName,\n              input: nextTool.input,\n            },\n          },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: nextTool.itemId,\n          }),\n          raw: {\n            source: \"claude.sdk.message\",\n            method: \"claude/stream_event/content_block_delta/input_json_delta\",\n            payload: message,\n          },\n        });\n\n        // Emit plan update when TodoWrite input is parsed\n        if (parsedInput && isTodoTool(nextTool.toolName)) {\n          const planSteps = extractPlanStepsFromTodoInput(parsedInput);\n          if (planSteps && planSteps.length > 0) {\n            const planStamp = yield* makeEventStamp();\n            yield* offerRuntimeEvent({\n              type: \"turn.plan.updated\",\n              eventId: planStamp.eventId,\n              provider: PROVIDER,\n              createdAt: planStamp.createdAt,\n              threadId: context.session.threadId,\n              ...(context.turnState\n                ? {\n                    turnId: asCanonicalTurnId(context.turnState.turnId),\n                  }\n                : {}),\n              payload: {\n                plan: planSteps,\n              },\n              providerRefs: nativeProviderRefs(context),\n            });\n          }\n        }\n      }\n      return;\n    }\n\n    if (event.type === \"content_block_start\") {\n      const { index, content_block: block } = event;\n      if (block.type === \"text\") {\n        yield* ensureAssistantTextBlock(context, index, {\n          fallbackText: extractContentBlockText(block),\n        });\n        return;\n      }\n      if (\n        block.type !== \"tool_use\" &&\n        block.type !== \"server_tool_use\" &&\n        block.type !== \"mcp_tool_use\"\n      ) {\n        return;\n      }\n\n      const toolName = block.name;\n      const itemType = classifyToolItemType(toolName);\n      const toolInput =\n        typeof block.input === \"object\" && block.input !== null\n          ? (block.input as Record<string, unknown>)\n          : {};\n      const itemId = block.id;\n      const detail = summarizeToolRequest(toolName, toolInput);\n      const inputFingerprint =\n        Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined;\n\n      // Attribute tools that ran inside a subagent to their owning agent so\n      // clients can re-home them out of the main timeline (quiet-timeline\n      // guarantee): the SDK forwards subagent tool_use blocks tagged with the\n      // spawning Task tool's id as parent_tool_use_id.\n      const parentToolUseId =\n        (message as { parent_tool_use_id?: string | null }).parent_tool_use_id ?? undefined;\n      const owningAgentId = agentIdForParentToolUse(context.taskAgents, parentToolUseId);\n\n      const tool: ToolInFlight = {\n        itemId,\n        itemType,\n        toolName,\n        title: titleForTool(itemType),\n        detail,\n        input: toolInput,\n        partialInputJson: \"\",\n        ...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}),\n        ...(owningAgentId ? { agentId: owningAgentId } : {}),\n        ...(parentToolUseId ? { parentToolUseId } : {}),\n      };\n      context.inFlightTools.set(index, tool);\n\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"item.started\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n        itemId: asRuntimeItemId(tool.itemId),\n        payload: {\n          itemType: tool.itemType,\n          status: \"inProgress\",\n          title: tool.title,\n          ...(tool.detail ? { detail: tool.detail } : {}),\n          ...(tool.agentId ? { agentId: tool.agentId } : {}),\n          ...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),\n          data: {\n            toolName: tool.toolName,\n            input: toolInput,\n          },\n        },\n        providerRefs: nativeProviderRefs(context, {\n          providerItemId: tool.itemId,\n        }),\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/stream_event/content_block_start\",\n          payload: message,\n        },\n      });\n      return;\n    }\n\n    if (event.type === \"content_block_stop\") {\n      const { index } = event;\n      const assistantBlock = context.turnState?.assistantTextBlocks.get(index);\n      if (assistantBlock) {\n        assistantBlock.streamClosed = true;\n        yield* completeAssistantTextBlock(context, assistantBlock, {\n          rawMethod: \"claude/stream_event/content_block_stop\",\n          rawPayload: message,\n        });\n        return;\n      }\n      const tool = context.inFlightTools.get(index);\n      if (!tool) {\n        return;\n      }\n    }\n  });\n\n  const handleUserMessage = Effect.fn(\"handleUserMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"user\") {\n      return;\n    }\n\n    if (context.turnState) {\n      context.turnState.items.push(message.message);\n    }\n\n    for (const toolResult of toolResultBlocksFromUserMessage(message)) {\n      const toolEntry = Array.from(context.inFlightTools.entries()).find(\n        ([, tool]) => tool.itemId === toolResult.toolUseId,\n      );\n      if (!toolEntry) {\n        continue;\n      }\n\n      const [index, tool] = toolEntry;\n      const itemStatus = toolResult.isError ? \"failed\" : \"completed\";\n      const toolUseResult = readClaudeToolUseResult(message);\n      const toolData = {\n        toolName: tool.toolName,\n        input: tool.input,\n        result: toolResult.block,\n      };\n\n      const updatedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"item.updated\",\n        eventId: updatedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: updatedStamp.createdAt,\n        threadId: context.session.threadId,\n        ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n        itemId: asRuntimeItemId(tool.itemId),\n        payload: {\n          itemType: tool.itemType,\n          status: toolResult.isError ? \"failed\" : \"inProgress\",\n          title: tool.title,\n          ...(tool.detail ? { detail: tool.detail } : {}),\n          ...(tool.agentId ? { agentId: tool.agentId } : {}),\n          ...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),\n          data: toolData,\n        },\n        providerRefs: nativeProviderRefs(context, {\n          providerItemId: tool.itemId,\n        }),\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/user\",\n          payload: message,\n        },\n      });\n\n      const streamKind = toolResultStreamKind(tool.itemType);\n      if (streamKind && toolResult.text.length > 0 && context.turnState) {\n        const deltaStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"content.delta\",\n          eventId: deltaStamp.eventId,\n          provider: PROVIDER,\n          createdAt: deltaStamp.createdAt,\n          threadId: context.session.threadId,\n          turnId: context.turnState.turnId,\n          itemId: asRuntimeItemId(tool.itemId),\n          payload: {\n            streamKind,\n            delta: toolResult.text,\n          },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: tool.itemId,\n          }),\n          raw: {\n            source: \"claude.sdk.message\",\n            method: \"claude/user\",\n            payload: message,\n          },\n        });\n      }\n\n      const completedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"item.completed\",\n        eventId: completedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: completedStamp.createdAt,\n        threadId: context.session.threadId,\n        ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n        itemId: asRuntimeItemId(tool.itemId),\n        payload: {\n          itemType: tool.itemType,\n          status: itemStatus,\n          title: tool.title,\n          ...(tool.detail ? { detail: tool.detail } : {}),\n          ...(tool.agentId ? { agentId: tool.agentId } : {}),\n          ...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),\n          data: toolData,\n        },\n        providerRefs: nativeProviderRefs(context, {\n          providerItemId: tool.itemId,\n        }),\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/user\",\n          payload: message,\n        },\n      });\n\n      // The Workflow tool's result carries the run handles (runId, scriptPath,\n      // transcriptDir, sessionUrl). Attach them to the workflow's task agent so\n      // the next task.* payload advertises them to clients.\n      if (!toolResult.isError && tool.toolName.toLowerCase() === \"workflow\" && toolUseResult) {\n        const workflowTaskId = trimmedString(toolUseResult.taskId);\n        if (workflowTaskId) {\n          const runHandles: TaskRunHandles = {\n            ...(trimmedString(toolUseResult.runId)\n              ? { runId: trimmedString(toolUseResult.runId) }\n              : {}),\n            ...(trimmedString(toolUseResult.scriptPath)\n              ? { scriptPath: trimmedString(toolUseResult.scriptPath) }\n              : {}),\n            ...(trimmedString(toolUseResult.transcriptDir)\n              ? { transcriptDir: trimmedString(toolUseResult.transcriptDir) }\n              : {}),\n            ...(sanitizeSessionUrl(toolUseResult.sessionUrl)\n              ? { sessionUrl: sanitizeSessionUrl(toolUseResult.sessionUrl) }\n              : {}),\n          };\n          const existing = context.taskAgents.get(workflowTaskId);\n          context.taskAgents.set(workflowTaskId, {\n            taskId: workflowTaskId,\n            toolUseId: existing?.toolUseId ?? tool.itemId,\n            description: existing?.description,\n            subagentType: existing?.subagentType,\n            taskType: existing?.taskType ?? \"local_workflow\",\n            workflowName: existing?.workflowName,\n            skipTranscript: existing?.skipTranscript ?? false,\n            runHandles,\n            owningAgentId: existing?.owningAgentId,\n            model: existing?.model,\n            effort: existing?.effort,\n          });\n        }\n      }\n\n      if (\n        !toolResult.isError &&\n        applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult)\n      ) {\n        yield* emitClaudeTaskPlanUpdated(context, {\n          toolUseId: tool.itemId,\n          rawMethod: \"claude/user\",\n          rawPayload: message,\n        });\n      }\n\n      context.inFlightTools.delete(index);\n    }\n  });\n\n  const handleAssistantMessage = Effect.fn(\"handleAssistantMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"assistant\") {\n      return;\n    }\n\n    // Subagent-owned assistant snapshots (parent_tool_use_id set) are the\n    // subagent's own conversation, not the parent's. Emitting them created\n    // interleaved \"Agent N done\"-adjacent leak messages and spawned synthetic\n    // turns per subagent completion (which also reset the Working timer).\n    const assistantParentToolUseId = (message as { parent_tool_use_id?: string | null })\n      .parent_tool_use_id;\n    if (assistantParentToolUseId !== null && assistantParentToolUseId !== undefined) {\n      // The snapshot's message.model is the authoritative API model the\n      // subagent actually ran on — refine the seeded launch-time value.\n      const owningTaskId = agentIdForParentToolUse(context.taskAgents, assistantParentToolUseId);\n      const snapshotModel = trimmedString(message.message.model);\n      const owningAgent = owningTaskId ? context.taskAgents.get(owningTaskId) : undefined;\n      if (owningAgent && snapshotModel) {\n        owningAgent.model = snapshotModel;\n      }\n      context.lastAssistantUuid = message.uuid;\n      yield* updateResumeCursor(context);\n      return;\n    }\n\n    // Auto-start a synthetic turn for assistant messages that arrive without\n    // an active turn (e.g., background agent/subagent responses between user prompts).\n    if (!context.turnState) {\n      const turnId = TurnId.make(yield* randomUUIDv4);\n      const startedAt = yield* nowIso;\n      context.turnState = {\n        turnId,\n        startedAt,\n        synthetic: true,\n        items: [],\n        assistantTextBlocks: new Map(),\n        assistantTextBlockOrder: [],\n        capturedProposedPlanKeys: new Set(),\n        nextSyntheticAssistantBlockIndex: -1,\n      };\n      context.session = {\n        ...context.session,\n        status: \"running\",\n        activeTurnId: turnId,\n        updatedAt: startedAt,\n      };\n      const turnStartedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"turn.started\",\n        eventId: turnStartedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: turnStartedStamp.createdAt,\n        threadId: context.session.threadId,\n        turnId,\n        payload: {},\n        providerRefs: {\n          ...nativeProviderRefs(context),\n          providerTurnId: turnId,\n        },\n        raw: {\n          source: \"claude.sdk.message\",\n          method: \"claude/synthetic-turn-start\",\n          payload: {},\n        },\n      });\n    }\n\n    const content = message.message?.content;\n    if (Array.isArray(content)) {\n      for (const block of content) {\n        if (!block || typeof block !== \"object\") {\n          continue;\n        }\n        const toolUse = block as {\n          type?: unknown;\n          id?: unknown;\n          name?: unknown;\n          input?: unknown;\n        };\n        if (toolUse.type !== \"tool_use\" || toolUse.name !== \"ExitPlanMode\") {\n          continue;\n        }\n        const planMarkdown = extractExitPlanModePlan(toolUse.input);\n        if (!planMarkdown) {\n          continue;\n        }\n        yield* emitProposedPlanCompleted(context, {\n          planMarkdown,\n          toolUseId: typeof toolUse.id === \"string\" ? toolUse.id : undefined,\n          rawSource: \"claude.sdk.message\",\n          rawMethod: \"claude/assistant\",\n          rawPayload: message,\n        });\n      }\n    }\n\n    if (context.turnState) {\n      context.turnState.items.push(message.message);\n      yield* backfillAssistantTextBlocksFromSnapshot(context, message);\n    }\n\n    context.lastAssistantUuid = message.uuid;\n    yield* updateResumeCursor(context);\n  });\n\n  const handleResultMessage = Effect.fn(\"handleResultMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"result\") {\n      return;\n    }\n\n    const status = turnStatusFromResult(message);\n    const errorMessage = resultUserFacingError(message);\n\n    if (status === \"failed\") {\n      yield* emitRuntimeError(context, errorMessage ?? \"Claude turn failed.\");\n    }\n\n    yield* completeTurn(context, status, errorMessage, message);\n  });\n\n  /**\n   * Synthesizes per-member task.progress rows from the coordinator's\n   * workflow_progress array. Member identity is the stable slot\n   * `<coordinatorTaskId>:wf:<index>` (never the per-attempt agent id, which\n   * changes on retry and would split one member into duplicate rows).\n   * timelineBypass keeps these out of the parent chat; the Agents surface and\n   * workflow card consume them.\n   */\n  const emitWorkflowMemberProgress = Effect.fn(\"emitWorkflowMemberProgress\")(function* (\n    context: ClaudeSessionContext,\n    base: Omit<ProviderRuntimeEvent, \"type\" | \"payload\">,\n    message: Extract<SDKMessage, { type: \"system\"; subtype: \"task_progress\" }>,\n  ) {\n    const progress = parseWorkflowProgress(\n      (message as unknown as Record<string, unknown>).workflow_progress,\n    );\n    if (!progress) {\n      return;\n    }\n    const coordinatorId = message.task_id;\n    for (const entry of progress.agents) {\n      const memberTaskId = `${coordinatorId}:wf:${entry.index}`;\n      const status = workflowAgentStatus(entry);\n      // Material-transition filter: the wire repeats every member each tick.\n      // Emit only when something the client renders actually changed, so a\n      // 100-agent fleet costs ~1 event per changed member instead of 100\n      // per tick (review finding: unbounded event amplification).\n      const fingerprint = [\n        status,\n        entry.label ?? \"\",\n        entry.model ?? \"\",\n        entry.lastToolName ?? \"\",\n        entry.error ?? \"\",\n        entry.tokens ?? \"\",\n        entry.toolCalls ?? \"\",\n        entry.phaseIndex ?? \"\",\n        entry.phaseTitle ?? \"\",\n        entry.attempt ?? \"\",\n      ].join(\"\\u001f\");\n      if (context.workflowMemberFingerprints.get(memberTaskId) === fingerprint) {\n        continue;\n      }\n      context.workflowMemberFingerprints.set(memberTaskId, fingerprint);\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        ...base,\n        eventId: stamp.eventId,\n        createdAt: stamp.createdAt,\n        type: \"task.progress\",\n        payload: {\n          taskId: RuntimeTaskId.make(memberTaskId),\n          description: entry.label ?? `agent ${entry.index}`,\n          status,\n          ...(entry.error ? { error: entry.error } : {}),\n          ...(entry.label ? { title: entry.label } : {}),\n          ...(entry.model ? { model: entry.model } : {}),\n          ...(entry.lastToolName ? { lastToolName: entry.lastToolName } : {}),\n          ...(entry.tokens !== undefined\n            ? {\n                typedUsage: {\n                  totalTokens: entry.tokens,\n                  ...(entry.toolCalls !== undefined ? { toolUses: entry.toolCalls } : {}),\n                },\n              }\n            : {}),\n          parentAgentId: coordinatorId,\n          agentIndex: entry.index,\n          ...(entry.phaseIndex !== undefined ? { phaseIndex: entry.phaseIndex } : {}),\n          ...(entry.phaseTitle ? { phaseTitle: entry.phaseTitle } : {}),\n          ...(entry.attempt !== undefined ? { attempt: entry.attempt } : {}),\n          timelineBypass: true,\n        },\n      });\n    }\n  });\n\n  const handleSystemMessage = Effect.fn(\"handleSystemMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    if (message.type !== \"system\") {\n      return;\n    }\n\n    const stamp = yield* makeEventStamp();\n    const base = {\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n      providerRefs: nativeProviderRefs(context),\n      raw: {\n        source: \"claude.sdk.message\" as const,\n        method: sdkNativeMethod(message),\n        messageType: `${message.type}:${message.subtype}`,\n        payload: message,\n      },\n    };\n\n    // Undeclared-but-real subtypes (absent from the SDK's union, so they can't\n    // be switch cases): consumed intentionally without emitting, otherwise\n    // they fall through to the unknown-subtype warning and surface as spurious\n    // error rows in client work logs. `background_tasks_changed` is a roster\n    // snapshot ({tasks: [...]}) — the task_* lifecycle events carry the\n    // authoritative per-agent data and the typed background_tasks control\n    // request is the reconciliation source. `vcs_state_changed`\n    // ({kind: commit|push|rebase}) and `code_change_published`\n    // ({provider, url, repo}) are informational CLI notices; the work log\n    // already shows the underlying git/gh tool calls.\n    switch (message.subtype as string) {\n      case \"background_tasks_changed\":\n      case \"vcs_state_changed\":\n      case \"code_change_published\":\n        return;\n    }\n\n    switch (message.subtype) {\n      case \"init\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"session.configured\",\n          payload: {\n            config: message as Record<string, unknown>,\n          },\n        });\n        return;\n      case \"status\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"session.state.changed\",\n          payload: {\n            state: message.status === \"compacting\" ? \"waiting\" : \"running\",\n            reason: `status:${message.status ?? \"active\"}`,\n            detail: message,\n          },\n        });\n        return;\n      case \"compact_boundary\":\n        yield* emitThreadTokenUsage(\n          context,\n          compactBoundaryTokenUsageSnapshot(\n            message as unknown as Record<string, unknown>,\n            context.lastKnownContextWindow,\n            context.lastKnownTotalProcessedTokens,\n          ),\n          {\n            rawMethod: \"claude/system/compact_boundary\",\n            rawPayload: message,\n          },\n        );\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"thread.state.changed\",\n          payload: {\n            state: \"compacted\",\n            detail: message,\n          },\n        });\n        return;\n      case \"hook_started\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"hook.started\",\n          payload: {\n            hookId: message.hook_id,\n            hookName: message.hook_name,\n            hookEvent: message.hook_event,\n          },\n        });\n        return;\n      case \"hook_progress\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"hook.progress\",\n          payload: {\n            hookId: message.hook_id,\n            output: message.output,\n            stdout: message.stdout,\n            stderr: message.stderr,\n          },\n        });\n        return;\n      case \"hook_response\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"hook.completed\",\n          payload: {\n            hookId: message.hook_id,\n            outcome: message.outcome,\n            output: message.output,\n            stdout: message.stdout,\n            stderr: message.stderr,\n            ...(typeof message.exit_code === \"number\" ? { exitCode: message.exit_code } : {}),\n          },\n        });\n        return;\n      case \"task_started\": {\n        // A task launched by a tool that itself ran inside a subagent (the\n        // in-flight tool carries agentId from parent_tool_use_id) is\n        // agent-internal: a subagent's background shell, not parent work.\n        const launchingTool = message.tool_use_id\n          ? Array.from(context.inFlightTools.values()).find(\n              (tool) => tool.itemId === message.tool_use_id,\n            )\n          : undefined;\n        const owningAgentId = launchingTool?.agentId;\n        // Model/effort: the Agent tool's input carries explicit overrides;\n        // absent ones inherit the session's selection (SDK behavior).\n        // Subagent assistant snapshots later refine model with the\n        // authoritative API id. AgentInput.effort may be a named level or an\n        // integer.\n        const launchInput = launchingTool?.input;\n        const model =\n          trimmedString(launchInput?.model) ?? trimmedString(context.session.model ?? undefined);\n        const rawLaunchEffort = launchInput?.effort;\n        const effort =\n          trimmedString(rawLaunchEffort) ??\n          (typeof rawLaunchEffort === \"number\" && Number.isFinite(rawLaunchEffort)\n            ? String(rawLaunchEffort)\n            : context.currentEffort);\n        // Remember the agent identity so every later task.* payload for this\n        // taskId is self-describing (identity must survive activity retention).\n        context.taskAgents.set(message.task_id, {\n          taskId: message.task_id,\n          toolUseId: message.tool_use_id,\n          description: message.description,\n          subagentType: message.subagent_type,\n          taskType: message.task_type,\n          workflowName: message.workflow_name,\n          skipTranscript: message.skip_transcript === true,\n          runHandles: context.taskAgents.get(message.task_id)?.runHandles,\n          owningAgentId,\n          model,\n          effort,\n        });\n        context.liveTaskIds.add(message.task_id);\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"task.started\",\n          payload: {\n            taskId: RuntimeTaskId.make(message.task_id),\n            description: message.description,\n            ...(message.task_type ? { taskType: message.task_type } : {}),\n            ...(owningAgentId ? { agentId: owningAgentId } : {}),\n            ...(message.description ? { title: message.description } : {}),\n            ...(message.subagent_type ? { role: message.subagent_type } : {}),\n            ...(model ? { model } : {}),\n            ...(effort ? { effort } : {}),\n            ...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),\n            ...(message.workflow_name ? { workflowName: message.workflow_name } : {}),\n          },\n        });\n        return;\n      }\n      case \"task_progress\": {\n        yield* emitThreadTokenUsage(\n          context,\n          normalizeClaudeTaskProgressTokenUsage(message.usage, context),\n          {\n            rawMethod: \"claude/system/task_progress\",\n            rawPayload: message,\n          },\n        );\n        const linkage = taskLinkageFor(context.taskAgents, message.task_id);\n        const typedUsage = normalizeTaskUsage(message.usage);\n        // Phases ride on the coordinator's ONE progress row per tick. A\n        // separate phases-only row shared the stable ingestion activity id\n        // with this full row, and the thinner upsert overwrote usage and\n        // progress text (review finding).\n        const workflowPhases = parseWorkflowProgress(\n          (message as unknown as Record<string, unknown>).workflow_progress,\n        )?.phases;\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"task.progress\",\n          payload: {\n            taskId: RuntimeTaskId.make(message.task_id),\n            description: message.description,\n            ...(message.summary ? { summary: message.summary } : {}),\n            ...(message.usage ? { usage: message.usage } : {}),\n            ...(typedUsage ? { typedUsage } : {}),\n            ...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),\n            ...(workflowPhases && workflowPhases.length > 0 ? { phases: workflowPhases } : {}),\n            ...linkage,\n            ...(message.subagent_type ? { role: message.subagent_type } : {}),\n          },\n        });\n        yield* emitWorkflowMemberProgress(context, base, message);\n        return;\n      }\n      case \"task_updated\": {\n        // Status patch (killed/paused/backgrounded/end_time/error) — main\n        // previously dropped this on the floor, losing all transitions.\n        const patch = message.patch;\n        const status =\n          patch.status !== undefined ? CLAUDE_TASK_PATCH_STATUS[patch.status] : undefined;\n        if (status === \"completed\" || status === \"failed\" || status === \"cancelled\") {\n          context.liveTaskIds.delete(message.task_id);\n        }\n        const endedAt =\n          typeof patch.end_time === \"number\" && Number.isFinite(patch.end_time)\n            ? DateTime.formatIso(DateTime.makeUnsafe(patch.end_time))\n            : undefined;\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"task.updated\",\n          payload: {\n            taskId: RuntimeTaskId.make(message.task_id),\n            ...(status ? { status } : {}),\n            ...(patch.description ? { description: patch.description } : {}),\n            ...(patch.error ? { error: patch.error } : {}),\n            ...(endedAt ? { endedAt } : {}),\n            ...(patch.is_backgrounded !== undefined\n              ? { isBackgrounded: patch.is_backgrounded }\n              : {}),\n            ...taskLinkageFor(context.taskAgents, message.task_id),\n          },\n        });\n        return;\n      }\n      case \"task_notification\": {\n        context.liveTaskIds.delete(message.task_id);\n        yield* emitThreadTokenUsage(\n          context,\n          normalizeClaudeTaskProgressTokenUsage(message.usage, context),\n          {\n            rawMethod: \"claude/system/task_notification\",\n            rawPayload: message,\n          },\n        );\n        const typedUsage = normalizeTaskUsage(message.usage);\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"task.completed\",\n          payload: {\n            taskId: RuntimeTaskId.make(message.task_id),\n            status: message.status,\n            ...(message.summary ? { summary: message.summary } : {}),\n            ...(message.usage ? { usage: message.usage } : {}),\n            ...(typedUsage ? { typedUsage } : {}),\n            ...(message.output_file ? { outputFile: message.output_file } : {}),\n            ...taskLinkageFor(context.taskAgents, message.task_id),\n          },\n        });\n        return;\n      }\n      case \"files_persisted\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"files.persisted\",\n          payload: {\n            files: Array.isArray(message.files)\n              ? message.files.map((file: { filename: string; file_id: string }) => ({\n                  filename: file.filename,\n                  fileId: file.file_id,\n                }))\n              : [],\n            ...(Array.isArray(message.failed)\n              ? {\n                  failed: message.failed.map((entry: { filename: string; error: string }) => ({\n                    filename: entry.filename,\n                    error: entry.error,\n                  })),\n                }\n              : {}),\n          },\n        });\n        return;\n      case \"thinking_tokens\":\n        return;\n      case \"api_retry\":\n        // Transport-level retry heartbeat. Surfacing each attempt as a\n        // warning row spammed the work log (10 rows during a 502 storm);\n        // the terminal result/error path reports the actual failure. Keep\n        // the session visibly alive instead.\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"session.state.changed\",\n          payload: {\n            state: \"running\",\n            reason: `api_retry:${message.attempt}/${message.max_retries}`,\n          },\n        });\n        return;\n      case \"session_state_changed\":\n        // Authoritative turn-over signal from the CLI.\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"session.state.changed\",\n          payload: {\n            state:\n              message.state === \"running\"\n                ? \"running\"\n                : message.state === \"requires_action\"\n                  ? \"waiting\"\n                  : \"ready\",\n            reason: `session_state:${message.state}`,\n          },\n        });\n        return;\n      case \"notification\":\n        // User-facing CLI notification (e.g. context-limit warnings). Only\n        // high-priority ones warrant a work-log row.\n        if (message.priority === \"high\" || message.priority === \"immediate\") {\n          yield* emitRuntimeWarning(context, message.text, message);\n        }\n        return;\n      // Inner protocol/UX details with no T3 surface today — consumed\n      // deliberately so they don't masquerade as unknown-subtype warnings.\n      case \"model_refusal_fallback\":\n      case \"local_command_output\":\n      case \"plugin_install\":\n      case \"commands_changed\":\n      case \"memory_recall\":\n      case \"elicitation_complete\":\n        return;\n      case \"permission_denied\":\n        yield* offerRuntimeEvent({\n          ...base,\n          type: \"tool.denied\",\n          payload: {\n            toolName: message.tool_name,\n            ...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),\n            ...(message.decision_reason ? { reason: message.decision_reason } : {}),\n            ...(message.agent_id ? { agentId: message.agent_id } : {}),\n          },\n        });\n        return;\n      case \"mirror_error\":\n        yield* emitRuntimeError(\n          context,\n          `Claude workspace mirror error: ${message.error}`,\n          message,\n        );\n        return;\n      default: {\n        // Exhaustiveness guard: every subtype in the SDK's typed union is\n        // handled above, so `message` narrows to never here — a new SDK\n        // release adding a subtype fails this typecheck instead of silently\n        // warning at runtime. The runtime fallback still catches undeclared\n        // wire-only subtypes (like background_tasks_changed used to be).\n        message satisfies never;\n        const unknownMessage = message as never as { subtype: string };\n        yield* emitRuntimeWarning(\n          context,\n          describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),\n          message,\n        );\n        return;\n      }\n    }\n  });\n\n  const handleSdkTelemetryMessage = Effect.fn(\"handleSdkTelemetryMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    const stamp = yield* makeEventStamp();\n    const base = {\n      eventId: stamp.eventId,\n      provider: PROVIDER,\n      createdAt: stamp.createdAt,\n      threadId: context.session.threadId,\n      ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n      providerRefs: nativeProviderRefs(context),\n      raw: {\n        source: \"claude.sdk.message\" as const,\n        method: sdkNativeMethod(message),\n        messageType: message.type,\n        payload: message,\n      },\n    };\n\n    if (message.type === \"tool_progress\") {\n      yield* offerRuntimeEvent({\n        ...base,\n        type: \"tool.progress\",\n        payload: {\n          toolUseId: message.tool_use_id,\n          toolName: message.tool_name,\n          elapsedSeconds: message.elapsed_time_seconds,\n          ...(message.task_id ? { taskId: RuntimeTaskId.make(message.task_id) } : {}),\n          ...(message.parent_tool_use_id !== null\n            ? { parentToolUseId: message.parent_tool_use_id }\n            : {}),\n        },\n      });\n      return;\n    }\n\n    if (message.type === \"tool_use_summary\") {\n      yield* offerRuntimeEvent({\n        ...base,\n        type: \"tool.summary\",\n        payload: {\n          summary: message.summary,\n          ...(message.preceding_tool_use_ids.length > 0\n            ? {\n                precedingToolUseIds: message.preceding_tool_use_ids,\n              }\n            : {}),\n        },\n      });\n      return;\n    }\n\n    if (message.type === \"auth_status\") {\n      yield* offerRuntimeEvent({\n        ...base,\n        type: \"auth.status\",\n        payload: {\n          isAuthenticating: message.isAuthenticating,\n          output: message.output,\n          ...(message.error ? { error: message.error } : {}),\n        },\n      });\n      return;\n    }\n\n    if (message.type === \"rate_limit_event\") {\n      yield* offerRuntimeEvent({\n        ...base,\n        type: \"account.rate-limits.updated\",\n        payload: {\n          rateLimits: message,\n        },\n      });\n      return;\n    }\n  });\n\n  const handleSdkMessage = Effect.fn(\"handleSdkMessage\")(function* (\n    context: ClaudeSessionContext,\n    message: SDKMessage,\n  ) {\n    yield* logNativeSdkMessage(context, message);\n    yield* ensureThreadId(context, message);\n\n    switch (message.type) {\n      case \"stream_event\":\n        yield* handleStreamEvent(context, message);\n        return;\n      case \"user\":\n        yield* handleUserMessage(context, message);\n        return;\n      case \"assistant\":\n        yield* handleAssistantMessage(context, message);\n        return;\n      case \"result\":\n        yield* handleResultMessage(context, message);\n        return;\n      case \"system\":\n        yield* handleSystemMessage(context, message);\n        return;\n      case \"tool_progress\":\n      case \"tool_use_summary\":\n      case \"auth_status\":\n      case \"rate_limit_event\":\n        yield* handleSdkTelemetryMessage(context, message);\n        return;\n      // Composer prompt suggestions have no T3 surface; consumed deliberately.\n      case \"prompt_suggestion\":\n        return;\n      default: {\n        // Exhaustiveness guard (see handleSystemMessage): new SDK top-level\n        // message types fail typecheck here instead of warning at runtime.\n        message satisfies never;\n        const unknownMessage = message as never as { type: string };\n        yield* emitRuntimeWarning(\n          context,\n          describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),\n          message,\n        );\n        return;\n      }\n    }\n  });\n\n  const runSdkStream = (\n    context: ClaudeSessionContext,\n  ): Effect.Effect<void, ProviderAdapterProcessError> =>\n    Stream.fromAsyncIterable(\n      context.query,\n      (cause) =>\n        new ProviderAdapterProcessError({\n          provider: PROVIDER,\n          threadId: context.session.threadId,\n          detail: \"Claude runtime stream failed.\",\n          cause,\n        }),\n    ).pipe(\n      Stream.takeWhile(() => !context.stopped),\n      Stream.runForEach((message) =>\n        handleSdkMessage(context, message).pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProviderAdapterProcessError({\n                provider: PROVIDER,\n                threadId: context.session.threadId,\n                detail: \"Failed to process Claude runtime event.\",\n                cause,\n              }),\n          ),\n        ),\n      ),\n    );\n\n  const handleStreamExit = Effect.fn(\"handleStreamExit\")(function* (\n    context: ClaudeSessionContext,\n    exit: Exit.Exit<void, ProviderAdapterProcessError>,\n  ) {\n    if (context.stopped) {\n      return;\n    }\n\n    if (Exit.isFailure(exit)) {\n      if (isClaudeInterruptedCause(exit.cause)) {\n        if (context.turnState) {\n          yield* completeTurn(context, \"interrupted\", \"Claude runtime interrupted.\");\n        }\n      } else {\n        const failures = exit.cause.reasons.flatMap((reason) =>\n          Cause.isFailReason(reason) ? [reason.error] : [],\n        );\n        const message = failures[0]?.detail ?? \"Claude runtime stream failed.\";\n        yield* emitRuntimeError(context, message, {\n          failureCount: failures.length,\n          failureTags: failures.map((failure) => failure._tag),\n        });\n        yield* completeTurn(context, \"failed\", message);\n      }\n    } else if (context.turnState) {\n      yield* completeTurn(context, \"interrupted\", \"Claude runtime stream ended.\");\n    }\n\n    yield* stopSessionInternal(context, {\n      emitExitEvent: true,\n    });\n  });\n\n  const stopSessionInternal = Effect.fn(\"stopSessionInternal\")(function* (\n    context: ClaudeSessionContext,\n    options?: { readonly emitExitEvent?: boolean },\n  ) {\n    if (context.stopped) return;\n\n    context.stopped = true;\n\n    for (const [requestId, pending] of context.pendingApprovals) {\n      yield* Deferred.succeed(pending.decision, \"cancel\");\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"request.resolved\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n        requestId: asRuntimeRequestId(requestId),\n        payload: {\n          requestType: pending.requestType,\n          decision: \"cancel\",\n        },\n        providerRefs: nativeProviderRefs(context),\n      });\n    }\n    context.pendingApprovals.clear();\n\n    if (context.turnState) {\n      yield* completeTurn(context, \"interrupted\", \"Session stopped.\");\n    }\n\n    yield* Queue.shutdown(context.promptQueue);\n\n    const streamFiber = context.streamFiber;\n    context.streamFiber = undefined;\n    if (streamFiber && streamFiber.pollUnsafe() === undefined) {\n      yield* Fiber.interrupt(streamFiber);\n    }\n\n    yield* Effect.try({\n      try: () => context.query.close(),\n      catch: (cause) =>\n        new ProviderAdapterProcessError({\n          provider: PROVIDER,\n          threadId: context.session.threadId,\n          detail: \"Failed to close Claude runtime query.\",\n          cause,\n        }),\n    }).pipe(\n      Effect.catch((error) =>\n        emitRuntimeError(context, \"Failed to close Claude runtime query.\", {\n          errorTag: error._tag,\n          provider: error.provider,\n          threadId: error.threadId,\n          detail: error.detail,\n        }),\n      ),\n    );\n\n    const updatedAt = yield* nowIso;\n    context.session = {\n      ...context.session,\n      status: \"closed\",\n      activeTurnId: undefined,\n      updatedAt,\n    };\n\n    if (options?.emitExitEvent !== false) {\n      const stamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"session.exited\",\n        eventId: stamp.eventId,\n        provider: PROVIDER,\n        createdAt: stamp.createdAt,\n        threadId: context.session.threadId,\n        payload: {\n          reason: \"Session stopped\",\n          exitKind: \"graceful\",\n        },\n        providerRefs: {},\n      });\n    }\n\n    sessions.delete(context.session.threadId);\n  });\n\n  const requireSession = (\n    threadId: ThreadId,\n  ): Effect.Effect<ClaudeSessionContext, ProviderAdapterError> => {\n    const context = sessions.get(threadId);\n    if (!context) {\n      return Effect.fail(\n        new ProviderAdapterSessionNotFoundError({\n          provider: PROVIDER,\n          threadId,\n        }),\n      );\n    }\n    if (context.stopped || context.session.status === \"closed\") {\n      return Effect.fail(\n        new ProviderAdapterSessionClosedError({\n          provider: PROVIDER,\n          threadId,\n        }),\n      );\n    }\n    return Effect.succeed(context);\n  };\n\n  const startSession: ClaudeAdapterShape[\"startSession\"] = Effect.fn(\"startSession\")(\n    function* (input) {\n      if (input.provider !== undefined && input.provider !== PROVIDER) {\n        return yield* new ProviderAdapterValidationError({\n          provider: PROVIDER,\n          operation: \"startSession\",\n          issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,\n        });\n      }\n\n      const existingContext = sessions.get(input.threadId);\n      if (existingContext) {\n        yield* Effect.logWarning(\"claude.session.replacing\", {\n          threadId: input.threadId,\n          existingSessionStatus: existingContext.session.status,\n          reason: \"startSession called with existing active session\",\n        });\n        yield* stopSessionInternal(existingContext, {\n          emitExitEvent: false,\n        }).pipe(\n          // Replacement cleanup is best-effort: never block the new session on\n          // either typed failures or unexpected defects from tearing down the old one.\n          Effect.catchCause((cause) =>\n            Effect.logWarning(\"claude.session.replace.stop-failed\", {\n              threadId: input.threadId,\n              cause,\n            }),\n          ),\n        );\n      }\n\n      const startedAt = yield* nowIso;\n      const resumeState = readClaudeResumeState(input.resumeCursor);\n      const threadId = input.threadId;\n      const existingResumeSessionId = resumeState?.resume;\n      const newSessionId = existingResumeSessionId === undefined ? yield* randomUUIDv4 : undefined;\n      const sessionId = existingResumeSessionId ?? newSessionId;\n\n      const runtimeContext = yield* Effect.context<never>();\n      const runFork = Effect.runForkWith(runtimeContext);\n      const runPromise = Effect.runPromiseWith(runtimeContext);\n\n      const promptQueue = yield* Queue.unbounded<PromptQueueItem>();\n      const prompt = Stream.fromQueue(promptQueue).pipe(\n        Stream.filter((item) => item.type === \"message\"),\n        Stream.map((item) => item.message),\n        Stream.catchCause((cause) =>\n          Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),\n        ),\n        Stream.toAsyncIterable,\n      );\n\n      const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();\n      const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();\n      const inFlightTools = new Map<number, ToolInFlight>();\n      const claudeTasks = new Map<string, ClaudeTaskState>();\n      const taskAgents = new Map<string, ClaudeTaskAgentState>();\n      const workflowMemberFingerprints = new Map<string, string>();\n      const liveTaskIds = new Set<string>();\n\n      const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);\n\n      /**\n       * Handle AskUserQuestion tool calls by emitting a `user-input.requested`\n       * runtime event and waiting for the user to respond via `respondToUserInput`.\n       */\n      const handleAskUserQuestion = Effect.fn(\"handleAskUserQuestion\")(function* (\n        context: ClaudeSessionContext,\n        toolInput: Record<string, unknown>,\n        callbackOptions: {\n          readonly signal: AbortSignal;\n          readonly toolUseID?: string;\n        },\n      ) {\n        const requestId = ApprovalRequestId.make(yield* randomUUIDv4);\n\n        // Parse questions from the SDK's AskUserQuestion input.\n        // `id` MUST equal the full question text — Claude SDK >= 2.1.121 looks\n        // up answers by question text in `mapToolResultToToolResultBlockParam`,\n        // so the key the UI uses to keep its draft answer must match the SDK's\n        // expected lookup key. See https://github.com/pingdotgg/t3code/issues/2388\n        const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : [];\n        const questions: Array<UserInputQuestion> = rawQuestions.map(\n          (q: Record<string, unknown>, idx: number) => ({\n            id: typeof q.question === \"string\" && q.question.length > 0 ? q.question : `q-${idx}`,\n            header: typeof q.header === \"string\" ? q.header : `Question ${idx + 1}`,\n            question: typeof q.question === \"string\" ? q.question : \"\",\n            options: Array.isArray(q.options)\n              ? q.options.map((opt: Record<string, unknown>) => ({\n                  label: typeof opt.label === \"string\" ? opt.label : \"\",\n                  description: typeof opt.description === \"string\" ? opt.description : \"\",\n                }))\n              : [],\n            multiSelect: typeof q.multiSelect === \"boolean\" ? q.multiSelect : false,\n          }),\n        );\n\n        const answersDeferred = yield* Deferred.make<ProviderUserInputAnswers>();\n        let aborted = false;\n        const pendingInput: PendingUserInput = {\n          questions,\n          answers: answersDeferred,\n        };\n\n        // Emit user-input.requested so the UI can present the questions.\n        const requestedStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"user-input.requested\",\n          eventId: requestedStamp.eventId,\n          provider: PROVIDER,\n          createdAt: requestedStamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState\n            ? {\n                turnId: asCanonicalTurnId(context.turnState.turnId),\n              }\n            : {}),\n          requestId: asRuntimeRequestId(requestId),\n          payload: { questions },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: callbackOptions.toolUseID,\n          }),\n          raw: {\n            source: \"claude.sdk.permission\",\n            method: \"canUseTool/AskUserQuestion\",\n            payload: {\n              toolName: \"AskUserQuestion\",\n              input: toolInput,\n            },\n          },\n        });\n\n        pendingUserInputs.set(requestId, pendingInput);\n\n        // Handle abort (e.g. turn interrupted while waiting for user input).\n        const onAbort = () => {\n          if (!pendingUserInputs.has(requestId)) {\n            return;\n          }\n          aborted = true;\n          pendingUserInputs.delete(requestId);\n          runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));\n        };\n        callbackOptions.signal.addEventListener(\"abort\", onAbort, {\n          once: true,\n        });\n\n        // Block until the user provides answers.\n        const answers = yield* Deferred.await(answersDeferred);\n        pendingUserInputs.delete(requestId);\n\n        // Emit user-input.resolved so the UI knows the interaction completed.\n        const resolvedStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"user-input.resolved\",\n          eventId: resolvedStamp.eventId,\n          provider: PROVIDER,\n          createdAt: resolvedStamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState\n            ? {\n                turnId: asCanonicalTurnId(context.turnState.turnId),\n              }\n            : {}),\n          requestId: asRuntimeRequestId(requestId),\n          payload: { answers },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: callbackOptions.toolUseID,\n          }),\n          raw: {\n            source: \"claude.sdk.permission\",\n            method: \"canUseTool/AskUserQuestion/resolved\",\n            payload: { answers },\n          },\n        });\n\n        if (aborted) {\n          return {\n            behavior: \"deny\",\n            message: \"User cancelled tool execution.\",\n          } satisfies PermissionResult;\n        }\n\n        // Return the answers to the SDK in the expected format:\n        // { questions: [...], answers: { questionText: selectedLabel } }\n        return {\n          behavior: \"allow\",\n          updatedInput: {\n            questions: toolInput.questions,\n            answers,\n          },\n        } satisfies PermissionResult;\n      });\n\n      const canUseToolEffect = Effect.fn(\"canUseTool\")(function* (\n        toolName: Parameters<CanUseTool>[0],\n        toolInput: Parameters<CanUseTool>[1],\n        callbackOptions: Parameters<CanUseTool>[2],\n      ) {\n        const context = yield* Ref.get(contextRef);\n        if (!context) {\n          return {\n            behavior: \"deny\",\n            message: \"Claude session context is unavailable.\",\n          } satisfies PermissionResult;\n        }\n\n        // Handle AskUserQuestion: surface clarifying questions to the\n        // user via the user-input runtime event channel, regardless of\n        // runtime mode (plan mode relies on this heavily).\n        if (toolName === \"AskUserQuestion\") {\n          return yield* handleAskUserQuestion(context, toolInput, callbackOptions);\n        }\n\n        if (toolName === \"ExitPlanMode\") {\n          const planMarkdown = extractExitPlanModePlan(toolInput);\n          if (planMarkdown) {\n            yield* emitProposedPlanCompleted(context, {\n              planMarkdown,\n              toolUseId: callbackOptions.toolUseID,\n              rawSource: \"claude.sdk.permission\",\n              rawMethod: \"canUseTool/ExitPlanMode\",\n              rawPayload: {\n                toolName,\n                input: toolInput,\n              },\n            });\n          }\n\n          return {\n            behavior: \"deny\",\n            message:\n              \"The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.\",\n          } satisfies PermissionResult;\n        }\n\n        const runtimeMode = input.runtimeMode ?? \"full-access\";\n        if (runtimeMode === \"full-access\") {\n          return {\n            behavior: \"allow\",\n            updatedInput: toolInput,\n          } satisfies PermissionResult;\n        }\n\n        const requestId = ApprovalRequestId.make(yield* randomUUIDv4);\n        const requestType = classifyRequestType(toolName);\n        const detail = summarizeToolRequest(toolName, toolInput);\n        const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();\n        const pendingApproval: PendingApproval = {\n          requestType,\n          detail,\n          decision: decisionDeferred,\n          ...(callbackOptions.suggestions ? { suggestions: callbackOptions.suggestions } : {}),\n        };\n\n        const requestedStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"request.opened\",\n          eventId: requestedStamp.eventId,\n          provider: PROVIDER,\n          createdAt: requestedStamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n          requestId: asRuntimeRequestId(requestId),\n          payload: {\n            requestType,\n            detail,\n            args: {\n              toolName,\n              input: toolInput,\n              ...(callbackOptions.toolUseID ? { toolUseId: callbackOptions.toolUseID } : {}),\n            },\n          },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: callbackOptions.toolUseID,\n          }),\n          raw: {\n            source: \"claude.sdk.permission\",\n            method: \"canUseTool/request\",\n            payload: {\n              toolName,\n              input: toolInput,\n            },\n          },\n        });\n\n        pendingApprovals.set(requestId, pendingApproval);\n\n        const onAbort = () => {\n          if (!pendingApprovals.has(requestId)) {\n            return;\n          }\n          pendingApprovals.delete(requestId);\n          runFork(Deferred.succeed(decisionDeferred, \"cancel\"));\n        };\n\n        callbackOptions.signal.addEventListener(\"abort\", onAbort, {\n          once: true,\n        });\n\n        const decision = yield* Deferred.await(decisionDeferred);\n        pendingApprovals.delete(requestId);\n\n        const resolvedStamp = yield* makeEventStamp();\n        yield* offerRuntimeEvent({\n          type: \"request.resolved\",\n          eventId: resolvedStamp.eventId,\n          provider: PROVIDER,\n          createdAt: resolvedStamp.createdAt,\n          threadId: context.session.threadId,\n          ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),\n          requestId: asRuntimeRequestId(requestId),\n          payload: {\n            requestType,\n            decision,\n          },\n          providerRefs: nativeProviderRefs(context, {\n            providerItemId: callbackOptions.toolUseID,\n          }),\n          raw: {\n            source: \"claude.sdk.permission\",\n            method: \"canUseTool/decision\",\n            payload: {\n              decision,\n            },\n          },\n        });\n\n        if (decision === \"accept\" || decision === \"acceptForSession\") {\n          return {\n            behavior: \"allow\",\n            updatedInput: toolInput,\n            ...(decision === \"acceptForSession\" && pendingApproval.suggestions\n              ? {\n                  updatedPermissions: [...pendingApproval.suggestions],\n                }\n              : {}),\n          } satisfies PermissionResult;\n        }\n\n        return {\n          behavior: \"deny\",\n          message:\n            decision === \"cancel\"\n              ? \"User cancelled tool execution.\"\n              : \"User declined tool execution.\",\n        } satisfies PermissionResult;\n      });\n\n      const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) =>\n        runPromise(canUseToolEffect(toolName, toolInput, callbackOptions));\n\n      const claudeBinaryPath = claudeSdkExecutablePath;\n      const extraArgs = parseCliArgs(claudeSettings.launchArgs).flags;\n      const modelSelection =\n        input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;\n      const caps = getClaudeModelCapabilities(modelSelection?.model);\n      const descriptors = getProviderOptionDescriptors({ caps });\n      const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;\n      const initialContextWindow = selectedClaudeContextWindow(modelSelection);\n      const rawEffort = getModelSelectionStringOptionValue(modelSelection, \"effort\");\n      const effort = resolveClaudeEffort(caps, rawEffort) ?? null;\n      const fastModeSupported = descriptors.some(\n        (descriptor) => descriptor.type === \"boolean\" && descriptor.id === \"fastMode\",\n      );\n      const thinkingSupported = descriptors.some(\n        (descriptor) => descriptor.type === \"boolean\" && descriptor.id === \"thinking\",\n      );\n      const fastMode =\n        getModelSelectionBooleanOptionValue(modelSelection, \"fastMode\") === true &&\n        fastModeSupported;\n      const thinking = thinkingSupported\n        ? getModelSelectionBooleanOptionValue(modelSelection, \"thinking\")\n        : undefined;\n      const ultracode = isClaudeUltracodeEffort(effort);\n      const effectiveEffort = getEffectiveClaudeAgentEffort(effort, modelSelection?.model);\n      const runtimeModeToPermission: Record<string, PermissionMode> = {\n        \"auto-accept-edits\": \"acceptEdits\",\n        auto: \"auto\",\n        \"full-access\": \"bypassPermissions\",\n      };\n      const permissionMode = runtimeModeToPermission[input.runtimeMode];\n      const settings = {\n        ...(typeof thinking === \"boolean\" ? { alwaysThinkingEnabled: thinking } : {}),\n        ...(fastMode ? { fastMode: true } : {}),\n        ...(ultracode ? { ultracode: true } : {}),\n      };\n      const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);\n      const queryOptions: ClaudeQueryOptions = {\n        ...(input.cwd ? { cwd: input.cwd } : {}),\n        ...(apiModelId ? { model: apiModelId } : {}),\n        pathToClaudeCodeExecutable: claudeBinaryPath,\n        systemPrompt: { type: \"preset\", preset: \"claude_code\" },\n        settingSources: [...CLAUDE_SETTING_SOURCES],\n        // `ultracode` is a Claude Code setting, not an API effort level. It is\n        // normalized to `xhigh` above and paired with `settings.ultracode`.\n        ...(effectiveEffort\n          ? {\n              effort: effectiveEffort as unknown as NonNullable<ClaudeQueryOptions[\"effort\"]>,\n            }\n          : {}),\n        ...(permissionMode ? { permissionMode } : {}),\n        ...(permissionMode === \"bypassPermissions\"\n          ? { allowDangerouslySkipPermissions: true }\n          : {}),\n        ...(Object.keys(settings).length > 0 ? { settings } : {}),\n        ...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}),\n        ...(newSessionId ? { sessionId: newSessionId } : {}),\n        includePartialMessages: true,\n        canUseTool,\n        env: claudeEnvironment,\n        ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),\n        ...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),\n        ...(mcpSession\n          ? {\n              mcpServers: {\n                \"synaptic-code\": {\n                  type: \"http\",\n                  url: mcpSession.endpoint,\n                  headers: {\n                    Authorization: mcpSession.authorizationHeader,\n                  },\n                },\n              },\n            }\n          : {}),\n      };\n\n      yield* Effect.annotateCurrentSpan({\n        \"provider.kind\": PROVIDER,\n        \"provider.thread_id\": threadId,\n        \"provider.runtime_mode\": input.runtimeMode,\n        \"claude.resume.source\":\n          existingResumeSessionId !== undefined ? \"resume-session\" : \"generated-session\",\n        \"claude.resume.thread_id\": resumeState?.threadId ?? \"\",\n        \"claude.resume.session_id\": existingResumeSessionId ?? \"\",\n        \"claude.resume.session_at\": resumeState?.resumeSessionAt ?? \"\",\n        \"claude.resume.turn_count\": resumeState?.turnCount ?? -1,\n        \"claude.query.cwd\": input.cwd ?? \"\",\n        \"claude.query.model\": apiModelId ?? \"\",\n        \"claude.query.effort\": effectiveEffort ?? \"\",\n        \"claude.query.permission_mode\": permissionMode ?? \"\",\n        \"claude.query.allow_dangerously_skip_permissions\": permissionMode === \"bypassPermissions\",\n        \"claude.query.resume\": existingResumeSessionId ?? \"\",\n        \"claude.query.session_id\": newSessionId ?? \"\",\n        \"claude.query.include_partial_messages\": true,\n        \"claude.query.additional_directories\": input.cwd ? [input.cwd] : [],\n        \"claude.query.setting_sources\": [...CLAUDE_SETTING_SOURCES],\n        \"claude.query.settings_json\": encodeJsonStringForDiagnostics(settings) ?? \"\",\n        \"claude.query.extra_args_json\": encodeJsonStringForDiagnostics(extraArgs) ?? \"\",\n        \"claude.query.path_to_executable\": claudeBinaryPath,\n      });\n\n      const queryRuntime = yield* Effect.try({\n        try: () =>\n          createQuery({\n            prompt,\n            options: queryOptions,\n          }),\n        catch: (cause) =>\n          new ProviderAdapterProcessError({\n            provider: PROVIDER,\n            threadId,\n            detail: \"Failed to start Claude runtime session.\",\n            cause,\n          }),\n      });\n\n      const session: ProviderSession = {\n        threadId,\n        provider: PROVIDER,\n        providerInstanceId: boundInstanceId,\n        status: \"ready\",\n        runtimeMode: input.runtimeMode,\n        ...(input.cwd ? { cwd: input.cwd } : {}),\n        ...(modelSelection?.model ? { model: modelSelection.model } : {}),\n        ...(threadId ? { threadId } : {}),\n        resumeCursor: {\n          ...(threadId ? { threadId } : {}),\n          ...(sessionId ? { resume: sessionId } : {}),\n          ...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}),\n          turnCount: resumeState?.turnCount ?? 0,\n        },\n        createdAt: startedAt,\n        updatedAt: startedAt,\n      };\n\n      const context: ClaudeSessionContext = {\n        session,\n        promptQueue,\n        query: queryRuntime,\n        streamFiber: undefined,\n        startedAt,\n        basePermissionMode: permissionMode,\n        currentApiModelId: apiModelId,\n        currentEffort: effectiveEffort ?? undefined,\n        resumeSessionId: sessionId,\n        pendingApprovals,\n        pendingUserInputs,\n        turns: [],\n        inFlightTools,\n        claudeTasks,\n        taskAgents,\n        workflowMemberFingerprints,\n        liveTaskIds,\n        turnState: undefined,\n        lastKnownContextWindow: initialContextWindow,\n        lastKnownTokenUsage: undefined,\n        lastKnownTotalProcessedTokens: undefined,\n        lastAssistantUuid: resumeState?.resumeSessionAt,\n        lastThreadStartedId: undefined,\n        stopped: false,\n      };\n      yield* Ref.set(contextRef, context);\n      sessions.set(threadId, context);\n\n      const sessionStartedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"session.started\",\n        eventId: sessionStartedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: sessionStartedStamp.createdAt,\n        threadId,\n        payload: input.resumeCursor !== undefined ? { resume: input.resumeCursor } : {},\n        providerRefs: {},\n      });\n\n      const configuredStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"session.configured\",\n        eventId: configuredStamp.eventId,\n        provider: PROVIDER,\n        createdAt: configuredStamp.createdAt,\n        threadId,\n        payload: {\n          config: {\n            ...(apiModelId ? { model: apiModelId } : {}),\n            ...(input.cwd ? { cwd: input.cwd } : {}),\n            ...(effectiveEffort ? { effort: effectiveEffort } : {}),\n            ...(permissionMode ? { permissionMode } : {}),\n            ...(fastMode ? { fastMode: true } : {}),\n          },\n        },\n        providerRefs: {},\n      });\n\n      const readyStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"session.state.changed\",\n        eventId: readyStamp.eventId,\n        provider: PROVIDER,\n        createdAt: readyStamp.createdAt,\n        threadId,\n        payload: {\n          state: \"ready\",\n        },\n        providerRefs: {},\n      });\n\n      let streamFiber: Fiber.Fiber<void, never>;\n      streamFiber = runFork(\n        Effect.exit(runSdkStream(context)).pipe(\n          Effect.flatMap((exit) => {\n            if (context.stopped) {\n              return Effect.void;\n            }\n            if (context.streamFiber === streamFiber) {\n              context.streamFiber = undefined;\n            }\n            return handleStreamExit(context, exit).pipe(\n              Effect.catch((cause) =>\n                Effect.logError(\"Failed to close Claude runtime stream.\", { cause }),\n              ),\n            );\n          }),\n        ),\n      );\n      context.streamFiber = streamFiber;\n      streamFiber.addObserver(() => {\n        if (context.streamFiber === streamFiber) {\n          context.streamFiber = undefined;\n        }\n      });\n\n      return {\n        ...session,\n      };\n    },\n  );\n\n  const sendTurn: ClaudeAdapterShape[\"sendTurn\"] = Effect.fn(\"sendTurn\")(function* (input) {\n    const context = yield* requireSession(input.threadId);\n    const modelSelection =\n      input.modelSelection !== undefined && input.modelSelection.instanceId === boundInstanceId\n        ? input.modelSelection\n        : undefined;\n\n    // A sendTurn while a real turn is running is a steer: the message is\n    // queued into the live SDK agent loop and the work continues as the same\n    // turn — no synthetic turn boundary. Stale synthetic turns (from\n    // background agent responses between user prompts) are auto-closed\n    // instead, so they don't block the user's next turn.\n    const steeringTurnState =\n      context.turnState && context.turnState.synthetic !== true ? context.turnState : null;\n    if (context.turnState && steeringTurnState === null) {\n      yield* completeTurn(context, \"completed\");\n    }\n\n    if (modelSelection?.model) {\n      const apiModelId = resolveClaudeApiModelId(modelSelection);\n      if (context.currentApiModelId !== apiModelId) {\n        yield* Effect.tryPromise({\n          try: () => context.query.setModel(apiModelId),\n          catch: (cause) => toRequestError(input.threadId, \"turn/setModel\", cause),\n        });\n        context.currentApiModelId = apiModelId;\n      }\n      context.session = {\n        ...context.session,\n        model: modelSelection.model,\n      };\n      const turnCaps = getClaudeModelCapabilities(modelSelection.model);\n      const turnEffort = resolveClaudeEffort(\n        turnCaps,\n        getModelSelectionStringOptionValue(modelSelection, \"effort\"),\n      );\n      context.currentEffort =\n        getEffectiveClaudeAgentEffort(turnEffort ?? null, modelSelection.model) ?? undefined;\n    }\n\n    // Apply interaction mode by switching the SDK's permission mode.\n    // \"plan\" maps directly to the SDK's \"plan\" permission mode;\n    // \"default\" restores the session's original permission mode.\n    // When interactionMode is absent we leave the current mode unchanged.\n    if (input.interactionMode === \"plan\") {\n      yield* Effect.tryPromise({\n        try: () => context.query.setPermissionMode(\"plan\"),\n        catch: (cause) => toRequestError(input.threadId, \"turn/setPermissionMode\", cause),\n      });\n    } else if (input.interactionMode === \"default\") {\n      yield* Effect.tryPromise({\n        try: () => context.query.setPermissionMode(context.basePermissionMode ?? \"default\"),\n        catch: (cause) => toRequestError(input.threadId, \"turn/setPermissionMode\", cause),\n      });\n    }\n\n    const turnId = steeringTurnState?.turnId ?? TurnId.make(yield* randomUUIDv4);\n    if (steeringTurnState === null) {\n      const turnState: ClaudeTurnState = {\n        turnId,\n        startedAt: yield* nowIso,\n        items: [],\n        assistantTextBlocks: new Map(),\n        assistantTextBlockOrder: [],\n        capturedProposedPlanKeys: new Set(),\n        nextSyntheticAssistantBlockIndex: -1,\n      };\n\n      const updatedAt = yield* nowIso;\n      context.turnState = turnState;\n      context.session = {\n        ...context.session,\n        status: \"running\",\n        activeTurnId: turnId,\n        updatedAt,\n      };\n\n      const turnStartedStamp = yield* makeEventStamp();\n      yield* offerRuntimeEvent({\n        type: \"turn.started\",\n        eventId: turnStartedStamp.eventId,\n        provider: PROVIDER,\n        createdAt: turnStartedStamp.createdAt,\n        threadId: context.session.threadId,\n        turnId,\n        payload: modelSelection?.model ? { model: modelSelection.model } : {},\n        providerRefs: {},\n      });\n    }\n\n    const message = yield* buildUserMessageEffect(input, {\n      fileSystem,\n      attachmentsDir: serverConfig.attachmentsDir,\n      boundInstanceId,\n    });\n\n    yield* Queue.offer(context.promptQueue, {\n      type: \"message\",\n      message,\n    }).pipe(Effect.mapError((cause) => toRequestError(input.threadId, \"turn/start\", cause)));\n\n    return {\n      threadId: context.session.threadId,\n      turnId,\n      ...(context.session.resumeCursor !== undefined\n        ? { resumeCursor: context.session.resumeCursor }\n        : {}),\n    };\n  });\n\n  const interruptTurn: ClaudeAdapterShape[\"interruptTurn\"] = Effect.fn(\"interruptTurn\")(\n    function* (threadId, _turnId) {\n      const context = yield* requireSession(threadId);\n      // Stop-everything semantics: users reach for Stop precisely when a\n      // fleet ran away. interrupt() alone only ends the parent turn —\n      // background subagents/shells keep running and keep burning tokens.\n      // Stop every live task first (best-effort per task: one refusal must\n      // not strand the rest or block the turn interrupt), then interrupt.\n      if (context.query.stopTask && context.liveTaskIds.size > 0) {\n        const liveIds = Array.from(context.liveTaskIds);\n        // Bounded: a wedged child's stopTask promise may never settle\n        // (Effect.ignore handles rejection, not non-resolution), and the\n        // parent interrupt below MUST still run — Stop matters most during\n        // runaway fleets (review finding). Per-task timeout keeps one hung\n        // child from consuming the whole budget.\n        yield* Effect.forEach(\n          liveIds,\n          (taskId) =>\n            Effect.gen(function* () {\n              const stopAcknowledged = yield* Effect.tryPromise({\n                // Invoke through the query object: SDK methods rely on `this`.\n                try: () => context.query.stopTask!(taskId),\n                catch: () => undefined,\n              }).pipe(\n                Effect.timeoutOption(\"3 seconds\"),\n                Effect.orElseSucceed(() => Option.none()),\n              );\n              if (Option.isNone(stopAcknowledged) || !context.liveTaskIds.delete(taskId)) {\n                return;\n              }\n\n              // stopTask only acknowledges the control request. Its separate\n              // task_notification can lose the race with interrupt(), so make\n              // the acknowledged stop authoritative for the durable UI state.\n              const stamp = yield* makeEventStamp();\n              yield* offerRuntimeEvent({\n                type: \"task.completed\",\n                eventId: stamp.eventId,\n                provider: PROVIDER,\n                createdAt: stamp.createdAt,\n                threadId: context.session.threadId,\n                ...(context.turnState\n                  ? { turnId: asCanonicalTurnId(context.turnState.turnId) }\n                  : {}),\n                payload: {\n                  taskId: RuntimeTaskId.make(taskId),\n                  status: \"stopped\",\n                  ...taskLinkageFor(context.taskAgents, taskId),\n                },\n                providerRefs: nativeProviderRefs(context),\n              });\n            }).pipe(Effect.ignore),\n          { concurrency: 8, discard: true },\n        ).pipe(Effect.timeoutOption(\"10 seconds\"), Effect.ignore);\n      }\n      yield* Effect.tryPromise({\n        try: () => context.query.interrupt(),\n        catch: (cause) => toRequestError(threadId, \"turn/interrupt\", cause),\n      });\n    },\n  );\n\n  const readThread: ClaudeAdapterShape[\"readThread\"] = Effect.fn(\"readThread\")(\n    function* (threadId) {\n      const context = yield* requireSession(threadId);\n      return yield* snapshotThread(context);\n    },\n  );\n\n  const rollbackThread: ClaudeAdapterShape[\"rollbackThread\"] = Effect.fn(\"rollbackThread\")(\n    function* (threadId, numTurns) {\n      const context = yield* requireSession(threadId);\n      const nextLength = Math.max(0, context.turns.length - numTurns);\n      context.turns.splice(nextLength);\n      yield* updateResumeCursor(context);\n      return yield* snapshotThread(context);\n    },\n  );\n\n  const respondToRequest: ClaudeAdapterShape[\"respondToRequest\"] = Effect.fn(\"respondToRequest\")(\n    function* (threadId, requestId, decision) {\n      const context = yield* requireSession(threadId);\n      const pending = context.pendingApprovals.get(requestId);\n      if (!pending) {\n        return yield* new ProviderAdapterRequestError({\n          provider: PROVIDER,\n          method: \"item/requestApproval/decision\",\n          detail: `Unknown pending approval request: ${requestId}`,\n        });\n      }\n\n      context.pendingApprovals.delete(requestId);\n      yield* Deferred.succeed(pending.decision, decision);\n    },\n  );\n\n  const respondToUserInput: ClaudeAdapterShape[\"respondToUserInput\"] = Effect.fn(\n    \"respondToUserInput\",\n  )(function* (threadId, requestId, answers) {\n    const context = yield* requireSession(threadId);\n    const pending = context.pendingUserInputs.get(requestId);\n    if (!pending) {\n      return yield* new ProviderAdapterRequestError({\n        provider: PROVIDER,\n        method: \"item/tool/respondToUserInput\",\n        detail: `Unknown pending user-input request: ${requestId}`,\n      });\n    }\n\n    context.pendingUserInputs.delete(requestId);\n    yield* Deferred.succeed(pending.answers, answers);\n  });\n\n  const stopSession: ClaudeAdapterShape[\"stopSession\"] = Effect.fn(\"stopSession\")(\n    function* (threadId) {\n      const context = yield* requireSession(threadId);\n      yield* stopSessionInternal(context, {\n        emitExitEvent: true,\n      });\n    },\n  );\n\n  const listSessions: ClaudeAdapterShape[\"listSessions\"] = () =>\n    Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session })));\n\n  const hasSession: ClaudeAdapterShape[\"hasSession\"] = (threadId) =>\n    Effect.sync(() => {\n      const context = sessions.get(threadId);\n      return context !== undefined && !context.stopped;\n    });\n\n  const stopAll: ClaudeAdapterShape[\"stopAll\"] = () =>\n    Effect.forEach(\n      sessions,\n      ([, context]) =>\n        stopSessionInternal(context, {\n          emitExitEvent: true,\n        }),\n      { discard: true },\n    );\n\n  yield* Effect.addFinalizer(() =>\n    Effect.forEach(\n      sessions,\n      ([, context]) =>\n        stopSessionInternal(context, {\n          emitExitEvent: false,\n        }),\n      { discard: true },\n    ).pipe(\n      Effect.catch((cause) =>\n        Effect.logError(\"Failed to emit Claude session shutdown event.\", { cause }),\n      ),\n      Effect.tap(() => Queue.shutdown(runtimeEventQueue)),\n      Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),\n    ),\n  );\n\n  return {\n    provider: PROVIDER,\n    capabilities: {\n      sessionModelSwitch: \"in-session\",\n    },\n    startSession,\n    sendTurn,\n    interruptTurn,\n    readThread,\n    rollbackThread,\n    respondToRequest,\n    respondToUserInput,\n    stopSession,\n    listSessions,\n    hasSession,\n    stopAll,\n    get streamEvents() {\n      return Stream.fromQueue(runtimeEventQueue);\n    },\n  } satisfies ClaudeAdapterShape;\n});\n","import {\n  DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL,\n  type ServerProvider,\n  ServerSettingsError,\n} from \"@t3tools/contracts\";\nimport { resolveServerBackgroundActivitySettings } from \"@t3tools/shared/backgroundActivitySettings\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Semaphore from \"effect/Semaphore\";\n\nimport * as BackgroundPolicy from \"../background/BackgroundPolicy.ts\";\nimport { ServerSettingsService } from \"../serverSettings.ts\";\nimport type { ServerProviderShape } from \"./Services/ServerProvider.ts\";\n\ninterface ProviderSnapshotState {\n  readonly snapshot: ServerProvider;\n  readonly enrichmentGeneration: number;\n}\n\nexport const makeManagedServerProvider = Effect.fn(\"makeManagedServerProvider\")(function* <\n  Settings,\n>(input: {\n  readonly maintenanceCapabilities: ServerProviderShape[\"maintenanceCapabilities\"];\n  readonly getSettings: Effect.Effect<Settings, ServerSettingsError>;\n  readonly streamSettings: Stream.Stream<Settings>;\n  readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;\n  readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;\n  readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;\n  readonly enrichSnapshot?: (input: {\n    readonly settings: Settings;\n    readonly snapshot: ServerProvider;\n    readonly getSnapshot: Effect.Effect<ServerProvider>;\n    readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;\n  }) => Effect.Effect<void>;\n  readonly refreshInterval?: Duration.Input;\n}): Effect.fn.Return<\n  ServerProviderShape,\n  ServerSettingsError,\n  Scope.Scope | BackgroundPolicy.BackgroundPolicy | ServerSettingsService\n> {\n  const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;\n  const serverSettings = yield* ServerSettingsService;\n  const refreshSemaphore = yield* Semaphore.make(1);\n  const changesPubSub = yield* Effect.acquireRelease(\n    PubSub.unbounded<ServerProvider>(),\n    PubSub.shutdown,\n  );\n  const initialSettings = yield* input.getSettings;\n  const initialSnapshot = yield* input.initialSnapshot(initialSettings);\n  const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({\n    snapshot: initialSnapshot,\n    enrichmentGeneration: 0,\n  });\n  const settingsRef = yield* Ref.make(initialSettings);\n  const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);\n  const scope = yield* Effect.scope;\n\n  const publishEnrichedSnapshot = Effect.fn(\"publishEnrichedSnapshot\")(function* (\n    generation: number,\n    nextSnapshot: ServerProvider,\n  ) {\n    const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {\n      if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {\n        return [null, state] as const;\n      }\n      return [\n        nextSnapshot,\n        {\n          ...state,\n          snapshot: nextSnapshot,\n        },\n      ] as const;\n    });\n    if (snapshotToPublish === null) {\n      return;\n    }\n    yield* PubSub.publish(changesPubSub, snapshotToPublish);\n  });\n\n  const restartSnapshotEnrichment = Effect.fn(\"restartSnapshotEnrichment\")(function* (\n    settings: Settings,\n    snapshot: ServerProvider,\n    generation: number,\n  ) {\n    const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);\n    if (previousFiber) {\n      yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);\n    }\n\n    if (!input.enrichSnapshot) {\n      return;\n    }\n\n    const fiber = yield* input\n      .enrichSnapshot({\n        settings,\n        snapshot,\n        getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),\n        publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),\n      })\n      .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));\n\n    yield* Ref.set(enrichmentFiberRef, fiber);\n  });\n\n  const applySnapshotBase = Effect.fn(\"applySnapshot\")(function* (\n    nextSettings: Settings,\n    options?: { readonly forceRefresh?: boolean },\n  ) {\n    const forceRefresh = options?.forceRefresh === true;\n    const previousSettings = yield* Ref.get(settingsRef);\n    if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {\n      yield* Ref.set(settingsRef, nextSettings);\n      return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));\n    }\n\n    const nextSnapshot = yield* input.checkProvider;\n    const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {\n      const generation = input.enrichSnapshot\n        ? state.enrichmentGeneration + 1\n        : state.enrichmentGeneration;\n      return [\n        generation,\n        {\n          snapshot: nextSnapshot,\n          enrichmentGeneration: generation,\n        },\n      ] as const;\n    });\n    yield* Ref.set(settingsRef, nextSettings);\n    yield* PubSub.publish(changesPubSub, nextSnapshot);\n    yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);\n    return nextSnapshot;\n  });\n  const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>\n    refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));\n\n  const refreshSnapshot = Effect.fn(\"refreshSnapshot\")(function* () {\n    const nextSettings = yield* input.getSettings;\n    return yield* applySnapshot(nextSettings, { forceRefresh: true });\n  });\n\n  const hasProviderStatusDemand = Effect.gen(function* () {\n    const state = yield* Ref.get(snapshotStateRef);\n    const instanceId = state.snapshot.instanceId;\n    const [genericDemand, instanceDemand] = yield* Effect.all([\n      backgroundPolicy.shouldRunScopeWork({ type: \"provider-status\" }),\n      backgroundPolicy.shouldRunScopeWork({ type: \"provider-status\", instanceId }),\n    ]);\n    return genericDemand || instanceDemand;\n  });\n\n  const getRefreshInterval =\n    input.refreshInterval !== undefined\n      ? Effect.succeed(input.refreshInterval)\n      : serverSettings.getSettings.pipe(\n          Effect.map(\n            (settings) =>\n              resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,\n          ),\n          Effect.orElseSucceed(() => DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL),\n        );\n\n  const refreshIntervalChanges = yield* Queue.sliding<void>(1);\n  if (input.refreshInterval === undefined) {\n    const serverSettingsChanges = yield* serverSettings.subscribeChanges;\n    yield* serverSettingsChanges.pipe(\n      Stream.map((settings) =>\n        Duration.toMillis(\n          resolveServerBackgroundActivitySettings(settings).providerHealthRefreshInterval,\n        ),\n      ),\n      Stream.changes,\n      Stream.runForEach(() => Queue.offer(refreshIntervalChanges, undefined).pipe(Effect.asVoid)),\n      Effect.forkScoped,\n    );\n  }\n\n  yield* Stream.runForEach(input.streamSettings, (nextSettings) =>\n    Effect.asVoid(applySnapshot(nextSettings)),\n  ).pipe(Effect.forkScoped);\n\n  yield* Effect.forever(\n    getRefreshInterval.pipe(\n      Effect.flatMap((refreshInterval) =>\n        Effect.raceFirst(\n          Effect.sleep(\n            Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) <= 0\n              ? \"60 seconds\"\n              : refreshInterval,\n          ).pipe(Effect.as(true)),\n          Queue.take(refreshIntervalChanges).pipe(Effect.as(false)),\n        ).pipe(\n          Effect.flatMap((intervalElapsed) =>\n            intervalElapsed && Duration.toMillis(Duration.fromInputUnsafe(refreshInterval)) > 0\n              ? hasProviderStatusDemand.pipe(\n                  Effect.flatMap((shouldRefresh) =>\n                    shouldRefresh ? refreshSnapshot().pipe(Effect.asVoid) : Effect.void,\n                  ),\n                )\n              : Effect.void,\n          ),\n        ),\n      ),\n      Effect.ignoreCause({ log: true }),\n    ),\n  ).pipe(Effect.forkScoped);\n\n  yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(\n    Effect.ignoreCause({ log: true }),\n    Effect.forkScoped,\n  );\n\n  return {\n    maintenanceCapabilities: input.maintenanceCapabilities,\n    getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),\n    refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),\n    get streamChanges() {\n      return Stream.fromPubSub(changesPubSub);\n    },\n  } satisfies ServerProviderShape;\n});\n","/**\n * ProviderDriver / ProviderInstance — driver SPI as plain values.\n *\n * `ProviderDriver` is a record, not a Context.Service. The thing it produces\n * (`ProviderInstance`) is also a record — three captured closures\n * (`snapshot`, `adapter`, `textGeneration`), an id, and a driver kind. There\n * are intentionally no per-driver Context tags because tags are\n * singleton-per-runtime and we need many instances of the same driver.\n *\n * The only Effect service involved is `ProviderInstanceRegistry`, which\n * owns the live `Map<InstanceId, ProviderInstance>` and is itself a\n * singleton.\n *\n * Driver factories are functions of `(typed config, env)` where:\n *   - `typed config` is decoded once by the registry via `configSchema`,\n *     so drivers never deal with raw `unknown`.\n *   - `env` flows through Effect's R channel. Each driver declares the\n *     subset of infrastructure services it needs (FileSystem,\n *     ChildProcessSpawner, …) on its `create` return type; the registry\n *     layer's R is the union of those, and the runtime layer satisfies it.\n *\n * @module provider/ProviderDriver\n */\nimport type {\n  ProviderDriverKind,\n  ProviderInstanceEnvironment,\n  ProviderInstanceId,\n} from \"@t3tools/contracts\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Schema from \"effect/Schema\";\nimport type * as Scope from \"effect/Scope\";\n\nimport type * as TextGeneration from \"../textGeneration/TextGeneration.ts\";\nimport type { ProviderAdapterError, ProviderDriverError } from \"./Errors.ts\";\nimport type { ProviderAdapterShape } from \"./Services/ProviderAdapter.ts\";\nimport type { ServerProviderShape } from \"./Services/ServerProvider.ts\";\n\n/**\n * Static metadata advertised by a driver. Used for default presentation\n * and (later) settings UI. Doesn't need to be Effect-typed because nothing\n * about it is dynamic — drivers are registered at startup.\n */\nexport interface ProviderDriverMetadata {\n  /** Human-readable name for the driver itself (e.g. \"Codex\"). */\n  readonly displayName: string;\n  /**\n   * Whether the driver may be instantiated more than once concurrently.\n   * Defaults to `true`. Set to `false` for drivers that wrap a global\n   * resource (e.g. a single desktop app socket) — the registry then\n   * rejects multi-instance configurations with a clear error.\n   */\n  readonly supportsMultipleInstances?: boolean;\n}\n\n/**\n * One materialized provider instance. Held by the registry, looked up by\n * `instanceId`, torn down by closing the scope it was created in.\n *\n * The three \"shape\" fields are captured closures owned by this instance —\n * stopping one instance cannot affect another, and starting a second\n * instance of the same driver does not reach into the first instance's\n * state.\n */\nexport interface ProviderInstance {\n  readonly instanceId: ProviderInstanceId;\n  readonly driverKind: ProviderDriverKind;\n  readonly continuationIdentity: ProviderContinuationIdentity;\n  readonly displayName: string | undefined;\n  readonly accentColor?: string | undefined;\n  readonly enabled: boolean;\n  readonly snapshot: ServerProviderShape;\n  readonly adapter: ProviderAdapterShape<ProviderAdapterError>;\n  readonly textGeneration: TextGeneration.TextGeneration[\"Service\"];\n}\n\nexport interface ProviderContinuationIdentity {\n  readonly driverKind: ProviderDriverKind;\n  readonly continuationKey: string;\n}\n\nexport function defaultProviderContinuationIdentity(input: {\n  readonly driverKind: ProviderDriverKind;\n  readonly instanceId: ProviderInstanceId;\n}): ProviderContinuationIdentity {\n  return {\n    driverKind: input.driverKind,\n    continuationKey: `${input.driverKind}:instance:${input.instanceId}`,\n  };\n}\n\n/**\n * Inputs the registry passes to a driver's `create` function.\n *\n * `config` is the typed payload — already decoded by the registry through\n * `driver.configSchema`. Drivers never decode their own raw envelope.\n */\nexport interface ProviderDriverCreateInput<Config> {\n  readonly instanceId: ProviderInstanceId;\n  readonly displayName: string | undefined;\n  readonly accentColor?: string | undefined;\n  readonly environment: ProviderInstanceEnvironment;\n  readonly enabled: boolean;\n  readonly config: Config;\n}\n\n/**\n * Driver SPI — registered as a plain value, not a Layer.\n *\n * `Config` is whatever the driver decoded from\n * `ProviderInstanceConfig.config`. `R` is the union of infrastructure\n * services the driver depends on; the registry layer aggregates `R` across\n * all registered drivers and the runtime supplies them.\n *\n * `create` is responsible for *all* per-instance state — process handles,\n * pubsub topics, refs, file watchers — and must release them when its\n * scope closes. Two calls to `create` with different `instanceId` /\n * `config` MUST yield instances with no shared mutable state.\n */\nexport interface ProviderDriver<Config, R = never> {\n  readonly driverKind: ProviderDriverKind;\n  readonly metadata: ProviderDriverMetadata;\n  /**\n   * Decoder for the opaque `ProviderInstanceConfig.config` envelope. The\n   * registry runs this exactly once per (re)load of an instance; a decode\n   * failure is surfaced as `ProviderDriverError` and downgraded to an\n   * unavailable shadow snapshot.\n   *\n   * The `Encoded` parameter is intentionally left as `unknown` (not\n   * `Config`) so schemas with `withDecodingDefault` / transformations — where\n   * the encoded shape differs from the decoded shape — satisfy the SPI\n   * without casts. The registry only ever decodes `unknown` envelopes here,\n   * so the precise encoded type is irrelevant at this boundary.\n   *\n   * Using `Codec` rather than `Schema` pins `DecodingServices = never` — if\n   * we used `Schema<Config>`, the erased `any` in `AnyProviderDriver` would\n   * widen `DecodingServices` to `unknown` and poison the R channel of every\n   * caller of `decodeUnknownEffect`.\n   */\n  readonly configSchema: Schema.Codec<Config, unknown>;\n  /**\n   * Default config payload used when the legacy\n   * `ServerSettings.providers.<kind>` entry is empty or when the driver\n   * is auto-bootstrapped without user configuration. Returning a typed\n   * default keeps the migration path simple — no special-casing needed\n   * to construct a \"blank\" instance.\n   */\n  readonly defaultConfig: () => Config;\n  /**\n   * Materialize one instance. The returned effect runs in a scope owned\n   * by the registry; closing that scope releases every resource the\n   * driver opened. Failures become unavailable shadow snapshots — the\n   * driver MUST NOT throw defects.\n   */\n  readonly create: (\n    input: ProviderDriverCreateInput<Config>,\n  ) => Effect.Effect<ProviderInstance, ProviderDriverError, R | Scope.Scope>;\n}\n\n/**\n * Heterogeneous-array convenience: the registry stores drivers as\n * `ReadonlyArray<AnyProviderDriver<R>>` where `R` is the union of all\n * registered drivers' env requirements.\n */\n// `any` here intentionally erases the per-driver Config; the registry\n// already decoded it before invoking `create`, so downstream code never\n// needs the original `Config` type. Using `unknown` instead would force\n// `create` callers into casts since `unknown` is not assignable to a\n// concrete `Config` from inside the driver body.\nexport type AnyProviderDriver<R = never> = ProviderDriver<any, R>;\n","import type { ProviderInstanceEnvironment } from \"@t3tools/contracts\";\n\nexport function mergeProviderInstanceEnvironment(\n  environment: ProviderInstanceEnvironment | undefined,\n  baseEnv: NodeJS.ProcessEnv = process.env,\n): NodeJS.ProcessEnv {\n  if (!environment || environment.length === 0) {\n    return baseEnv;\n  }\n\n  const next: NodeJS.ProcessEnv = { ...baseEnv };\n  for (const variable of environment) {\n    next[variable.name] = variable.value;\n  }\n  return next;\n}\n","import type { ServerSettings, ServerSettingsError } from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as Stream from \"effect/Stream\";\n\nimport type * as ServerSettingsModule from \"../serverSettings.ts\";\n\nexport interface ProviderSnapshotSettings<Settings> {\n  readonly provider: Settings;\n  readonly enableProviderUpdateChecks: boolean;\n}\n\nexport function makeProviderSnapshotSettings<Settings>(\n  provider: Settings,\n  settings: ServerSettings,\n): ProviderSnapshotSettings<Settings> {\n  return {\n    provider,\n    enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n  };\n}\n\nexport function haveProviderSnapshotSettingsChanged<Settings>(\n  previous: ProviderSnapshotSettings<Settings>,\n  next: ProviderSnapshotSettings<Settings>,\n): boolean {\n  return !Equal.equals(previous, next);\n}\n\nexport function makeProviderSnapshotSettingsSource<Settings>(\n  provider: Settings,\n  serverSettings: ServerSettingsModule.ServerSettingsService[\"Service\"],\n): {\n  readonly getSettings: Effect.Effect<ProviderSnapshotSettings<Settings>, ServerSettingsError>;\n  readonly streamSettings: Stream.Stream<ProviderSnapshotSettings<Settings>>;\n} {\n  const mapSettings = (settings: ServerSettings) =>\n    makeProviderSnapshotSettings(provider, settings);\n  return {\n    getSettings: serverSettings.getSettings.pipe(Effect.map(mapSettings)),\n    streamSettings: serverSettings.streamChanges.pipe(Stream.map(mapSettings)),\n  };\n}\n","/**\n * ClaudeDriver — `ProviderDriver` for the Claude Agent SDK runtime.\n *\n * Mirrors `CodexDriver`: a plain value whose `create()` returns one\n * `ProviderInstance` bundling `snapshot` / `adapter` / `textGeneration`\n * closures captured over the per-instance `ClaudeSettings`.\n *\n * Unlike Codex, the Claude snapshot probe may invoke a secondary probe\n * (`probeClaudeCapabilities`) to read Anthropic account + slash-command\n * metadata. That probe is per-instance and keyed by binary + resolved HOME so\n * two concurrent Claude instances don't cross-contaminate account metadata.\n *\n * @module provider/Drivers/ClaudeDriver\n */\nimport { ClaudeSettings, ProviderDriverKind, type ServerProvider } from \"@t3tools/contracts\";\nimport * as Cache from \"effect/Cache\";\nimport * as Duration from \"effect/Duration\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { makeClaudeTextGeneration } from \"../../textGeneration/ClaudeTextGeneration.ts\";\nimport * as BackgroundPolicy from \"../../background/BackgroundPolicy.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { ProviderDriverError } from \"../Errors.ts\";\nimport { makeClaudeAdapter } from \"../Layers/ClaudeAdapter.ts\";\nimport {\n  checkClaudeProviderStatus,\n  makePendingClaudeProvider,\n  probeClaudeCapabilities,\n} from \"../Layers/ClaudeProvider.ts\";\nimport { ProviderEventLoggers } from \"../Layers/ProviderEventLoggers.ts\";\nimport { makeManagedServerProvider } from \"../makeManagedServerProvider.ts\";\nimport {\n  defaultProviderContinuationIdentity,\n  type ProviderDriver,\n  type ProviderInstance,\n} from \"../ProviderDriver.ts\";\nimport type { ServerProviderDraft } from \"../providerSnapshot.ts\";\nimport { mergeProviderInstanceEnvironment } from \"../ProviderInstanceEnvironment.ts\";\nimport {\n  enrichProviderSnapshotWithVersionAdvisory,\n  makePackageManagedProviderMaintenanceResolver,\n  normalizeCommandPath,\n  resolveProviderMaintenanceCapabilitiesEffect,\n} from \"../providerMaintenance.ts\";\nimport {\n  haveProviderSnapshotSettingsChanged,\n  makeProviderSnapshotSettingsSource,\n  type ProviderSnapshotSettings,\n} from \"../providerUpdateSettings.ts\";\nimport { makeClaudeCapabilitiesCacheKey, makeClaudeContinuationGroupKey } from \"./ClaudeHome.ts\";\nconst decodeClaudeSettings = Schema.decodeSync(ClaudeSettings);\n\nconst DRIVER_KIND = ProviderDriverKind.make(\"claudeAgent\");\nconst CAPABILITIES_PROBE_TTL = Duration.minutes(5);\n\nfunction isClaudeNativeCommandPath(commandPath: string): boolean {\n  const normalized = normalizeCommandPath(commandPath);\n  return (\n    normalized.endsWith(\"/.local/bin/claude\") ||\n    normalized.endsWith(\"/.local/bin/claude.exe\") ||\n    normalized.includes(\"/.local/share/claude/\")\n  );\n}\n\nconst UPDATE = makePackageManagedProviderMaintenanceResolver({\n  provider: DRIVER_KIND,\n  npmPackageName: \"@anthropic-ai/claude-code\",\n  homebrewFormula: \"claude-code\",\n  nativeUpdate: {\n    executable: \"claude\",\n    args: [\"update\"],\n    lockKey: \"claude-native\",\n    isCommandPath: isClaudeNativeCommandPath,\n  },\n});\n\nexport type ClaudeDriverEnv =\n  | BackgroundPolicy.BackgroundPolicy\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | HttpClient.HttpClient\n  | Path.Path\n  | ProviderEventLoggers\n  | ServerConfig\n  | ServerSettingsService;\n\nconst withInstanceIdentity =\n  (input: {\n    readonly instanceId: ProviderInstance[\"instanceId\"];\n    readonly displayName: string | undefined;\n    readonly accentColor: string | undefined;\n    readonly continuationGroupKey: string;\n  }) =>\n  (snapshot: ServerProviderDraft): ServerProvider => ({\n    ...snapshot,\n    instanceId: input.instanceId,\n    driver: DRIVER_KIND,\n    ...(input.displayName ? { displayName: input.displayName } : {}),\n    ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n    continuation: { groupKey: input.continuationGroupKey },\n  });\n\nexport const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {\n  driverKind: DRIVER_KIND,\n  metadata: {\n    displayName: \"Claude\",\n    supportsMultipleInstances: true,\n  },\n  configSchema: ClaudeSettings,\n  defaultConfig: (): ClaudeSettings => decodeClaudeSettings({}),\n  create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n    Effect.gen(function* () {\n      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n      const fileSystem = yield* FileSystem.FileSystem;\n      const path = yield* Path.Path;\n      const { cwd } = yield* ServerConfig;\n      const httpClient = yield* HttpClient.HttpClient;\n      const serverSettings = yield* ServerSettingsService;\n      const eventLoggers = yield* ProviderEventLoggers;\n      const processEnv = mergeProviderInstanceEnvironment(environment);\n      const fallbackContinuationIdentity = defaultProviderContinuationIdentity({\n        driverKind: DRIVER_KIND,\n        instanceId,\n      });\n      const effectiveConfig = { ...config, enabled } satisfies ClaudeSettings;\n      const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {\n        binaryPath: effectiveConfig.binaryPath,\n        env: processEnv,\n      });\n      const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);\n      const stampIdentity = withInstanceIdentity({\n        instanceId,\n        displayName,\n        accentColor,\n        continuationGroupKey,\n      });\n\n      const adapterOptions = {\n        instanceId,\n        environment: processEnv,\n        ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n      };\n      const adapter = yield* makeClaudeAdapter(effectiveConfig, adapterOptions);\n      const textGeneration = yield* makeClaudeTextGeneration(effectiveConfig, processEnv);\n\n      // Per-instance capabilities cache: keyed on binary + resolved HOME so\n      // account-specific probes never share auth metadata across instances.\n      const capabilitiesProbeCache = yield* Cache.make({\n        capacity: 1,\n        timeToLive: CAPABILITIES_PROBE_TTL,\n        lookup: () =>\n          probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(\n            Effect.provideService(Path.Path, path),\n          ),\n      });\n      const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig, cwd);\n\n      const checkProvider = checkClaudeProviderStatus(\n        effectiveConfig,\n        () => Cache.get(capabilitiesProbeCache, capabilitiesCacheKey),\n        processEnv,\n        cwd,\n      ).pipe(\n        Effect.map(stampIdentity),\n        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n        Effect.provideService(FileSystem.FileSystem, fileSystem),\n        Effect.provideService(Path.Path, path),\n      );\n\n      const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);\n      const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<ClaudeSettings>>({\n        maintenanceCapabilities,\n        getSettings: snapshotSettings.getSettings,\n        streamSettings: snapshotSettings.streamSettings,\n        haveSettingsChanged: haveProviderSnapshotSettingsChanged,\n        initialSnapshot: (settings) =>\n          makePendingClaudeProvider(settings.provider).pipe(Effect.map(stampIdentity)),\n        checkProvider,\n        enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>\n          enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {\n            enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n          }).pipe(\n            Effect.provideService(HttpClient.HttpClient, httpClient),\n            Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),\n          ),\n      }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProviderDriverError({\n              driver: DRIVER_KIND,\n              instanceId,\n              detail: `Failed to build Claude snapshot: ${cause.message ?? String(cause)}`,\n              cause,\n            }),\n        ),\n      );\n\n      return {\n        instanceId,\n        driverKind: DRIVER_KIND,\n        continuationIdentity: {\n          ...fallbackContinuationIdentity,\n          continuationKey: continuationGroupKey,\n        },\n        displayName,\n        accentColor,\n        enabled,\n        snapshot,\n        adapter,\n        textGeneration,\n      } satisfies ProviderInstance;\n    }),\n};\n","import { tokenizeCliArgs } from \"@t3tools/shared/cliArgs\";\n\nexport const SYNAPTIC_CODEX_LAUNCH_ARGS_ENV = \"SYNAPTIC_CODEX_LAUNCH_ARGS\";\n\nexport const resolveCodexLaunchArgs = (\n  launchArgs?: string,\n  environment: NodeJS.ProcessEnv = process.env,\n) => environment[SYNAPTIC_CODEX_LAUNCH_ARGS_ENV]?.trim() || launchArgs?.trim() || \"\";\n\nexport const codexLaunchArgv = (launchArgs?: string): ReadonlyArray<string> =>\n  tokenizeCliArgs(launchArgs);\n\nexport const codexAppServerArgs = (launchArgs?: string) => [\n  \"app-server\",\n  ...codexLaunchArgv(launchArgs),\n];\n\nexport const codexExecLaunchArgs = (launchArgs?: string) => {\n  const args = codexLaunchArgv(launchArgs);\n  const execArgs: Array<string> = [];\n\n  for (let index = 0; index < args.length; index++) {\n    const arg = args[index];\n    if (arg === undefined) continue;\n\n    if (arg === \"--strict-config\" || arg.startsWith(\"--config=\") || arg.startsWith(\"-c=\")) {\n      execArgs.push(arg);\n    } else if (arg === \"--config\" || arg === \"-c\" || arg === \"--enable\" || arg === \"--disable\") {\n      const value = args[index + 1];\n      if (value !== undefined && !value.startsWith(\"-\")) {\n        execArgs.push(arg, value);\n        index++;\n      }\n    } else if (arg.startsWith(\"--enable=\") || arg.startsWith(\"--disable=\")) {\n      execArgs.push(arg);\n    }\n  }\n\n  return execArgs;\n};\n\nexport const codexSessionAppServerArgs = (\n  appServerArgs: ReadonlyArray<string> | undefined,\n  launchArgs: string | undefined,\n) => {\n  const launchAppServerArgs = codexAppServerArgs(launchArgs);\n  return appServerArgs ? [...launchAppServerArgs, ...appServerArgs] : launchAppServerArgs;\n};\n","import type { ModelSelection } from \"@t3tools/contracts\";\nimport {\n  getModelSelectionBooleanOptionValue,\n  getModelSelectionStringOptionValue,\n} from \"@t3tools/shared/model\";\n\nexport function getCodexServiceTierOptionValue(\n  modelSelection: ModelSelection | null | undefined,\n): string | undefined {\n  return (\n    getModelSelectionStringOptionValue(modelSelection, \"serviceTier\") ??\n    (getModelSelectionBooleanOptionValue(modelSelection, \"fastMode\") === true ? \"fast\" : undefined)\n  );\n}\n","import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport {\n  type CodexSettings,\n  DEFAULT_TEXT_GENERATION_REASONING_EFFORT,\n  type ModelSelection,\n  TextGenerationError,\n} from \"@t3tools/contracts\";\nimport { sanitizeBranchFragment, sanitizeFeatureBranchName } from \"@t3tools/shared/git\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\nimport { resolveAttachmentPath } from \"../attachmentStore.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport { expandHomePath } from \"../pathExpansion.ts\";\nimport { codexExecLaunchArgs, resolveCodexLaunchArgs } from \"../provider/Layers/codexLaunchArgs.ts\";\nimport * as TextGeneration from \"./TextGeneration.ts\";\nimport {\n  buildBranchNamePrompt,\n  buildCommitMessagePrompt,\n  buildPrContentPrompt,\n  buildThreadTitlePrompt,\n} from \"./TextGenerationPrompts.ts\";\nimport {\n  normalizeCliError,\n  sanitizeCommitSubject,\n  sanitizePrTitle,\n  sanitizeThreadTitle,\n  toJsonSchemaObject,\n} from \"./TextGenerationUtils.ts\";\nimport { getModelSelectionStringOptionValue } from \"@t3tools/shared/model\";\nimport { getCodexServiceTierOptionValue } from \"../codexModelOptions.ts\";\n\nconst CODEX_TIMEOUT_MS = 180_000;\nconst encodeJsonString = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));\n/**\n * Build a Codex text-generation closure bound to a specific `CodexSettings`\n * payload. See `makeCodexAdapter` for the overall per-instance rationale.\n */\nexport const makeCodexTextGeneration = Effect.fn(\"makeCodexTextGeneration\")(function* (\n  codexConfig: CodexSettings,\n  environment?: NodeJS.ProcessEnv,\n) {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const serverConfig = yield* Effect.service(ServerConfig.ServerConfig);\n  const resolvedEnvironment = environment ?? process.env;\n\n  type MaterializedImageAttachments = {\n    readonly imagePaths: ReadonlyArray<string>;\n  };\n\n  const readStreamAsString = <E>(\n    operation: string,\n    stream: Stream.Stream<Uint8Array, E>,\n  ): Effect.Effect<string, TextGenerationError> =>\n    stream.pipe(\n      Stream.decodeText(),\n      Stream.runFold(\n        () => \"\",\n        (acc, chunk) => acc + chunk,\n      ),\n      Effect.mapError((cause) =>\n        normalizeCliError(\"codex\", operation, cause, \"Failed to collect process output\"),\n      ),\n    );\n\n  const writeTempFile = (\n    operation: string,\n    prefix: string,\n    content: string,\n  ): Effect.Effect<string, TextGenerationError, Scope.Scope> =>\n    fileSystem\n      .makeTempFileScoped({\n        prefix: `t3code-${prefix}-${process.pid}-`,\n      })\n      .pipe(\n        Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),\n        Effect.mapError(\n          (cause) =>\n            new TextGenerationError({\n              operation,\n              detail: `Failed to write temp file`,\n              cause,\n            }),\n        ),\n      );\n\n  const safeUnlink = (filePath: string): Effect.Effect<void, never> =>\n    fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));\n\n  const encodeJsonForOperation = (\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\",\n    value: unknown,\n  ): Effect.Effect<string, TextGenerationError> =>\n    encodeJsonString(value).pipe(\n      Effect.mapError(\n        (cause) =>\n          new TextGenerationError({\n            operation,\n            detail: \"Failed to encode structured output schema.\",\n            cause,\n          }),\n      ),\n    );\n\n  const materializeImageAttachments = Effect.fn(\"materializeImageAttachments\")(function* (\n    _operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\",\n    attachments: TextGeneration.BranchNameGenerationInput[\"attachments\"],\n  ): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {\n    if (!attachments || attachments.length === 0) {\n      return { imagePaths: [] };\n    }\n\n    const imagePaths: string[] = [];\n    for (const attachment of attachments) {\n      if (attachment.type !== \"image\") {\n        continue;\n      }\n\n      const resolvedPath = resolveAttachmentPath({\n        attachmentsDir: serverConfig.attachmentsDir,\n        attachment,\n      });\n      if (!resolvedPath || !path.isAbsolute(resolvedPath)) {\n        continue;\n      }\n      const fileInfo = yield* fileSystem.stat(resolvedPath).pipe(Effect.orElseSucceed(() => null));\n      if (!fileInfo || fileInfo.type !== \"File\") {\n        continue;\n      }\n      imagePaths.push(resolvedPath);\n    }\n    return { imagePaths };\n  });\n\n  const runCodexJson = Effect.fn(\"runCodexJson\")(function* <S extends Schema.Top>({\n    operation,\n    cwd,\n    prompt,\n    outputSchemaJson,\n    imagePaths = [],\n    cleanupPaths = [],\n    modelSelection,\n  }: {\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\";\n    cwd: string;\n    prompt: string;\n    outputSchemaJson: S;\n    imagePaths?: ReadonlyArray<string>;\n    cleanupPaths?: ReadonlyArray<string>;\n    modelSelection: ModelSelection;\n  }): Effect.fn.Return<S[\"Type\"], TextGenerationError, S[\"DecodingServices\"]> {\n    const schemaJson = yield* encodeJsonForOperation(\n      operation,\n      toJsonSchemaObject(outputSchemaJson),\n    );\n    const schemaPath = yield* writeTempFile(operation, \"codex-schema\", schemaJson);\n    const outputPath = yield* writeTempFile(operation, \"codex-output\", \"\");\n\n    const runCodexCommand = Effect.fn(\"runCodexJson.runCodexCommand\")(function* () {\n      const launchArgs = resolveCodexLaunchArgs(codexConfig.launchArgs, resolvedEnvironment);\n      const reasoningEffort =\n        getModelSelectionStringOptionValue(modelSelection, \"reasoningEffort\") ??\n        DEFAULT_TEXT_GENERATION_REASONING_EFFORT;\n      const serviceTier = getCodexServiceTierOptionValue(modelSelection);\n      const spawnCommand = yield* resolveSpawnCommand(\n        codexConfig.binaryPath || \"codex\",\n        [\n          \"exec\",\n          ...codexExecLaunchArgs(launchArgs),\n          \"--ephemeral\",\n          \"--skip-git-repo-check\",\n          \"-s\",\n          \"read-only\",\n          \"--model\",\n          modelSelection.model,\n          \"--config\",\n          `model_reasoning_effort=\"${reasoningEffort}\"`,\n          ...(serviceTier ? [\"--config\", `service_tier=\"${serviceTier}\"`] : []),\n          \"--output-schema\",\n          schemaPath,\n          \"--output-last-message\",\n          outputPath,\n          ...imagePaths.flatMap((imagePath) => [\"--image\", imagePath]),\n          \"-\",\n        ],\n        { env: resolvedEnvironment },\n      );\n      const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        env: {\n          ...resolvedEnvironment,\n          ...(codexConfig.homePath ? { CODEX_HOME: expandHomePath(codexConfig.homePath) } : {}),\n        },\n        cwd,\n        shell: spawnCommand.shell,\n        stdin: {\n          stream: Stream.encodeText(Stream.make(prompt)),\n        },\n      });\n\n      const child = yield* commandSpawner\n        .spawn(command)\n        .pipe(\n          Effect.mapError((cause) =>\n            normalizeCliError(\"codex\", operation, cause, \"Failed to spawn Codex CLI process\"),\n          ),\n        );\n\n      const [stdout, stderr, exitCode] = yield* Effect.all(\n        [\n          readStreamAsString(operation, child.stdout),\n          readStreamAsString(operation, child.stderr),\n          child.exitCode.pipe(\n            Effect.mapError((cause) =>\n              normalizeCliError(\"codex\", operation, cause, \"Failed to read Codex CLI exit code\"),\n            ),\n          ),\n        ],\n        { concurrency: \"unbounded\" },\n      );\n\n      if (exitCode !== 0) {\n        const stderrDetail = stderr.trim();\n        const stdoutDetail = stdout.trim();\n        const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;\n        return yield* new TextGenerationError({\n          operation,\n          detail:\n            detail.length > 0\n              ? `Codex CLI command failed: ${detail}`\n              : `Codex CLI command failed with code ${exitCode}.`,\n        });\n      }\n    });\n\n    const cleanup = Effect.all(\n      [schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),\n      {\n        concurrency: \"unbounded\",\n      },\n    ).pipe(Effect.asVoid);\n\n    return yield* Effect.gen(function* () {\n      yield* runCodexCommand().pipe(\n        Effect.scoped,\n        Effect.timeoutOption(CODEX_TIMEOUT_MS),\n        Effect.flatMap(\n          Option.match({\n            onNone: () =>\n              Effect.fail(\n                new TextGenerationError({ operation, detail: \"Codex CLI request timed out.\" }),\n              ),\n            onSome: () => Effect.void,\n          }),\n        ),\n      );\n\n      const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));\n\n      return yield* fileSystem.readFileString(outputPath).pipe(\n        Effect.mapError(\n          (cause) =>\n            new TextGenerationError({\n              operation,\n              detail: \"Failed to read Codex output file.\",\n              cause,\n            }),\n        ),\n        Effect.flatMap(decodeOutput),\n        Effect.catchTags({\n          SchemaError: (cause) =>\n            Effect.fail(\n              new TextGenerationError({\n                operation,\n                detail: \"Codex returned invalid structured output.\",\n                cause,\n              }),\n            ),\n        }),\n      );\n    }).pipe(Effect.ensuring(cleanup));\n  });\n\n  const generateCommitMessage: TextGeneration.TextGeneration[\"Service\"][\"generateCommitMessage\"] =\n    Effect.fn(\"CodexTextGeneration.generateCommitMessage\")(function* (input) {\n      const { prompt, outputSchema } = buildCommitMessagePrompt({\n        branch: input.branch,\n        stagedSummary: input.stagedSummary,\n        stagedPatch: input.stagedPatch,\n        includeBranch: input.includeBranch === true,\n        policy: input.policy,\n      });\n\n      const generated = yield* runCodexJson({\n        operation: \"generateCommitMessage\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        subject: sanitizeCommitSubject(generated.subject),\n        body: generated.body.trim(),\n        ...(\"branch\" in generated && typeof generated.branch === \"string\"\n          ? { branch: sanitizeFeatureBranchName(generated.branch) }\n          : {}),\n      };\n    });\n\n  const generatePrContent: TextGeneration.TextGeneration[\"Service\"][\"generatePrContent\"] =\n    Effect.fn(\"CodexTextGeneration.generatePrContent\")(function* (input) {\n      const { prompt, outputSchema } = buildPrContentPrompt({\n        baseBranch: input.baseBranch,\n        headBranch: input.headBranch,\n        commitSummary: input.commitSummary,\n        diffSummary: input.diffSummary,\n        diffPatch: input.diffPatch,\n        policy: input.policy,\n        changeRequestTemplate: input.changeRequestTemplate,\n      });\n\n      const generated = yield* runCodexJson({\n        operation: \"generatePrContent\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizePrTitle(generated.title),\n        body: generated.body.trim(),\n      };\n    });\n\n  const generateBranchName: TextGeneration.TextGeneration[\"Service\"][\"generateBranchName\"] =\n    Effect.fn(\"CodexTextGeneration.generateBranchName\")(function* (input) {\n      const { imagePaths } = yield* materializeImageAttachments(\n        \"generateBranchName\",\n        input.attachments,\n      );\n      const { prompt, outputSchema } = buildBranchNamePrompt({\n        message: input.message,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runCodexJson({\n        operation: \"generateBranchName\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        imagePaths,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        branch: sanitizeBranchFragment(generated.branch),\n      };\n    });\n\n  const generateThreadTitle: TextGeneration.TextGeneration[\"Service\"][\"generateThreadTitle\"] =\n    Effect.fn(\"CodexTextGeneration.generateThreadTitle\")(function* (input) {\n      const { imagePaths } = yield* materializeImageAttachments(\n        \"generateThreadTitle\",\n        input.attachments,\n      );\n      const { prompt, outputSchema } = buildThreadTitlePrompt({\n        message: input.message,\n        previousTitle: input.previousTitle,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runCodexJson({\n        operation: \"generateThreadTitle\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        imagePaths,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizeThreadTitle(generated.title),\n      } satisfies TextGeneration.ThreadTitleGenerationResult;\n    });\n\n  return {\n    generateCommitMessage,\n    generatePrContent,\n    generateBranchName,\n    generateThreadTitle,\n  } satisfies TextGeneration.TextGeneration[\"Service\"];\n});\n","import * as Schema from \"effect/Schema\";\nimport type * as SchemaIssue from \"effect/SchemaIssue\";\n\nexport const CodexAppServerRequestOperation = Schema.Literals([\n  \"decode-payload\",\n  \"encode-payload\",\n  \"handle-request\",\n  \"receive-response\",\n]);\nexport type CodexAppServerRequestOperation = typeof CodexAppServerRequestOperation.Type;\n\nexport const CodexAppServerSchemaIssueKind = Schema.Literals([\n  \"Filter\",\n  \"Encoding\",\n  \"Pointer\",\n  \"Composite\",\n  \"AnyOf\",\n  \"InvalidType\",\n  \"InvalidValue\",\n  \"MissingKey\",\n  \"UnexpectedKey\",\n  \"Forbidden\",\n  \"OneOf\",\n]);\nexport type CodexAppServerSchemaIssueKind = typeof CodexAppServerSchemaIssueKind.Type;\n\nexport interface CodexAppServerSchemaIssueDiagnostics {\n  readonly issueCount: number;\n  readonly issueKinds: ReadonlyArray<CodexAppServerSchemaIssueKind>;\n  readonly maximumPathDepth: number;\n}\n\nconst schemaIssueDiagnostics = (root: SchemaIssue.Issue): CodexAppServerSchemaIssueDiagnostics => {\n  let issueCount = 0;\n  let maximumPathDepth = 0;\n  const issueKinds = new Set<CodexAppServerSchemaIssueKind>();\n\n  const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {\n    issueCount += 1;\n    issueKinds.add(issue._tag);\n    maximumPathDepth = Math.max(maximumPathDepth, pathDepth);\n    switch (issue._tag) {\n      case \"Filter\":\n      case \"Encoding\":\n        visit(issue.issue, pathDepth);\n        break;\n      case \"Pointer\":\n        visit(issue.issue, pathDepth + issue.path.length);\n        break;\n      case \"Composite\":\n      case \"AnyOf\":\n        for (const child of issue.issues) visit(child, pathDepth);\n        break;\n    }\n  };\n\n  visit(root, 0);\n  return {\n    issueCount,\n    issueKinds: [...issueKinds],\n    maximumPathDepth,\n  };\n};\n\nexport const CodexAppServerPayloadKind = Schema.Literals([\n  \"null\",\n  \"array\",\n  \"string\",\n  \"number\",\n  \"boolean\",\n  \"bigint\",\n  \"object\",\n  \"symbol\",\n  \"function\",\n  \"undefined\",\n]);\nexport type CodexAppServerPayloadKind = typeof CodexAppServerPayloadKind.Type;\n\nconst payloadKind = (payload: unknown): CodexAppServerPayloadKind => {\n  if (payload === null) return \"null\";\n  if (Array.isArray(payload)) return \"array\";\n  return typeof payload;\n};\n\nconst protocolMessageFields = [\"id\", \"method\", \"params\", \"result\", \"error\"] as const;\n\nexport const CodexAppServerProtocolMessageField = Schema.Literals(protocolMessageFields);\nexport type CodexAppServerProtocolMessageField = typeof CodexAppServerProtocolMessageField.Type;\n\nexport interface CodexAppServerRequestDiagnostics {\n  readonly method?: string;\n  readonly requestId?: string;\n  readonly operation?: CodexAppServerRequestOperation;\n  readonly cause?: unknown;\n  readonly issueCount?: number;\n  readonly issueKinds?: ReadonlyArray<CodexAppServerSchemaIssueKind>;\n  readonly maximumPathDepth?: number;\n  readonly payloadKind?: CodexAppServerPayloadKind;\n}\n\nexport const CodexAppServerProtocolParseOperation = Schema.Literals([\n  \"encode-wire-message\",\n  \"decode-wire-message\",\n  \"route-wire-message\",\n  \"decode-notification-payload\",\n  \"decode-request-payload\",\n  \"decode-response-payload\",\n]);\nexport type CodexAppServerProtocolParseOperation = typeof CodexAppServerProtocolParseOperation.Type;\n\nexport const CodexAppServerTransportOperation = Schema.Literals([\n  \"read-input-stream\",\n  \"read-process-exit-status\",\n]);\nexport type CodexAppServerTransportOperation = typeof CodexAppServerTransportOperation.Type;\n\nexport const CodexAppServerIdentifierPurpose = Schema.Literals([\n  \"provider-event\",\n  \"command-approval-request\",\n  \"file-change-approval-request\",\n  \"user-input-request\",\n]);\nexport type CodexAppServerIdentifierPurpose = typeof CodexAppServerIdentifierPurpose.Type;\n\nexport interface CodexAppServerProtocolErrorShape {\n  readonly code: number;\n  readonly message: string;\n  readonly data?: unknown;\n}\n\nexport class CodexAppServerSpawnError extends Schema.TaggedErrorClass<CodexAppServerSpawnError>()(\n  \"CodexAppServerSpawnError\",\n  {\n    command: Schema.optional(Schema.String),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return this.command\n      ? `Failed to spawn Codex App Server process for command: ${this.command}`\n      : \"Failed to spawn Codex App Server process\";\n  }\n}\n\nexport class CodexAppServerProcessExitedError extends Schema.TaggedErrorClass<CodexAppServerProcessExitedError>()(\n  \"CodexAppServerProcessExitedError\",\n  {\n    code: Schema.optional(Schema.Number),\n    pid: Schema.optionalKey(Schema.Int),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message() {\n    return this.code === undefined\n      ? \"Codex App Server process exited\"\n      : `Codex App Server process exited with code ${this.code}`;\n  }\n}\n\nexport class CodexAppServerProtocolParseError extends Schema.TaggedErrorClass<CodexAppServerProtocolParseError>()(\n  \"CodexAppServerProtocolParseError\",\n  {\n    operation: CodexAppServerProtocolParseOperation,\n    method: Schema.optionalKey(Schema.String),\n    requestId: Schema.optionalKey(Schema.String),\n    payloadKind: Schema.optionalKey(CodexAppServerPayloadKind),\n    presentFields: Schema.optionalKey(Schema.Array(CodexAppServerProtocolMessageField)),\n    issueCount: Schema.optionalKey(Schema.Number),\n    issueKinds: Schema.optionalKey(Schema.Array(CodexAppServerSchemaIssueKind)),\n    maximumPathDepth: Schema.optionalKey(Schema.Number),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message() {\n    const method = this.method === undefined ? \"\" : ` for method '${this.method}'`;\n    return `Codex App Server protocol operation '${this.operation}' failed${method}.`;\n  }\n\n  static fromSchemaError(\n    operation: CodexAppServerProtocolParseOperation,\n    cause: Schema.SchemaError,\n    context: { readonly method?: string; readonly requestId?: string } = {},\n  ) {\n    return new CodexAppServerProtocolParseError({\n      operation,\n      ...context,\n      ...schemaIssueDiagnostics(cause.issue),\n      cause,\n    });\n  }\n\n  static fromRequestError(\n    operation: CodexAppServerProtocolParseOperation,\n    method: string,\n    cause: CodexAppServerRequestError,\n  ) {\n    return new CodexAppServerProtocolParseError({\n      operation,\n      method,\n      ...(cause.issueCount === undefined ? {} : { issueCount: cause.issueCount }),\n      ...(cause.issueKinds === undefined ? {} : { issueKinds: cause.issueKinds }),\n      ...(cause.maximumPathDepth === undefined ? {} : { maximumPathDepth: cause.maximumPathDepth }),\n      cause,\n    });\n  }\n\n  static fromUnroutableMessage(message: unknown) {\n    const diagnostics = { payloadKind: payloadKind(message) };\n    if (typeof message !== \"object\" || message === null || Array.isArray(message)) {\n      return new CodexAppServerProtocolParseError({\n        operation: \"route-wire-message\",\n        ...diagnostics,\n      });\n    }\n\n    const presentFields = protocolMessageFields.filter((field) => field in message);\n    const method =\n      \"method\" in message && typeof message.method === \"string\" ? message.method : undefined;\n    const requestId =\n      \"id\" in message && (typeof message.id === \"string\" || typeof message.id === \"number\")\n        ? String(message.id)\n        : undefined;\n    return new CodexAppServerProtocolParseError({\n      operation: \"route-wire-message\",\n      ...diagnostics,\n      presentFields,\n      ...(method === undefined ? {} : { method }),\n      ...(requestId === undefined ? {} : { requestId }),\n    });\n  }\n}\n\nexport class CodexAppServerTransportError extends Schema.TaggedErrorClass<CodexAppServerTransportError>()(\n  \"CodexAppServerTransportError\",\n  {\n    operation: CodexAppServerTransportOperation,\n    pid: Schema.optionalKey(Schema.Int),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Codex App Server transport operation '${this.operation}' failed.`;\n  }\n}\n\nexport class CodexAppServerIdentifierGenerationError extends Schema.TaggedErrorClass<CodexAppServerIdentifierGenerationError>()(\n  \"CodexAppServerIdentifierGenerationError\",\n  {\n    purpose: CodexAppServerIdentifierPurpose,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    return `Failed to generate Codex App Server identifier for ${this.purpose}.`;\n  }\n}\n\nexport class CodexAppServerInputStreamEndedError extends Schema.TaggedErrorClass<CodexAppServerInputStreamEndedError>()(\n  \"CodexAppServerInputStreamEndedError\",\n  {},\n) {\n  override get message() {\n    return \"Codex App Server input stream ended.\";\n  }\n}\n\nexport class CodexAppServerRequestError extends Schema.TaggedErrorClass<CodexAppServerRequestError>()(\n  \"CodexAppServerRequestError\",\n  {\n    code: Schema.Number,\n    errorMessage: Schema.String,\n    data: Schema.optional(Schema.Unknown),\n    method: Schema.optionalKey(Schema.String),\n    requestId: Schema.optionalKey(Schema.String),\n    operation: Schema.optionalKey(CodexAppServerRequestOperation),\n    issueCount: Schema.optionalKey(Schema.Number),\n    issueKinds: Schema.optionalKey(Schema.Array(CodexAppServerSchemaIssueKind)),\n    maximumPathDepth: Schema.optionalKey(Schema.Number),\n    payloadKind: Schema.optionalKey(CodexAppServerPayloadKind),\n    cause: Schema.optionalKey(Schema.Defect()),\n  },\n) {\n  override get message() {\n    return this.errorMessage;\n  }\n\n  static fromProtocolError(\n    error: CodexAppServerProtocolErrorShape,\n    method: string,\n    requestId: string,\n  ) {\n    return new CodexAppServerRequestError({\n      code: error.code,\n      errorMessage: error.message,\n      ...(error.data !== undefined ? { data: error.data } : {}),\n      method,\n      requestId,\n      operation: \"receive-response\",\n      cause: error,\n    });\n  }\n\n  static fromAppServerError(error: CodexAppServerError, method: string) {\n    if (error._tag === \"CodexAppServerRequestError\") {\n      return error;\n    }\n    return CodexAppServerRequestError.internalError(\n      `Codex App Server request handler failed for method '${method}'`,\n      undefined,\n      {\n        method,\n        operation: \"handle-request\",\n        cause: error,\n      },\n    );\n  }\n\n  static parseError(message = \"Parse error\", data?: unknown) {\n    return new CodexAppServerRequestError({\n      code: -32700,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static invalidRequest(message = \"Invalid request\", data?: unknown) {\n    return new CodexAppServerRequestError({\n      code: -32600,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static methodNotFound(method: string) {\n    return new CodexAppServerRequestError({\n      code: -32601,\n      errorMessage: `Method not found: ${method}`,\n    });\n  }\n\n  static invalidParams(\n    message = \"Invalid params\",\n    data?: unknown,\n    diagnostics: CodexAppServerRequestDiagnostics = {},\n  ) {\n    return new CodexAppServerRequestError({\n      code: -32602,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n      ...diagnostics,\n    });\n  }\n\n  static invalidPayload(\n    method: string,\n    operation: \"decode-payload\" | \"encode-payload\",\n    cause: Schema.SchemaError,\n  ) {\n    const diagnostics = schemaIssueDiagnostics(cause.issue);\n    return new CodexAppServerRequestError({\n      code: -32602,\n      errorMessage: `Invalid payload for method '${method}' during '${operation}'`,\n      data: diagnostics,\n      method,\n      operation,\n      ...diagnostics,\n      cause,\n    });\n  }\n\n  static unexpectedPayload(\n    method: string,\n    operation: \"decode-payload\" | \"encode-payload\",\n    payload: unknown,\n  ) {\n    const diagnostics = { payloadKind: payloadKind(payload) };\n    return new CodexAppServerRequestError({\n      code: -32602,\n      errorMessage: `Method '${method}' does not accept a payload during '${operation}'`,\n      data: diagnostics,\n      method,\n      operation,\n      ...diagnostics,\n    });\n  }\n\n  static internalError(\n    message = \"Internal error\",\n    data?: unknown,\n    diagnostics: CodexAppServerRequestDiagnostics = {},\n  ) {\n    return new CodexAppServerRequestError({\n      code: -32603,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n      ...diagnostics,\n    });\n  }\n\n  static overloaded(message = \"Server overloaded; retry later.\", data?: unknown) {\n    return new CodexAppServerRequestError({\n      code: -32001,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  toProtocolError(): CodexAppServerProtocolErrorShape {\n    return {\n      code: this.code,\n      message: this.errorMessage,\n      ...(this.data !== undefined ? { data: this.data } : {}),\n    };\n  }\n}\n\nexport const CodexAppServerError = Schema.Union([\n  CodexAppServerRequestError,\n  CodexAppServerSpawnError,\n  CodexAppServerProcessExitedError,\n  CodexAppServerProtocolParseError,\n  CodexAppServerTransportError,\n  CodexAppServerIdentifierGenerationError,\n  CodexAppServerInputStreamEndedError,\n]);\n\nexport type CodexAppServerError = typeof CodexAppServerError.Type;\n","// This file is generated by the effect-codex-app-server package. Do not edit manually.\n// Upstream protocol ref: 678157acaa819d5510adfe359abb5d0392cfe461\n\nimport * as Schema from \"effect/Schema\";\n\nexport type ApplyPatchApprovalParams__FileChange =\n  | { readonly content: string; readonly type: \"add\" }\n  | { readonly content: string; readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\"; readonly unified_diff: string };\nexport const ApplyPatchApprovalParams__FileChange = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.String,\n      type: Schema.Literal(\"add\").annotate({ title: \"AddFileChangeType\" }),\n    }).annotate({ title: \"AddFileChange\" }),\n    Schema.Struct({\n      content: Schema.String,\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeleteFileChangeType\" }),\n    }).annotate({ title: \"DeleteFileChange\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdateFileChangeType\" }),\n      unified_diff: Schema.String,\n    }).annotate({ title: \"UpdateFileChange\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ApplyPatchApprovalParams__ThreadId = string;\nexport const ApplyPatchApprovalParams__ThreadId = Schema.String;\n\nexport type ApplyPatchApprovalResponse__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const ApplyPatchApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason = \"unauthorized\";\nexport const ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason =\n  Schema.Literal(\"unauthorized\");\n\nexport type ClientRequest__AbsolutePathBuf = string;\nexport const ClientRequest__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type ClientRequest__AddCreditsNudgeCreditType = \"credits\" | \"usage_limit\";\nexport const ClientRequest__AddCreditsNudgeCreditType = Schema.Literals([\"credits\", \"usage_limit\"]);\n\nexport type ClientRequest__AdditionalContextKind = \"untrusted\" | \"application\";\nexport const ClientRequest__AdditionalContextKind = Schema.Literals([\"untrusted\", \"application\"]);\n\nexport type ClientRequest__AgentMessageInputContent =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const ClientRequest__AgentMessageInputContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"InputTextAgentMessageInputContent\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"EncryptedContentAgentMessageInputContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const ClientRequest__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type ClientRequest__AppsInstalledParams = {\n  readonly forceRefresh?: boolean;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__AppsInstalledParams = Schema.Struct({\n  forceRefresh: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true and Apps are permitted, refresh and publish the hosted connector runtime tool snapshot first.\",\n    }),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional loaded thread id used to evaluate effective app configuration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Read the committed installed connector runtime snapshot.\" });\n\nexport type ClientRequest__AppsListParams = {\n  readonly cursor?: string | null;\n  readonly forceRefetch?: boolean;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__AppsListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  forceRefetch: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, bypass app caches and fetch the latest data from sources.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional thread id used to evaluate app feature gating from that thread's config.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - list available apps/connectors.\" });\n\nexport type ClientRequest__AppsReadParams = {\n  readonly appIds: ReadonlyArray<string>;\n  readonly includeTools?: boolean;\n};\nexport const ClientRequest__AppsReadParams = Schema.Struct({\n  appIds: Schema.Array(Schema.String).annotate({\n    description:\n      \"App ids to read. The server accepts at most 100 ids and deduplicates repeated ids while preserving their first-request order.\",\n  }),\n  includeTools: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, include display-only public tool summaries in the returned metadata.\",\n    }),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - read metadata for specific apps/connectors.\" });\n\nexport type ClientRequest__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const ClientRequest__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__CancelLoginAccountParams = { readonly loginId: string };\nexport const ClientRequest__CancelLoginAccountParams = Schema.Struct({ loginId: Schema.String });\n\nexport type ClientRequest__ClientInfo = {\n  readonly name: string;\n  readonly title?: string | null;\n  readonly version: string;\n};\nexport const ClientRequest__ClientInfo = Schema.Struct({\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  version: Schema.String,\n});\n\nexport type ClientRequest__CommandExecResizeParams = {\n  readonly processId: string;\n  readonly size: { readonly cols: number; readonly rows: number };\n};\nexport const ClientRequest__CommandExecResizeParams = Schema.Struct({\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n  size: Schema.Struct({\n    cols: Schema.Number.annotate({\n      description: \"Terminal width in character cells.\",\n      format: \"uint16\",\n    })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    rows: Schema.Number.annotate({\n      description: \"Terminal height in character cells.\",\n      format: \"uint16\",\n    })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" }),\n}).annotate({ description: \"Resize a running PTY-backed `command/exec` session.\" });\n\nexport type ClientRequest__CommandExecTerminalSize = {\n  readonly cols: number;\n  readonly rows: number;\n};\nexport const ClientRequest__CommandExecTerminalSize = Schema.Struct({\n  cols: Schema.Number.annotate({\n    description: \"Terminal width in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  rows: Schema.Number.annotate({\n    description: \"Terminal height in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" });\n\nexport type ClientRequest__CommandExecTerminateParams = { readonly processId: string };\nexport const ClientRequest__CommandExecTerminateParams = Schema.Struct({\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n}).annotate({ description: \"Terminate a running `command/exec` session.\" });\n\nexport type ClientRequest__CommandExecWriteParams = {\n  readonly closeStdin?: boolean;\n  readonly deltaBase64?: string | null;\n  readonly processId: string;\n};\nexport const ClientRequest__CommandExecWriteParams = Schema.Struct({\n  closeStdin: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Close stdin after writing `deltaBase64`, if present.\",\n    }),\n  ),\n  deltaBase64: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional base64-encoded stdin bytes to write.\" }),\n      Schema.Null,\n    ]),\n  ),\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n}).annotate({\n  description: \"Write stdin bytes to a running `command/exec` session, close stdin, or both.\",\n});\n\nexport type ClientRequest__CommandMigration = { readonly name: string };\nexport const ClientRequest__CommandMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__ConfigReadParams = {\n  readonly cwd?: string | null;\n  readonly includeLayers?: boolean;\n};\nexport const ClientRequest__ConfigReadParams = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional working directory to resolve project config layers. If specified, return the effective config as seen from that directory (i.e., including any project layers between `cwd` and the project/repo root).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeLayers: Schema.optionalKey(Schema.Boolean),\n});\n\nexport type ClientRequest__ConsumeAccountRateLimitResetCreditParams = {\n  readonly creditId?: string | null;\n  readonly idempotencyKey: string;\n};\nexport const ClientRequest__ConsumeAccountRateLimitResetCreditParams = Schema.Struct({\n  creditId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque reset-credit identifier to redeem. When omitted, the backend selects the next available credit.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  idempotencyKey: Schema.String.annotate({\n    description:\n      \"Identifies one logical reset attempt. A UUID is recommended; reuse the same value when retrying that attempt.\",\n  }),\n});\n\nexport type ClientRequest__ConversationTextRole = \"user\" | \"developer\" | \"assistant\";\nexport const ClientRequest__ConversationTextRole = Schema.Literals([\n  \"user\",\n  \"developer\",\n  \"assistant\",\n]);\n\nexport type ClientRequest__DynamicToolNamespaceTool = {\n  readonly deferLoading?: boolean;\n  readonly description: string;\n  readonly inputSchema: unknown;\n  readonly name: string;\n  readonly type: \"function\";\n};\nexport const ClientRequest__DynamicToolNamespaceTool = Schema.Union(\n  [\n    Schema.Struct({\n      deferLoading: Schema.optionalKey(Schema.Boolean),\n      description: Schema.String,\n      inputSchema: Schema.Unknown,\n      name: Schema.String,\n      type: Schema.Literal(\"function\").annotate({ title: \"FunctionDynamicToolNamespaceToolType\" }),\n    }).annotate({ title: \"FunctionDynamicToolNamespaceTool\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ExperimentalFeatureEnablementSetParams = {\n  readonly enablement: { readonly [x: string]: boolean };\n};\nexport const ClientRequest__ExperimentalFeatureEnablementSetParams = Schema.Struct({\n  enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({\n    description:\n      \"Process-wide runtime feature enablement keyed by canonical feature name.\\n\\nOnly named features are updated. Omitted features are left unchanged. Send an empty map for a no-op.\",\n  }),\n});\n\nexport type ClientRequest__ExperimentalFeatureListParams = {\n  readonly cursor?: string | null;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__ExperimentalFeatureListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional loaded thread id. Pass this when showing feature state for an existing thread so enablement is computed from that thread's refreshed config, including project-local config for the thread's cwd.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ExternalAgentConfigDetectParams = {\n  readonly cwds?: ReadonlyArray<string> | null;\n  readonly includeHome?: boolean;\n  readonly migrationSource?: string | null;\n  readonly source?: string | null;\n};\nexport const ClientRequest__ExternalAgentConfigDetectParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Zero or more working directories to include for repo-scoped detection.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeHome: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"If true, include detection under the user's home directory.\",\n    }),\n  ),\n  migrationSource: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional migration-source selector. Missing or unrecognized values use the default source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  source: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Deprecated field retained for compatibility. This field is ignored; use `migrationSource` to select the migration source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const ClientRequest__ExternalAgentConfigMigrationItemType = Schema.Literals([\n  \"AGENTS_MD\",\n  \"CONFIG\",\n  \"SKILLS\",\n  \"PLUGINS\",\n  \"MCP_SERVER_CONFIG\",\n  \"SUBAGENTS\",\n  \"HOOKS\",\n  \"COMMANDS\",\n  \"MEMORY\",\n  \"SESSIONS\",\n]);\n\nexport type ClientRequest__FeedbackUploadParams = {\n  readonly classification: string;\n  readonly extraLogFiles?: ReadonlyArray<string> | null;\n  readonly includeLogs?: boolean;\n  readonly reason?: string | null;\n  readonly tags?: { readonly [x: string]: string } | null;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__FeedbackUploadParams = Schema.Struct({\n  classification: Schema.String,\n  extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  includeLogs: Schema.optionalKey(Schema.Boolean),\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  tags: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__FsCopyParams = {\n  readonly destinationPath: string;\n  readonly recursive?: boolean;\n  readonly sourcePath: string;\n};\nexport const ClientRequest__FsCopyParams = Schema.Struct({\n  destinationPath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Required for directory copies; ignored for file copies.\",\n    }),\n  ),\n  sourcePath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"Copy a file or directory tree on the host filesystem.\" });\n\nexport type ClientRequest__FsCreateDirectoryParams = {\n  readonly path: string;\n  readonly recursive?: boolean | null;\n};\nexport const ClientRequest__FsCreateDirectoryParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether parent directories should also be created. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Create a directory on the host filesystem.\" });\n\nexport type ClientRequest__FsGetMetadataParams = { readonly path: string };\nexport const ClientRequest__FsGetMetadataParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"Request metadata for an absolute path.\" });\n\nexport type ClientRequest__FsReadDirectoryParams = { readonly path: string };\nexport const ClientRequest__FsReadDirectoryParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"List direct child names for a directory.\" });\n\nexport type ClientRequest__FsReadFileParams = { readonly path: string };\nexport const ClientRequest__FsReadFileParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"Read a file from the host filesystem.\" });\n\nexport type ClientRequest__FsRemoveParams = {\n  readonly force?: boolean | null;\n  readonly path: string;\n  readonly recursive?: boolean | null;\n};\nexport const ClientRequest__FsRemoveParams = Schema.Struct({\n  force: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether missing paths should be ignored. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether directory removal should recurse. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Remove a file or directory tree from the host filesystem.\" });\n\nexport type ClientRequest__FsUnwatchParams = { readonly watchId: string };\nexport const ClientRequest__FsUnwatchParams = Schema.Struct({\n  watchId: Schema.String.annotate({\n    description: \"Watch identifier previously provided to `fs/watch`.\",\n  }),\n}).annotate({ description: \"Stop filesystem watch notifications for a prior `fs/watch`.\" });\n\nexport type ClientRequest__FsWatchParams = { readonly path: string; readonly watchId: string };\nexport const ClientRequest__FsWatchParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  watchId: Schema.String.annotate({\n    description: \"Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.\",\n  }),\n}).annotate({ description: \"Start filesystem watch notifications for an absolute path.\" });\n\nexport type ClientRequest__FsWriteFileParams = {\n  readonly dataBase64: string;\n  readonly path: string;\n};\nexport const ClientRequest__FsWriteFileParams = Schema.Struct({\n  dataBase64: Schema.String.annotate({ description: \"File contents encoded as base64.\" }),\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ description: \"Write a file on the host filesystem.\" });\n\nexport type ClientRequest__FuzzyFileSearchParams = {\n  readonly cancellationToken?: string | null;\n  readonly query: string;\n  readonly roots: ReadonlyArray<string>;\n};\nexport const ClientRequest__FuzzyFileSearchParams = Schema.Struct({\n  cancellationToken: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  query: Schema.String,\n  roots: Schema.Array(Schema.String),\n});\n\nexport type ClientRequest__GetAccountParams = { readonly refreshToken?: boolean };\nexport const ClientRequest__GetAccountParams = Schema.Struct({\n  refreshToken: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When `true`, requests a proactive token refresh before returning.\\n\\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__HookMigration = { readonly name: string };\nexport const ClientRequest__HookMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__HooksListParams = { readonly cwds?: ReadonlyArray<string> };\nexport const ClientRequest__HooksListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"When empty, defaults to the current session working directory.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const ClientRequest__ImageDetail = Schema.Literals([\"auto\", \"low\", \"high\", \"original\"]);\n\nexport type ClientRequest__InitializeCapabilities = {\n  readonly experimentalApi?: boolean;\n  readonly mcpServerOpenaiFormElicitation?: boolean;\n  readonly optOutNotificationMethods?: ReadonlyArray<string> | null;\n  readonly requestAttestation?: boolean;\n};\nexport const ClientRequest__InitializeCapabilities = Schema.Struct({\n  experimentalApi: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Opt into receiving experimental API methods and fields.\",\n      default: false,\n    }),\n  ),\n  mcpServerOpenaiFormElicitation: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Allow downstream MCP servers to request OpenAI extended form elicitations.\",\n    }),\n  ),\n  optOutNotificationMethods: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Exact notification method names that should be suppressed for this connection (for example `thread/started`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  requestAttestation: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Opt into `attestation/generate` requests for upstream `x-oai-attestation`.\",\n      default: false,\n    }),\n  ),\n}).annotate({ description: \"Client-declared capabilities negotiated during initialize.\" });\n\nexport type ClientRequest__InternalChatMessageMetadataPassthrough = {\n  readonly turn_id?: string | null;\n};\nexport const ClientRequest__InternalChatMessageMetadataPassthrough = Schema.Struct({\n  turn_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({\n  description:\n    \"Internal Responses API passthrough metadata copied into underlying chat messages.\\n\\nResponses API strongly types this payload. Do not modify it without first getting API approval and making the corresponding Responses API change.\",\n});\n\nexport type ClientRequest__LegacyAppPathString = string;\nexport const ClientRequest__LegacyAppPathString = Schema.String;\n\nexport type ClientRequest__LocalShellAction = {\n  readonly command: ReadonlyArray<string>;\n  readonly env?: { readonly [x: string]: string } | null;\n  readonly timeout_ms?: number | null;\n  readonly type: \"exec\";\n  readonly user?: string | null;\n  readonly working_directory?: string | null;\n};\nexport const ClientRequest__LocalShellAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.Array(Schema.String),\n      env: Schema.optionalKey(\n        Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n      ),\n      timeout_ms: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"uint64\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"exec\").annotate({ title: \"ExecLocalShellActionType\" }),\n      user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"ExecLocalShellAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__LocalShellStatus = \"completed\" | \"in_progress\" | \"incomplete\";\nexport const ClientRequest__LocalShellStatus = Schema.Literals([\n  \"completed\",\n  \"in_progress\",\n  \"incomplete\",\n]);\n\nexport type ClientRequest__LoginAppBrand = \"codex\" | \"chatgpt\";\nexport const ClientRequest__LoginAppBrand = Schema.Literals([\"codex\", \"chatgpt\"]);\n\nexport type ClientRequest__MarketplaceAddParams = {\n  readonly refName?: string | null;\n  readonly source: string;\n  readonly sparsePaths?: ReadonlyArray<string> | null;\n};\nexport const ClientRequest__MarketplaceAddParams = Schema.Struct({\n  refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  source: Schema.String,\n  sparsePaths: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n});\n\nexport type ClientRequest__MarketplaceRemoveParams = { readonly marketplaceName: string };\nexport const ClientRequest__MarketplaceRemoveParams = Schema.Struct({\n  marketplaceName: Schema.String,\n});\n\nexport type ClientRequest__MarketplaceUpgradeParams = { readonly marketplaceName?: string | null };\nexport const ClientRequest__MarketplaceUpgradeParams = Schema.Struct({\n  marketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__McpResourceReadParams = {\n  readonly server: string;\n  readonly threadId?: string | null;\n  readonly uri: string;\n};\nexport const ClientRequest__McpResourceReadParams = Schema.Struct({\n  server: Schema.String,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n});\n\nexport type ClientRequest__McpServerMigration = { readonly name: string };\nexport const ClientRequest__McpServerMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__McpServerOauthLoginParams = {\n  readonly name: string;\n  readonly scopes?: ReadonlyArray<string> | null;\n  readonly threadId?: string | null;\n  readonly timeoutSecs?: number | null;\n};\nexport const ClientRequest__McpServerOauthLoginParams = Schema.Struct({\n  name: Schema.String,\n  scopes: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  timeoutSecs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type ClientRequest__McpServerStatusDetail = \"full\" | \"toolsAndAuthOnly\";\nexport const ClientRequest__McpServerStatusDetail = Schema.Literals([\"full\", \"toolsAndAuthOnly\"]);\n\nexport type ClientRequest__McpServerToolCallParams = {\n  readonly _meta?: unknown;\n  readonly arguments?: unknown;\n  readonly server: string;\n  readonly threadId: string;\n  readonly tool: string;\n};\nexport const ClientRequest__McpServerToolCallParams = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  arguments: Schema.optionalKey(Schema.Unknown),\n  server: Schema.String,\n  threadId: Schema.String,\n  tool: Schema.String,\n});\n\nexport type ClientRequest__MergeStrategy = \"replace\" | \"upsert\";\nexport const ClientRequest__MergeStrategy = Schema.Literals([\"replace\", \"upsert\"]);\n\nexport type ClientRequest__MessagePhase = \"commentary\" | \"final_answer\";\nexport const ClientRequest__MessagePhase = Schema.Literals([\"commentary\", \"final_answer\"]).annotate(\n  {\n    description:\n      'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n  },\n);\n\nexport type ClientRequest__ModeKind = \"plan\" | \"default\";\nexport const ClientRequest__ModeKind = Schema.Literals([\"plan\", \"default\"]).annotate({\n  description: \"Initial collaboration mode to use when the TUI starts.\",\n});\n\nexport type ClientRequest__ModelListParams = {\n  readonly cursor?: string | null;\n  readonly includeHidden?: boolean | null;\n  readonly limit?: number | null;\n};\nexport const ClientRequest__ModelListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeHidden: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"When true, include models that are hidden from the default picker list.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ModelProviderCapabilitiesReadParams = {};\nexport const ClientRequest__ModelProviderCapabilitiesReadParams = Schema.Struct({});\n\nexport type ClientRequest__PermissionProfileListParams = {\n  readonly cursor?: string | null;\n  readonly cwd?: string | null;\n  readonly limit?: number | null;\n};\nexport const ClientRequest__PermissionProfileListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional working directory to resolve project config layers.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to the full result set.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const ClientRequest__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type ClientRequest__PluginListMarketplaceKind =\n  | \"local\"\n  | \"vertical\"\n  | \"workspace-directory\"\n  | \"shared-with-me\"\n  | \"created-by-me-remote\";\nexport const ClientRequest__PluginListMarketplaceKind = Schema.Literals([\n  \"local\",\n  \"vertical\",\n  \"workspace-directory\",\n  \"shared-with-me\",\n  \"created-by-me-remote\",\n]);\n\nexport type ClientRequest__PluginShareCheckoutParams = { readonly remotePluginId: string };\nexport const ClientRequest__PluginShareCheckoutParams = Schema.Struct({\n  remotePluginId: Schema.String,\n});\n\nexport type ClientRequest__PluginShareDeleteParams = { readonly remotePluginId: string };\nexport const ClientRequest__PluginShareDeleteParams = Schema.Struct({\n  remotePluginId: Schema.String,\n});\n\nexport type ClientRequest__PluginShareDiscoverability = \"LISTED\" | \"UNLISTED\" | \"PRIVATE\";\nexport const ClientRequest__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type ClientRequest__PluginShareListParams = {};\nexport const ClientRequest__PluginShareListParams = Schema.Struct({});\n\nexport type ClientRequest__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const ClientRequest__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type ClientRequest__PluginShareTargetRole = \"reader\" | \"editor\";\nexport const ClientRequest__PluginShareTargetRole = Schema.Literals([\"reader\", \"editor\"]);\n\nexport type ClientRequest__PluginShareUpdateDiscoverability = \"UNLISTED\" | \"PRIVATE\" | \"LISTED\";\nexport const ClientRequest__PluginShareUpdateDiscoverability = Schema.Literals([\n  \"UNLISTED\",\n  \"PRIVATE\",\n  \"LISTED\",\n]);\n\nexport type ClientRequest__PluginSkillReadParams = {\n  readonly remoteMarketplaceName: string;\n  readonly remotePluginId: string;\n  readonly skillName: string;\n};\nexport const ClientRequest__PluginSkillReadParams = Schema.Struct({\n  remoteMarketplaceName: Schema.String,\n  remotePluginId: Schema.String,\n  skillName: Schema.String,\n});\n\nexport type ClientRequest__PluginUninstallParams = { readonly pluginId: string };\nexport const ClientRequest__PluginUninstallParams = Schema.Struct({ pluginId: Schema.String });\n\nexport type ClientRequest__PluginsMigration = {\n  readonly marketplaceName: string;\n  readonly pluginNames: ReadonlyArray<string>;\n};\nexport const ClientRequest__PluginsMigration = Schema.Struct({\n  marketplaceName: Schema.String,\n  pluginNames: Schema.Array(Schema.String),\n});\n\nexport type ClientRequest__ReasoningEffort = string;\nexport const ClientRequest__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type ClientRequest__ReasoningItemContent =\n  | { readonly text: string; readonly type: \"reasoning_text\" }\n  | { readonly text: string; readonly type: \"text\" };\nexport const ClientRequest__ReasoningItemContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"reasoning_text\").annotate({\n        title: \"ReasoningTextReasoningItemContentType\",\n      }),\n    }).annotate({ title: \"ReasoningTextReasoningItemContent\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"text\").annotate({ title: \"TextReasoningItemContentType\" }),\n    }).annotate({ title: \"TextReasoningItemContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ReasoningItemReasoningSummary = {\n  readonly text: string;\n  readonly type: \"summary_text\";\n};\nexport const ClientRequest__ReasoningItemReasoningSummary = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"summary_text\").annotate({\n        title: \"SummaryTextReasoningItemReasoningSummaryType\",\n      }),\n    }).annotate({ title: \"SummaryTextReasoningItemReasoningSummary\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ReasoningSummary = \"auto\" | \"concise\" | \"detailed\" | \"none\";\nexport const ClientRequest__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type ClientRequest__RequestId = string | number;\nexport const ClientRequest__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type ClientRequest__ResponsesApiWebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"open_page\"; readonly url?: string | null }\n  | {\n      readonly pattern?: string | null;\n      readonly type: \"find_in_page\";\n      readonly url?: string | null;\n    }\n  | { readonly type: \"other\" };\nexport const ClientRequest__ResponsesApiWebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"SearchResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"open_page\").annotate({\n        title: \"OpenPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"find_in_page\").annotate({\n        title: \"FindInPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"OtherResponsesApiWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ReviewDelivery = \"inline\" | \"detached\";\nexport const ClientRequest__ReviewDelivery = Schema.Literals([\"inline\", \"detached\"]);\n\nexport type ClientRequest__ReviewTarget =\n  | { readonly type: \"uncommittedChanges\" }\n  | { readonly branch: string; readonly type: \"baseBranch\" }\n  | { readonly sha: string; readonly title?: string | null; readonly type: \"commit\" }\n  | { readonly instructions: string; readonly type: \"custom\" };\nexport const ClientRequest__ReviewTarget = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"uncommittedChanges\").annotate({\n        title: \"UncommittedChangesReviewTargetType\",\n      }),\n    }).annotate({\n      title: \"UncommittedChangesReviewTarget\",\n      description: \"Review the working tree: staged, unstaged, and untracked files.\",\n    }),\n    Schema.Struct({\n      branch: Schema.String,\n      type: Schema.Literal(\"baseBranch\").annotate({ title: \"BaseBranchReviewTargetType\" }),\n    }).annotate({\n      title: \"BaseBranchReviewTarget\",\n      description: \"Review changes between the current branch and the given base branch.\",\n    }),\n    Schema.Struct({\n      sha: Schema.String,\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Optional human-readable label (e.g., commit subject) for UIs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"commit\").annotate({ title: \"CommitReviewTargetType\" }),\n    }).annotate({\n      title: \"CommitReviewTarget\",\n      description: \"Review the changes introduced by a specific commit.\",\n    }),\n    Schema.Struct({\n      instructions: Schema.String,\n      type: Schema.Literal(\"custom\").annotate({ title: \"CustomReviewTargetType\" }),\n    }).annotate({\n      title: \"CustomReviewTarget\",\n      description: \"Arbitrary instructions, equivalent to the old free-form prompt.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__SandboxMode = \"read-only\" | \"workspace-write\" | \"danger-full-access\";\nexport const ClientRequest__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type ClientRequest__SessionMigration = {\n  readonly cwd: string;\n  readonly path: string;\n  readonly title?: string | null;\n};\nexport const ClientRequest__SessionMigration = Schema.Struct({\n  cwd: Schema.String,\n  path: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__SkillMigration = { readonly name: string };\nexport const ClientRequest__SkillMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__SkillsListParams = {\n  readonly cwds?: ReadonlyArray<string>;\n  readonly forceReload?: boolean;\n};\nexport const ClientRequest__SkillsListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"When empty, defaults to the current session working directory.\",\n    }),\n  ),\n  forceReload: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, bypass the skills cache and re-scan skills from disk.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__SortDirection = \"asc\" | \"desc\";\nexport const ClientRequest__SortDirection = Schema.Literals([\"asc\", \"desc\"]);\n\nexport type ClientRequest__SubagentMigration = { readonly name: string };\nexport const ClientRequest__SubagentMigration = Schema.Struct({ name: Schema.String });\n\nexport type ClientRequest__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const ClientRequest__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ThreadApproveGuardianDeniedActionParams = {\n  readonly event: unknown;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadApproveGuardianDeniedActionParams = Schema.Struct({\n  event: Schema.Unknown.annotate({\n    description: \"Serialized `codex_protocol::protocol::GuardianAssessmentEvent`.\",\n  }),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadArchiveParams = { readonly threadId: string };\nexport const ClientRequest__ThreadArchiveParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadCompactStartParams = { readonly threadId: string };\nexport const ClientRequest__ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadDeleteParams = { readonly threadId: string };\nexport const ClientRequest__ThreadDeleteParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadGoalClearParams = { readonly threadId: string };\nexport const ClientRequest__ThreadGoalClearParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadGoalGetParams = { readonly threadId: string };\nexport const ClientRequest__ThreadGoalGetParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const ClientRequest__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type ClientRequest__ThreadInjectItemsParams = {\n  readonly items: ReadonlyArray<unknown>;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadInjectItemsParams = Schema.Struct({\n  items: Schema.Array(Schema.Unknown).annotate({\n    description: \"Raw Responses API items to append to the thread's model-visible history.\",\n  }),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadListCwdFilter = string | ReadonlyArray<string>;\nexport const ClientRequest__ThreadListCwdFilter = Schema.Union([\n  Schema.String,\n  Schema.Array(Schema.String),\n]);\n\nexport type ClientRequest__ThreadLoadedListParams = {\n  readonly cursor?: string | null;\n  readonly limit?: number | null;\n};\nexport const ClientRequest__ThreadLoadedListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to no limit.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ThreadMetadataGitInfoUpdateParams = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const ClientRequest__ThreadMetadataGitInfoUpdateParams = Schema.Struct({\n  branch: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  originUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sha: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__ThreadReadParams = {\n  readonly includeTurns?: boolean;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadReadParams = Schema.Struct({\n  includeTurns: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, include turns and their items from rollout history.\",\n    }),\n  ),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadRollbackParams = {\n  readonly numTurns: number;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadRollbackParams = Schema.Struct({\n  numTurns: Schema.Number.annotate({\n    description:\n      \"The number of turns to drop from the end of the thread. Must be >= 1.\\n\\nThis only modifies the thread's history and does not revert local file changes that have been made by the agent. Clients are responsible for reverting these changes.\",\n    format: \"uint32\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  threadId: Schema.String,\n}).annotate({ description: \"DEPRECATED: `thread/rollback` will be removed soon.\" });\n\nexport type ClientRequest__ThreadSetNameParams = {\n  readonly name: string;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadSetNameParams = Schema.Struct({\n  name: Schema.String,\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadShellCommandParams = {\n  readonly command: string;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadShellCommandParams = Schema.Struct({\n  command: Schema.String.annotate({\n    description:\n      \"Shell command string evaluated by the thread's configured shell. Unlike `command/exec`, this intentionally preserves shell syntax such as pipes, redirects, and quoting. This runs unsandboxed with full access rather than inheriting the thread sandbox policy.\",\n  }),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadSortKey = \"created_at\" | \"updated_at\" | \"recency_at\";\nexport const ClientRequest__ThreadSortKey = Schema.Literals([\n  \"created_at\",\n  \"updated_at\",\n  \"recency_at\",\n]);\n\nexport type ClientRequest__ThreadSource = string;\nexport const ClientRequest__ThreadSource = Schema.String;\n\nexport type ClientRequest__ThreadSourceKind =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"subAgent\"\n  | \"subAgentReview\"\n  | \"subAgentCompact\"\n  | \"subAgentThreadSpawn\"\n  | \"subAgentOther\"\n  | \"unknown\";\nexport const ClientRequest__ThreadSourceKind = Schema.Literals([\n  \"cli\",\n  \"vscode\",\n  \"exec\",\n  \"appServer\",\n  \"subAgent\",\n  \"subAgentReview\",\n  \"subAgentCompact\",\n  \"subAgentThreadSpawn\",\n  \"subAgentOther\",\n  \"unknown\",\n]);\n\nexport type ClientRequest__ThreadStartSource = \"startup\" | \"clear\";\nexport const ClientRequest__ThreadStartSource = Schema.Literals([\"startup\", \"clear\"]);\n\nexport type ClientRequest__ThreadUnarchiveParams = { readonly threadId: string };\nexport const ClientRequest__ThreadUnarchiveParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__ThreadUnsubscribeParams = { readonly threadId: string };\nexport const ClientRequest__ThreadUnsubscribeParams = Schema.Struct({ threadId: Schema.String });\n\nexport type ClientRequest__TurnInterruptParams = {\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ClientRequest__TurnInterruptParams = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ClientRequest__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const ClientRequest__TurnItemsView = Schema.Literals([\"notLoaded\", \"summary\", \"full\"]);\n\nexport type ClientRequest__WindowsSandboxSetupMode = \"elevated\" | \"unelevated\";\nexport const ClientRequest__WindowsSandboxSetupMode = Schema.Literals([\"elevated\", \"unelevated\"]);\n\nexport type CommandExecutionRequestApprovalParams__AbsolutePathBuf = string;\nexport const CommandExecutionRequestApprovalParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type CommandExecutionRequestApprovalParams__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const CommandExecutionRequestApprovalParams__FileSystemAccessMode = Schema.Literals([\n  \"read\",\n  \"write\",\n  \"deny\",\n]);\n\nexport type CommandExecutionRequestApprovalParams__LegacyAppPathString = string;\nexport const CommandExecutionRequestApprovalParams__LegacyAppPathString = Schema.String;\n\nexport type CommandExecutionRequestApprovalParams__NetworkApprovalProtocol =\n  | \"http\"\n  | \"https\"\n  | \"socks5Tcp\"\n  | \"socks5Udp\";\nexport const CommandExecutionRequestApprovalParams__NetworkApprovalProtocol = Schema.Literals([\n  \"http\",\n  \"https\",\n  \"socks5Tcp\",\n  \"socks5Udp\",\n]);\n\nexport type CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type DynamicToolCallResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const DynamicToolCallResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ExecCommandApprovalParams__ParsedCommand =\n  | { readonly cmd: string; readonly name: string; readonly path: string; readonly type: \"read\" }\n  | { readonly cmd: string; readonly path?: string | null; readonly type: \"list_files\" }\n  | {\n      readonly cmd: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly cmd: string; readonly type: \"unknown\" };\nexport const ExecCommandApprovalParams__ParsedCommand = Schema.Union(\n  [\n    Schema.Struct({\n      cmd: Schema.String,\n      name: Schema.String,\n      path: Schema.String.annotate({\n        description:\n          \"(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.\",\n      }),\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadParsedCommandType\" }),\n    }).annotate({ title: \"ReadParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"list_files\").annotate({ title: \"ListFilesParsedCommandType\" }),\n    }).annotate({ title: \"ListFilesParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchParsedCommandType\" }),\n    }).annotate({ title: \"SearchParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownParsedCommandType\" }),\n    }).annotate({ title: \"UnknownParsedCommand\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ExecCommandApprovalParams__ThreadId = string;\nexport const ExecCommandApprovalParams__ThreadId = Schema.String;\n\nexport type ExecCommandApprovalResponse__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const ExecCommandApprovalResponse__NetworkPolicyRuleAction = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type FileChangeRequestApprovalResponse__FileChangeApprovalDecision =\n  | \"accept\"\n  | \"acceptForSession\"\n  | \"decline\"\n  | \"cancel\";\nexport const FileChangeRequestApprovalResponse__FileChangeApprovalDecision = Schema.Literals([\n  \"accept\",\n  \"acceptForSession\",\n  \"decline\",\n  \"cancel\",\n]);\n\nexport type FuzzyFileSearchResponse__FuzzyFileSearchMatchType = \"file\" | \"directory\";\nexport const FuzzyFileSearchResponse__FuzzyFileSearchMatchType = Schema.Literals([\n  \"file\",\n  \"directory\",\n]);\n\nexport type FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType =\n  | \"file\"\n  | \"directory\";\nexport const FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType = Schema.Literals([\n  \"file\",\n  \"directory\",\n]);\n\nexport type JSONRPCError__JSONRPCErrorError = {\n  readonly code: number;\n  readonly data?: unknown;\n  readonly message: string;\n};\nexport const JSONRPCError__JSONRPCErrorError = Schema.Struct({\n  code: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  data: Schema.optionalKey(Schema.Unknown),\n  message: Schema.String,\n});\n\nexport type JSONRPCError__RequestId = string | number;\nexport const JSONRPCError__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type JSONRPCMessage__JSONRPCErrorError = {\n  readonly code: number;\n  readonly data?: unknown;\n  readonly message: string;\n};\nexport const JSONRPCMessage__JSONRPCErrorError = Schema.Struct({\n  code: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  data: Schema.optionalKey(Schema.Unknown),\n  message: Schema.String,\n});\n\nexport type JSONRPCMessage__JSONRPCNotification = {\n  readonly method: string;\n  readonly params?: unknown;\n};\nexport const JSONRPCMessage__JSONRPCNotification = Schema.Struct({\n  method: Schema.String,\n  params: Schema.optionalKey(Schema.Unknown),\n}).annotate({ description: \"A notification which does not expect a response.\" });\n\nexport type JSONRPCMessage__RequestId = string | number;\nexport const JSONRPCMessage__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type JSONRPCMessage__W3cTraceContext = {\n  readonly traceparent?: string | null;\n  readonly tracestate?: string | null;\n};\nexport const JSONRPCMessage__W3cTraceContext = Schema.Struct({\n  traceparent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  tracestate: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type JSONRPCRequest__RequestId = string | number;\nexport const JSONRPCRequest__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type JSONRPCRequest__W3cTraceContext = {\n  readonly traceparent?: string | null;\n  readonly tracestate?: string | null;\n};\nexport const JSONRPCRequest__W3cTraceContext = Schema.Struct({\n  traceparent: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  tracestate: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type JSONRPCResponse__RequestId = string | number;\nexport const JSONRPCResponse__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type McpServerElicitationRequestParams__McpElicitationArrayType = \"array\";\nexport const McpServerElicitationRequestParams__McpElicitationArrayType = Schema.Literal(\"array\");\n\nexport type McpServerElicitationRequestParams__McpElicitationBooleanType = \"boolean\";\nexport const McpServerElicitationRequestParams__McpElicitationBooleanType =\n  Schema.Literal(\"boolean\");\n\nexport type McpServerElicitationRequestParams__McpElicitationConstOption = {\n  readonly const: string;\n  readonly title: string;\n};\nexport const McpServerElicitationRequestParams__McpElicitationConstOption = Schema.Struct({\n  const: Schema.String,\n  title: Schema.String,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationNumberType = \"number\" | \"integer\";\nexport const McpServerElicitationRequestParams__McpElicitationNumberType = Schema.Literals([\n  \"number\",\n  \"integer\",\n]);\n\nexport type McpServerElicitationRequestParams__McpElicitationObjectType = \"object\";\nexport const McpServerElicitationRequestParams__McpElicitationObjectType = Schema.Literal(\"object\");\n\nexport type McpServerElicitationRequestParams__McpElicitationStringFormat =\n  | \"email\"\n  | \"uri\"\n  | \"date\"\n  | \"date-time\";\nexport const McpServerElicitationRequestParams__McpElicitationStringFormat = Schema.Literals([\n  \"email\",\n  \"uri\",\n  \"date\",\n  \"date-time\",\n]);\n\nexport type McpServerElicitationRequestParams__McpElicitationStringType = \"string\";\nexport const McpServerElicitationRequestParams__McpElicitationStringType = Schema.Literal(\"string\");\n\nexport type McpServerElicitationRequestResponse__McpServerElicitationAction =\n  | \"accept\"\n  | \"decline\"\n  | \"cancel\";\nexport const McpServerElicitationRequestResponse__McpServerElicitationAction = Schema.Literals([\n  \"accept\",\n  \"decline\",\n  \"cancel\",\n]);\n\nexport type PermissionsRequestApprovalParams__AbsolutePathBuf = string;\nexport const PermissionsRequestApprovalParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type PermissionsRequestApprovalParams__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const PermissionsRequestApprovalParams__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type PermissionsRequestApprovalParams__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const PermissionsRequestApprovalParams__FileSystemAccessMode = Schema.Literals([\n  \"read\",\n  \"write\",\n  \"deny\",\n]);\n\nexport type PermissionsRequestApprovalParams__LegacyAppPathString = string;\nexport const PermissionsRequestApprovalParams__LegacyAppPathString = Schema.String;\n\nexport type PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const PermissionsRequestApprovalResponse__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type PermissionsRequestApprovalResponse__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const PermissionsRequestApprovalResponse__FileSystemAccessMode = Schema.Literals([\n  \"read\",\n  \"write\",\n  \"deny\",\n]);\n\nexport type PermissionsRequestApprovalResponse__LegacyAppPathString = string;\nexport const PermissionsRequestApprovalResponse__LegacyAppPathString = Schema.String;\n\nexport type ServerNotification__AbsolutePathBuf = string;\nexport const ServerNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type ServerNotification__AccountLoginCompletedNotification = {\n  readonly error?: string | null;\n  readonly loginId?: string | null;\n  readonly success: boolean;\n};\nexport const ServerNotification__AccountLoginCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  loginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  success: Schema.Boolean,\n});\n\nexport type ServerNotification__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const ServerNotification__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type ServerNotification__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const ServerNotification__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type ServerNotification__AgentMessageDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__AgentMessageDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__AgentPath = string;\nexport const ServerNotification__AgentPath = Schema.String;\n\nexport type ServerNotification__AppBranding = {\n  readonly category?: string | null;\n  readonly developer?: string | null;\n  readonly isDiscoverableApp: boolean;\n  readonly privacyPolicy?: string | null;\n  readonly termsOfService?: string | null;\n  readonly website?: string | null;\n};\nexport const ServerNotification__AppBranding = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isDiscoverableApp: Schema.Boolean,\n  privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type ServerNotification__AppReview = { readonly status: string };\nexport const ServerNotification__AppReview = Schema.Struct({ status: Schema.String });\n\nexport type ServerNotification__AppScreenshot = {\n  readonly fileId?: string | null;\n  readonly url?: string | null;\n  readonly userPrompt: string;\n};\nexport const ServerNotification__AppScreenshot = Schema.Struct({\n  fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  userPrompt: Schema.String,\n});\n\nexport type ServerNotification__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const ServerNotification__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type ServerNotification__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const ServerNotification__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__AuthMode =\n  | \"apikey\"\n  | \"chatgpt\"\n  | \"chatgptAuthTokens\"\n  | \"headers\"\n  | \"agentIdentity\"\n  | \"personalAccessToken\"\n  | \"bedrockApiKey\";\nexport const ServerNotification__AuthMode = Schema.Literals([\n  \"apikey\",\n  \"chatgpt\",\n  \"chatgptAuthTokens\",\n  \"headers\",\n  \"agentIdentity\",\n  \"personalAccessToken\",\n  \"bedrockApiKey\",\n]).annotate({ description: \"Authentication mode for OpenAI-backed providers.\" });\n\nexport type ServerNotification__AutoReviewDecisionSource = \"agent\";\nexport const ServerNotification__AutoReviewDecisionSource = Schema.Literal(\"agent\").annotate({\n  description: \"[UNSTABLE] Source that produced a terminal approval auto-review decision.\",\n});\n\nexport type ServerNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const ServerNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type ServerNotification__CommandExecOutputDeltaNotification = {\n  readonly capReached: boolean;\n  readonly deltaBase64: string;\n  readonly processId: string;\n  readonly stream: \"stdout\" | \"stderr\";\n};\nexport const ServerNotification__CommandExecOutputDeltaNotification = Schema.Struct({\n  capReached: Schema.Boolean.annotate({\n    description:\n      \"`true` on the final streamed chunk for a stream when `outputBytesCap` truncated later output on that stream.\",\n  }),\n  deltaBase64: Schema.String.annotate({ description: \"Base64-encoded output bytes.\" }),\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n  stream: Schema.Literals([\"stdout\", \"stderr\"]).annotate({\n    description: \"Stream label for `command/exec/outputDelta` notifications.\",\n  }),\n}).annotate({\n  description:\n    \"Base64-encoded output chunk emitted for a streaming `command/exec` request.\\n\\nThese notifications are connection-scoped. If the originating connection closes, the server terminates the process.\",\n});\n\nexport type ServerNotification__CommandExecutionOutputDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__CommandExecutionOutputDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const ServerNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type ServerNotification__ContextCompactedNotification = {\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ContextCompactedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ description: \"Deprecated: Use `ContextCompaction` item type instead.\" });\n\nexport type ServerNotification__CreditsSnapshot = {\n  readonly balance?: string | null;\n  readonly hasCredits: boolean;\n  readonly unlimited: boolean;\n};\nexport const ServerNotification__CreditsSnapshot = Schema.Struct({\n  balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  hasCredits: Schema.Boolean,\n  unlimited: Schema.Boolean,\n});\n\nexport type ServerNotification__DeprecationNoticeNotification = {\n  readonly details?: string | null;\n  readonly summary: string;\n};\nexport const ServerNotification__DeprecationNoticeNotification = Schema.Struct({\n  details: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional extra guidance, such as migration steps or rationale.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  summary: Schema.String.annotate({ description: \"Concise summary of what is deprecated.\" }),\n});\n\nexport type ServerNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const ServerNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const ServerNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type ServerNotification__EnvironmentConnectionNotification = {\n  readonly environmentId: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__EnvironmentConnectionNotification = Schema.Struct({\n  environmentId: Schema.String,\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const ServerNotification__ExternalAgentConfigMigrationItemType = Schema.Literals([\n  \"AGENTS_MD\",\n  \"CONFIG\",\n  \"SKILLS\",\n  \"PLUGINS\",\n  \"MCP_SERVER_CONFIG\",\n  \"SUBAGENTS\",\n  \"HOOKS\",\n  \"COMMANDS\",\n  \"MEMORY\",\n  \"SESSIONS\",\n]);\n\nexport type ServerNotification__FileChangeOutputDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__FileChangeOutputDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"Deprecated legacy notification for `apply_patch` textual output.\\n\\nThe server no longer emits this notification.\",\n});\n\nexport type ServerNotification__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const ServerNotification__FileSystemAccessMode = Schema.Literals([\"read\", \"write\", \"deny\"]);\n\nexport type ServerNotification__FuzzyFileSearchMatchType = \"file\" | \"directory\";\nexport const ServerNotification__FuzzyFileSearchMatchType = Schema.Literals([\"file\", \"directory\"]);\n\nexport type ServerNotification__FuzzyFileSearchSessionCompletedNotification = {\n  readonly sessionId: string;\n};\nexport const ServerNotification__FuzzyFileSearchSessionCompletedNotification = Schema.Struct({\n  sessionId: Schema.String,\n});\n\nexport type ServerNotification__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const ServerNotification__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__GuardianApprovalReviewStatus =\n  | \"inProgress\"\n  | \"approved\"\n  | \"denied\"\n  | \"timedOut\"\n  | \"aborted\";\nexport const ServerNotification__GuardianApprovalReviewStatus = Schema.Literals([\n  \"inProgress\",\n  \"approved\",\n  \"denied\",\n  \"timedOut\",\n  \"aborted\",\n]).annotate({ description: \"[UNSTABLE] Lifecycle state for an approval auto-review.\" });\n\nexport type ServerNotification__GuardianCommandSource = \"shell\" | \"unifiedExec\";\nexport const ServerNotification__GuardianCommandSource = Schema.Literals([\"shell\", \"unifiedExec\"]);\n\nexport type ServerNotification__GuardianRiskLevel = \"low\" | \"medium\" | \"high\" | \"critical\";\nexport const ServerNotification__GuardianRiskLevel = Schema.Literals([\n  \"low\",\n  \"medium\",\n  \"high\",\n  \"critical\",\n]).annotate({ description: \"[UNSTABLE] Risk level assigned by approval auto-review.\" });\n\nexport type ServerNotification__GuardianUserAuthorization = \"unknown\" | \"low\" | \"medium\" | \"high\";\nexport const ServerNotification__GuardianUserAuthorization = Schema.Literals([\n  \"unknown\",\n  \"low\",\n  \"medium\",\n  \"high\",\n]).annotate({ description: \"[UNSTABLE] Authorization level assigned by approval auto-review.\" });\n\nexport type ServerNotification__GuardianWarningNotification = {\n  readonly message: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__GuardianWarningNotification = Schema.Struct({\n  message: Schema.String.annotate({\n    description: \"Concise guardian warning message for the user.\",\n  }),\n  threadId: Schema.String.annotate({ description: \"Thread target for the guardian warning.\" }),\n});\n\nexport type ServerNotification__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const ServerNotification__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type ServerNotification__HookExecutionMode = \"sync\" | \"async\";\nexport const ServerNotification__HookExecutionMode = Schema.Literals([\"sync\", \"async\"]);\n\nexport type ServerNotification__HookHandlerType = \"command\" | \"prompt\" | \"agent\";\nexport const ServerNotification__HookHandlerType = Schema.Literals([\"command\", \"prompt\", \"agent\"]);\n\nexport type ServerNotification__HookOutputEntryKind =\n  | \"warning\"\n  | \"stop\"\n  | \"feedback\"\n  | \"context\"\n  | \"error\";\nexport const ServerNotification__HookOutputEntryKind = Schema.Literals([\n  \"warning\",\n  \"stop\",\n  \"feedback\",\n  \"context\",\n  \"error\",\n]);\n\nexport type ServerNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const ServerNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type ServerNotification__HookRunStatus =\n  | \"running\"\n  | \"completed\"\n  | \"failed\"\n  | \"blocked\"\n  | \"stopped\";\nexport const ServerNotification__HookRunStatus = Schema.Literals([\n  \"running\",\n  \"completed\",\n  \"failed\",\n  \"blocked\",\n  \"stopped\",\n]);\n\nexport type ServerNotification__HookScope = \"thread\" | \"turn\";\nexport const ServerNotification__HookScope = Schema.Literals([\"thread\", \"turn\"]);\n\nexport type ServerNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const ServerNotification__ImageDetail = Schema.Literals([\"auto\", \"low\", \"high\", \"original\"]);\n\nexport type ServerNotification__LegacyAppPathString = string;\nexport const ServerNotification__LegacyAppPathString = Schema.String;\n\nexport type ServerNotification__McpServerOauthLoginCompletedNotification = {\n  readonly error?: string | null;\n  readonly name: string;\n  readonly success: boolean;\n  readonly threadId?: string | null;\n};\nexport const ServerNotification__McpServerOauthLoginCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  success: Schema.Boolean,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__McpServerStartupFailureReason = \"reauthenticationRequired\";\nexport const ServerNotification__McpServerStartupFailureReason = Schema.Literal(\n  \"reauthenticationRequired\",\n);\n\nexport type ServerNotification__McpServerStartupState =\n  | \"starting\"\n  | \"ready\"\n  | \"failed\"\n  | \"cancelled\";\nexport const ServerNotification__McpServerStartupState = Schema.Literals([\n  \"starting\",\n  \"ready\",\n  \"failed\",\n  \"cancelled\",\n]);\n\nexport type ServerNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const ServerNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__McpToolCallError = { readonly message: string };\nexport const ServerNotification__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type ServerNotification__McpToolCallProgressNotification = {\n  readonly itemId: string;\n  readonly message: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__McpToolCallProgressNotification = Schema.Struct({\n  itemId: Schema.String,\n  message: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const ServerNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type ServerNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const ServerNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type ServerNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const ServerNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type ServerNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const ServerNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type ServerNotification__ModeKind = \"plan\" | \"default\";\nexport const ServerNotification__ModeKind = Schema.Literals([\"plan\", \"default\"]).annotate({\n  description: \"Initial collaboration mode to use when the TUI starts.\",\n});\n\nexport type ServerNotification__ModelRerouteReason = \"highRiskCyberActivity\";\nexport const ServerNotification__ModelRerouteReason = Schema.Literal(\"highRiskCyberActivity\");\n\nexport type ServerNotification__ModelSafetyBufferingUpdatedNotification = {\n  readonly fasterModel?: string | null;\n  readonly model: string;\n  readonly reasons: ReadonlyArray<string>;\n  readonly showBufferingUi: boolean;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly useCases: ReadonlyArray<string>;\n};\nexport const ServerNotification__ModelSafetyBufferingUpdatedNotification = Schema.Struct({\n  fasterModel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasons: Schema.Array(Schema.String),\n  showBufferingUi: Schema.Boolean,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  useCases: Schema.Array(Schema.String),\n});\n\nexport type ServerNotification__ModelVerification = \"trustedAccessForCyber\";\nexport const ServerNotification__ModelVerification = Schema.Literal(\"trustedAccessForCyber\");\n\nexport type ServerNotification__NetworkApprovalProtocol =\n  | \"http\"\n  | \"https\"\n  | \"socks5Tcp\"\n  | \"socks5Udp\";\nexport const ServerNotification__NetworkApprovalProtocol = Schema.Literals([\n  \"http\",\n  \"https\",\n  \"socks5Tcp\",\n  \"socks5Udp\",\n]);\n\nexport type ServerNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const ServerNotification__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type ServerNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const ServerNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type ServerNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const ServerNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const ServerNotification__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type ServerNotification__PlanDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__PlanDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.\",\n});\n\nexport type ServerNotification__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const ServerNotification__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type ServerNotification__ProcessExitedNotification = {\n  readonly exitCode: number;\n  readonly processHandle: string;\n  readonly stderr: string;\n  readonly stderrCapReached: boolean;\n  readonly stdout: string;\n  readonly stdoutCapReached: boolean;\n};\nexport const ServerNotification__ProcessExitedNotification = Schema.Struct({\n  exitCode: Schema.Number.annotate({ description: \"Process exit code.\", format: \"int32\" }).check(\n    Schema.isInt(),\n  ),\n  processHandle: Schema.String.annotate({\n    description: \"Client-supplied, connection-scoped `processHandle` from `process/spawn`.\",\n  }),\n  stderr: Schema.String.annotate({\n    description:\n      \"Buffered stderr capture.\\n\\nEmpty when stderr was streamed via `process/outputDelta`.\",\n  }),\n  stderrCapReached: Schema.Boolean.annotate({\n    description:\n      \"Whether stderr reached `outputBytesCap`.\\n\\nIn streaming mode, stderr is empty and cap state is also reported on the final stderr `process/outputDelta` notification.\",\n  }),\n  stdout: Schema.String.annotate({\n    description:\n      \"Buffered stdout capture.\\n\\nEmpty when stdout was streamed via `process/outputDelta`.\",\n  }),\n  stdoutCapReached: Schema.Boolean.annotate({\n    description:\n      \"Whether stdout reached `outputBytesCap`.\\n\\nIn streaming mode, stdout is empty and cap state is also reported on the final stdout `process/outputDelta` notification.\",\n  }),\n}).annotate({ description: \"Final process exit notification for `process/spawn`.\" });\n\nexport type ServerNotification__ProcessOutputDeltaNotification = {\n  readonly capReached: boolean;\n  readonly deltaBase64: string;\n  readonly processHandle: string;\n  readonly stream: \"stdout\" | \"stderr\";\n};\nexport const ServerNotification__ProcessOutputDeltaNotification = Schema.Struct({\n  capReached: Schema.Boolean.annotate({\n    description:\n      \"True on the final streamed chunk for this stream when output was truncated by `outputBytesCap`.\",\n  }),\n  deltaBase64: Schema.String.annotate({ description: \"Base64-encoded output bytes.\" }),\n  processHandle: Schema.String.annotate({\n    description: \"Client-supplied, connection-scoped `processHandle` from `process/spawn`.\",\n  }),\n  stream: Schema.Literals([\"stdout\", \"stderr\"]).annotate({\n    description: \"Stream label for `process/outputDelta` notifications.\",\n  }),\n}).annotate({\n  description: \"Base64-encoded output chunk emitted for a streaming `process/spawn` request.\",\n});\n\nexport type ServerNotification__RateLimitReachedType =\n  | \"rate_limit_reached\"\n  | \"workspace_owner_credits_depleted\"\n  | \"workspace_member_credits_depleted\"\n  | \"workspace_owner_usage_limit_reached\"\n  | \"workspace_member_usage_limit_reached\";\nexport const ServerNotification__RateLimitReachedType = Schema.Literals([\n  \"rate_limit_reached\",\n  \"workspace_owner_credits_depleted\",\n  \"workspace_member_credits_depleted\",\n  \"workspace_owner_usage_limit_reached\",\n  \"workspace_member_usage_limit_reached\",\n]);\n\nexport type ServerNotification__RateLimitWindow = {\n  readonly resetsAt?: number | null;\n  readonly usedPercent: number;\n  readonly windowDurationMins?: number | null;\n};\nexport const ServerNotification__RateLimitWindow = Schema.Struct({\n  resetsAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  usedPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  windowDurationMins: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type ServerNotification__RealtimeConversationVersion = \"v1\" | \"v2\" | \"v3\";\nexport const ServerNotification__RealtimeConversationVersion = Schema.Literals([\"v1\", \"v2\", \"v3\"]);\n\nexport type ServerNotification__ReasoningEffort = string;\nexport const ServerNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type ServerNotification__ReasoningSummary = \"auto\" | \"concise\" | \"detailed\" | \"none\";\nexport const ServerNotification__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type ServerNotification__ReasoningSummaryPartAddedNotification = {\n  readonly itemId: string;\n  readonly summaryIndex: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ReasoningSummaryPartAddedNotification = Schema.Struct({\n  itemId: Schema.String,\n  summaryIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__ReasoningSummaryTextDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly summaryIndex: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ReasoningSummaryTextDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  summaryIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__ReasoningTextDeltaNotification = {\n  readonly contentIndex: number;\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ReasoningTextDeltaNotification = Schema.Struct({\n  contentIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__RemoteControlConnectionStatus =\n  | \"disabled\"\n  | \"connecting\"\n  | \"connected\"\n  | \"errored\";\nexport const ServerNotification__RemoteControlConnectionStatus = Schema.Literals([\n  \"disabled\",\n  \"connecting\",\n  \"connected\",\n  \"errored\",\n]);\n\nexport type ServerNotification__RequestId = string | number;\nexport const ServerNotification__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type ServerNotification__SkillsChangedNotification = {};\nexport const ServerNotification__SkillsChangedNotification = Schema.Struct({}).annotate({\n  description:\n    \"Notification emitted when watched local skill files change.\\n\\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.\",\n});\n\nexport type ServerNotification__SpendControlLimitSnapshot = {\n  readonly limit: string;\n  readonly remainingPercent: number;\n  readonly resetsAt: number;\n  readonly used: string;\n};\nexport const ServerNotification__SpendControlLimitSnapshot = Schema.Struct({\n  limit: Schema.String,\n  remainingPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  resetsAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  used: Schema.String,\n});\n\nexport type ServerNotification__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const ServerNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type ServerNotification__TerminalInteractionNotification = {\n  readonly itemId: string;\n  readonly processId: string;\n  readonly stdin: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__TerminalInteractionNotification = Schema.Struct({\n  itemId: Schema.String,\n  processId: Schema.String,\n  stdin: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const ServerNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__TextPosition = { readonly column: number; readonly line: number };\nexport const ServerNotification__TextPosition = Schema.Struct({\n  column: Schema.Number.annotate({\n    description: \"1-based column number (in Unicode scalar values).\",\n    format: \"uint\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  line: Schema.Number.annotate({ description: \"1-based line number.\", format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type ServerNotification__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const ServerNotification__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type ServerNotification__ThreadArchivedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadArchivedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadClosedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadClosedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadDeletedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadDeletedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadGoalClearedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadGoalClearedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const ServerNotification__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type ServerNotification__ThreadId = string;\nexport const ServerNotification__ThreadId = Schema.String;\n\nexport type ServerNotification__ThreadNameUpdatedNotification = {\n  readonly threadId: string;\n  readonly threadName?: string | null;\n};\nexport const ServerNotification__ThreadNameUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  threadName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__ThreadRealtimeAudioChunk = {\n  readonly data: string;\n  readonly itemId?: string | null;\n  readonly numChannels: number;\n  readonly sampleRate: number;\n  readonly samplesPerChannel?: number | null;\n};\nexport const ServerNotification__ThreadRealtimeAudioChunk = Schema.Struct({\n  data: Schema.String,\n  itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  numChannels: Schema.Number.annotate({ format: \"uint16\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  sampleRate: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  samplesPerChannel: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - thread realtime audio chunk.\" });\n\nexport type ServerNotification__ThreadRealtimeClosedNotification = {\n  readonly reason?: string | null;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeClosedNotification = Schema.Struct({\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - emitted when thread realtime transport closes.\" });\n\nexport type ServerNotification__ThreadRealtimeErrorNotification = {\n  readonly message: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeErrorNotification = Schema.Struct({\n  message: Schema.String,\n  threadId: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - emitted when thread realtime encounters an error.\" });\n\nexport type ServerNotification__ThreadRealtimeItemAddedNotification = {\n  readonly item: unknown;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeItemAddedNotification = Schema.Struct({\n  item: Schema.Unknown,\n  threadId: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.\",\n});\n\nexport type ServerNotification__ThreadRealtimeSdpNotification = {\n  readonly sdp: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeSdpNotification = Schema.Struct({\n  sdp: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.\",\n});\n\nexport type ServerNotification__ThreadRealtimeTranscriptDeltaNotification = {\n  readonly delta: string;\n  readonly role: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeTranscriptDeltaNotification = Schema.Struct({\n  delta: Schema.String.annotate({ description: \"Live transcript delta from the realtime event.\" }),\n  role: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  description:\n    \"EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.\",\n});\n\nexport type ServerNotification__ThreadRealtimeTranscriptDoneNotification = {\n  readonly role: string;\n  readonly text: string;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeTranscriptDoneNotification = Schema.Struct({\n  role: Schema.String,\n  text: Schema.String.annotate({ description: \"Final complete text for the transcript part.\" }),\n  threadId: Schema.String,\n}).annotate({\n  description:\n    \"EXPERIMENTAL - final transcript text emitted when realtime completes a transcript part.\",\n});\n\nexport type ServerNotification__ThreadSource = string;\nexport const ServerNotification__ThreadSource = Schema.String;\n\nexport type ServerNotification__ThreadUnarchivedNotification = { readonly threadId: string };\nexport const ServerNotification__ThreadUnarchivedNotification = Schema.Struct({\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__TokenUsageBreakdown = {\n  readonly cacheWriteInputTokens?: number;\n  readonly cachedInputTokens: number;\n  readonly inputTokens: number;\n  readonly outputTokens: number;\n  readonly reasoningOutputTokens: number;\n  readonly totalTokens: number;\n};\nexport const ServerNotification__TokenUsageBreakdown = Schema.Struct({\n  cacheWriteInputTokens: Schema.optionalKey(\n    Schema.Number.annotate({ default: 0, format: \"int64\" }).check(Schema.isInt()),\n  ),\n  cachedInputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  inputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  outputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  reasoningOutputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  totalTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type ServerNotification__TurnDiffUpdatedNotification = {\n  readonly diff: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__TurnDiffUpdatedNotification = Schema.Struct({\n  diff: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.\",\n});\n\nexport type ServerNotification__TurnModerationMetadataNotification = {\n  readonly metadata: unknown;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__TurnModerationMetadataNotification = Schema.Struct({\n  metadata: Schema.Unknown,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__TurnPlanStepStatus = \"pending\" | \"inProgress\" | \"completed\";\nexport const ServerNotification__TurnPlanStepStatus = Schema.Literals([\n  \"pending\",\n  \"inProgress\",\n  \"completed\",\n]);\n\nexport type ServerNotification__TurnStatus = \"completed\" | \"interrupted\" | \"failed\" | \"inProgress\";\nexport const ServerNotification__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type ServerNotification__WarningNotification = {\n  readonly message: string;\n  readonly threadId?: string | null;\n};\nexport const ServerNotification__WarningNotification = Schema.Struct({\n  message: Schema.String.annotate({ description: \"Concise warning message for the user.\" }),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional thread target when the warning applies to a specific thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const ServerNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__WindowsSandboxSetupMode = \"elevated\" | \"unelevated\";\nexport const ServerNotification__WindowsSandboxSetupMode = Schema.Literals([\n  \"elevated\",\n  \"unelevated\",\n]);\n\nexport type ServerNotification__WindowsWorldWritableWarningNotification = {\n  readonly extraCount: number;\n  readonly failedScan: boolean;\n  readonly samplePaths: ReadonlyArray<string>;\n};\nexport const ServerNotification__WindowsWorldWritableWarningNotification = Schema.Struct({\n  extraCount: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  failedScan: Schema.Boolean,\n  samplePaths: Schema.Array(Schema.String),\n});\n\nexport type ServerRequest__AbsolutePathBuf = string;\nexport const ServerRequest__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type ServerRequest__AdditionalNetworkPermissions = { readonly enabled?: boolean | null };\nexport const ServerRequest__AdditionalNetworkPermissions = Schema.Struct({\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type ServerRequest__AttestationGenerateParams = {};\nexport const ServerRequest__AttestationGenerateParams = Schema.Struct({});\n\nexport type ServerRequest__ChatgptAuthTokensRefreshReason = \"unauthorized\";\nexport const ServerRequest__ChatgptAuthTokensRefreshReason = Schema.Literal(\"unauthorized\");\n\nexport type ServerRequest__DynamicToolCallParams = {\n  readonly arguments: unknown;\n  readonly callId: string;\n  readonly namespace?: string | null;\n  readonly threadId: string;\n  readonly tool: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__DynamicToolCallParams = Schema.Struct({\n  arguments: Schema.Unknown,\n  callId: Schema.String,\n  namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  tool: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__FileChange =\n  | { readonly content: string; readonly type: \"add\" }\n  | { readonly content: string; readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\"; readonly unified_diff: string };\nexport const ServerRequest__FileChange = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.String,\n      type: Schema.Literal(\"add\").annotate({ title: \"AddFileChangeType\" }),\n    }).annotate({ title: \"AddFileChange\" }),\n    Schema.Struct({\n      content: Schema.String,\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeleteFileChangeType\" }),\n    }).annotate({ title: \"DeleteFileChange\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdateFileChangeType\" }),\n      unified_diff: Schema.String,\n    }).annotate({ title: \"UpdateFileChange\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__FileChangeRequestApprovalParams = {\n  readonly grantRoot?: string | null;\n  readonly itemId: string;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__FileChangeRequestApprovalParams = Schema.Struct({\n  grantRoot: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"[UNSTABLE] When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for extra write access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__FileSystemAccessMode = \"read\" | \"write\" | \"deny\";\nexport const ServerRequest__FileSystemAccessMode = Schema.Literals([\"read\", \"write\", \"deny\"]);\n\nexport type ServerRequest__LegacyAppPathString = string;\nexport const ServerRequest__LegacyAppPathString = Schema.String;\n\nexport type ServerRequest__McpElicitationArrayType = \"array\";\nexport const ServerRequest__McpElicitationArrayType = Schema.Literal(\"array\");\n\nexport type ServerRequest__McpElicitationBooleanType = \"boolean\";\nexport const ServerRequest__McpElicitationBooleanType = Schema.Literal(\"boolean\");\n\nexport type ServerRequest__McpElicitationConstOption = {\n  readonly const: string;\n  readonly title: string;\n};\nexport const ServerRequest__McpElicitationConstOption = Schema.Struct({\n  const: Schema.String,\n  title: Schema.String,\n});\n\nexport type ServerRequest__McpElicitationNumberType = \"number\" | \"integer\";\nexport const ServerRequest__McpElicitationNumberType = Schema.Literals([\"number\", \"integer\"]);\n\nexport type ServerRequest__McpElicitationObjectType = \"object\";\nexport const ServerRequest__McpElicitationObjectType = Schema.Literal(\"object\");\n\nexport type ServerRequest__McpElicitationStringFormat = \"email\" | \"uri\" | \"date\" | \"date-time\";\nexport const ServerRequest__McpElicitationStringFormat = Schema.Literals([\n  \"email\",\n  \"uri\",\n  \"date\",\n  \"date-time\",\n]);\n\nexport type ServerRequest__McpElicitationStringType = \"string\";\nexport const ServerRequest__McpElicitationStringType = Schema.Literal(\"string\");\n\nexport type ServerRequest__NetworkApprovalProtocol = \"http\" | \"https\" | \"socks5Tcp\" | \"socks5Udp\";\nexport const ServerRequest__NetworkApprovalProtocol = Schema.Literals([\n  \"http\",\n  \"https\",\n  \"socks5Tcp\",\n  \"socks5Udp\",\n]);\n\nexport type ServerRequest__NetworkPolicyRuleAction = \"allow\" | \"deny\";\nexport const ServerRequest__NetworkPolicyRuleAction = Schema.Literals([\"allow\", \"deny\"]);\n\nexport type ServerRequest__ParsedCommand =\n  | { readonly cmd: string; readonly name: string; readonly path: string; readonly type: \"read\" }\n  | { readonly cmd: string; readonly path?: string | null; readonly type: \"list_files\" }\n  | {\n      readonly cmd: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly cmd: string; readonly type: \"unknown\" };\nexport const ServerRequest__ParsedCommand = Schema.Union(\n  [\n    Schema.Struct({\n      cmd: Schema.String,\n      name: Schema.String,\n      path: Schema.String.annotate({\n        description:\n          \"(Best effort) Path to the file being read by the command. When possible, this is an absolute path, though when relative, it should be resolved against the `cwd`` that will be used to run the command to derive the absolute path.\",\n      }),\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadParsedCommandType\" }),\n    }).annotate({ title: \"ReadParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"list_files\").annotate({ title: \"ListFilesParsedCommandType\" }),\n    }).annotate({ title: \"ListFilesParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchParsedCommandType\" }),\n    }).annotate({ title: \"SearchParsedCommand\" }),\n    Schema.Struct({\n      cmd: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownParsedCommandType\" }),\n    }).annotate({ title: \"UnknownParsedCommand\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__RequestId = string | number;\nexport const ServerRequest__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type ServerRequest__ThreadId = string;\nexport const ServerRequest__ThreadId = Schema.String;\n\nexport type ServerRequest__ToolRequestUserInputOption = {\n  readonly description: string;\n  readonly label: string;\n};\nexport const ServerRequest__ToolRequestUserInputOption = Schema.Struct({\n  description: Schema.String,\n  label: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL. Defines a single selectable option for request_user_input.\",\n});\n\nexport type ToolRequestUserInputParams__ToolRequestUserInputOption = {\n  readonly description: string;\n  readonly label: string;\n};\nexport const ToolRequestUserInputParams__ToolRequestUserInputOption = Schema.Struct({\n  description: Schema.String,\n  label: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL. Defines a single selectable option for request_user_input.\",\n});\n\nexport type ToolRequestUserInputResponse__ToolRequestUserInputAnswer = {\n  readonly answers: ReadonlyArray<string>;\n};\nexport const ToolRequestUserInputResponse__ToolRequestUserInputAnswer = Schema.Struct({\n  answers: Schema.Array(Schema.String),\n}).annotate({\n  description: \"EXPERIMENTAL. Captures a user's answer to a request_user_input question.\",\n});\n\nexport type V1InitializeParams__ClientInfo = {\n  readonly name: string;\n  readonly title?: string | null;\n  readonly version: string;\n};\nexport const V1InitializeParams__ClientInfo = Schema.Struct({\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  version: Schema.String,\n});\n\nexport type V1InitializeParams__InitializeCapabilities = {\n  readonly experimentalApi?: boolean;\n  readonly mcpServerOpenaiFormElicitation?: boolean;\n  readonly optOutNotificationMethods?: ReadonlyArray<string> | null;\n  readonly requestAttestation?: boolean;\n};\nexport const V1InitializeParams__InitializeCapabilities = Schema.Struct({\n  experimentalApi: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Opt into receiving experimental API methods and fields.\",\n      default: false,\n    }),\n  ),\n  mcpServerOpenaiFormElicitation: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Allow downstream MCP servers to request OpenAI extended form elicitations.\",\n    }),\n  ),\n  optOutNotificationMethods: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Exact notification method names that should be suppressed for this connection (for example `thread/started`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  requestAttestation: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Opt into `attestation/generate` requests for upstream `x-oai-attestation`.\",\n      default: false,\n    }),\n  ),\n}).annotate({ description: \"Client-declared capabilities negotiated during initialize.\" });\n\nexport type V2AccountRateLimitsUpdatedNotification__CreditsSnapshot = {\n  readonly balance?: string | null;\n  readonly hasCredits: boolean;\n  readonly unlimited: boolean;\n};\nexport const V2AccountRateLimitsUpdatedNotification__CreditsSnapshot = Schema.Struct({\n  balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  hasCredits: Schema.Boolean,\n  unlimited: Schema.Boolean,\n});\n\nexport type V2AccountRateLimitsUpdatedNotification__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const V2AccountRateLimitsUpdatedNotification__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type V2AccountRateLimitsUpdatedNotification__RateLimitReachedType =\n  | \"rate_limit_reached\"\n  | \"workspace_owner_credits_depleted\"\n  | \"workspace_member_credits_depleted\"\n  | \"workspace_owner_usage_limit_reached\"\n  | \"workspace_member_usage_limit_reached\";\nexport const V2AccountRateLimitsUpdatedNotification__RateLimitReachedType = Schema.Literals([\n  \"rate_limit_reached\",\n  \"workspace_owner_credits_depleted\",\n  \"workspace_member_credits_depleted\",\n  \"workspace_owner_usage_limit_reached\",\n  \"workspace_member_usage_limit_reached\",\n]);\n\nexport type V2AccountRateLimitsUpdatedNotification__RateLimitWindow = {\n  readonly resetsAt?: number | null;\n  readonly usedPercent: number;\n  readonly windowDurationMins?: number | null;\n};\nexport const V2AccountRateLimitsUpdatedNotification__RateLimitWindow = Schema.Struct({\n  resetsAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  usedPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  windowDurationMins: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type V2AccountRateLimitsUpdatedNotification__SpendControlLimitSnapshot = {\n  readonly limit: string;\n  readonly remainingPercent: number;\n  readonly resetsAt: number;\n  readonly used: string;\n};\nexport const V2AccountRateLimitsUpdatedNotification__SpendControlLimitSnapshot = Schema.Struct({\n  limit: Schema.String,\n  remainingPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  resetsAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  used: Schema.String,\n});\n\nexport type V2AccountUpdatedNotification__AuthMode =\n  | \"apikey\"\n  | \"chatgpt\"\n  | \"chatgptAuthTokens\"\n  | \"headers\"\n  | \"agentIdentity\"\n  | \"personalAccessToken\"\n  | \"bedrockApiKey\";\nexport const V2AccountUpdatedNotification__AuthMode = Schema.Literals([\n  \"apikey\",\n  \"chatgpt\",\n  \"chatgptAuthTokens\",\n  \"headers\",\n  \"agentIdentity\",\n  \"personalAccessToken\",\n  \"bedrockApiKey\",\n]).annotate({ description: \"Authentication mode for OpenAI-backed providers.\" });\n\nexport type V2AccountUpdatedNotification__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const V2AccountUpdatedNotification__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type V2AppListUpdatedNotification__AppBranding = {\n  readonly category?: string | null;\n  readonly developer?: string | null;\n  readonly isDiscoverableApp: boolean;\n  readonly privacyPolicy?: string | null;\n  readonly termsOfService?: string | null;\n  readonly website?: string | null;\n};\nexport const V2AppListUpdatedNotification__AppBranding = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isDiscoverableApp: Schema.Boolean,\n  privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type V2AppListUpdatedNotification__AppReview = { readonly status: string };\nexport const V2AppListUpdatedNotification__AppReview = Schema.Struct({ status: Schema.String });\n\nexport type V2AppListUpdatedNotification__AppScreenshot = {\n  readonly fileId?: string | null;\n  readonly url?: string | null;\n  readonly userPrompt: string;\n};\nexport const V2AppListUpdatedNotification__AppScreenshot = Schema.Struct({\n  fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  userPrompt: Schema.String,\n});\n\nexport type V2AppsInstalledResponse__InstalledApp = {\n  readonly callable: boolean;\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly runtimeName?: string | null;\n};\nexport const V2AppsInstalledResponse__InstalledApp = Schema.Struct({\n  callable: Schema.Boolean.annotate({\n    description:\n      \"Whether the connector is enabled and has a non-synthetic, model-visible tool allowed by effective MCP and app/tool policy in the committed runtime snapshot.\",\n  }),\n  enabled: Schema.Boolean.annotate({\n    description:\n      \"Effective enabled state after applying global, workspace, local, and managed configuration at read time.\",\n  }),\n  id: Schema.String,\n  runtimeName: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Best-effort name carried by the runtime tool catalog. Canonical app metadata remains owned by `app/read`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Installed connector runtime state.\" });\n\nexport type V2AppsListResponse__AppBranding = {\n  readonly category?: string | null;\n  readonly developer?: string | null;\n  readonly isDiscoverableApp: boolean;\n  readonly privacyPolicy?: string | null;\n  readonly termsOfService?: string | null;\n  readonly website?: string | null;\n};\nexport const V2AppsListResponse__AppBranding = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isDiscoverableApp: Schema.Boolean,\n  privacyPolicy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfService: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  website: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type V2AppsListResponse__AppReview = { readonly status: string };\nexport const V2AppsListResponse__AppReview = Schema.Struct({ status: Schema.String });\n\nexport type V2AppsListResponse__AppScreenshot = {\n  readonly fileId?: string | null;\n  readonly url?: string | null;\n  readonly userPrompt: string;\n};\nexport const V2AppsListResponse__AppScreenshot = Schema.Struct({\n  fileId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  userPrompt: Schema.String,\n});\n\nexport type V2AppsReadResponse__AppToolSummary = {\n  readonly description: string;\n  readonly name: string;\n  readonly title?: string | null;\n};\nexport const V2AppsReadResponse__AppToolSummary = Schema.Struct({\n  description: Schema.String,\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"EXPERIMENTAL - metadata returned by app/read.\" });\n\nexport type V2CancelLoginAccountResponse__CancelLoginAccountStatus = \"canceled\" | \"notFound\";\nexport const V2CancelLoginAccountResponse__CancelLoginAccountStatus = Schema.Literals([\n  \"canceled\",\n  \"notFound\",\n]);\n\nexport type V2CommandExecParams__AbsolutePathBuf = string;\nexport const V2CommandExecParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2CommandExecParams__CommandExecTerminalSize = {\n  readonly cols: number;\n  readonly rows: number;\n};\nexport const V2CommandExecParams__CommandExecTerminalSize = Schema.Struct({\n  cols: Schema.Number.annotate({\n    description: \"Terminal width in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  rows: Schema.Number.annotate({\n    description: \"Terminal height in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" });\n\nexport type V2ConfigBatchWriteParams__MergeStrategy = \"replace\" | \"upsert\";\nexport const V2ConfigBatchWriteParams__MergeStrategy = Schema.Literals([\"replace\", \"upsert\"]);\n\nexport type V2ConfigReadResponse__AbsolutePathBuf = string;\nexport const V2ConfigReadResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ConfigReadResponse__AnalyticsConfig = {\n  readonly enabled?: boolean | null;\n  readonly [x: string]: unknown;\n};\nexport const V2ConfigReadResponse__AnalyticsConfig = Schema.StructWithRest(\n  Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) }),\n  [Schema.Record(Schema.String, Schema.Unknown)],\n);\n\nexport type V2ConfigReadResponse__AppToolApproval = \"auto\" | \"prompt\" | \"writes\" | \"approve\";\nexport const V2ConfigReadResponse__AppToolApproval = Schema.Literals([\n  \"auto\",\n  \"prompt\",\n  \"writes\",\n  \"approve\",\n]);\n\nexport type V2ConfigReadResponse__AppToolsConfig = {};\nexport const V2ConfigReadResponse__AppToolsConfig = Schema.Struct({});\n\nexport type V2ConfigReadResponse__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ConfigReadResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ConfigReadResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ConfigReadResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigReadResponse__AutoCompactTokenLimitScope = \"total\" | \"body_after_prefix\";\nexport const V2ConfigReadResponse__AutoCompactTokenLimitScope = Schema.Literals([\n  \"total\",\n  \"body_after_prefix\",\n]).annotate({\n  description:\n    \"Selects which part of the active context is charged against `model_auto_compact_token_limit`.\",\n});\n\nexport type V2ConfigReadResponse__ForcedChatgptWorkspaceIds = string | ReadonlyArray<string>;\nexport const V2ConfigReadResponse__ForcedChatgptWorkspaceIds = Schema.Union([\n  Schema.String,\n  Schema.Array(Schema.String),\n]).annotate({\n  description: \"Backward-compatible API shape for ChatGPT workspace login restrictions.\",\n});\n\nexport type V2ConfigReadResponse__ForcedLoginMethod = \"chatgpt\" | \"api\";\nexport const V2ConfigReadResponse__ForcedLoginMethod = Schema.Literals([\"chatgpt\", \"api\"]);\n\nexport type V2ConfigReadResponse__ReasoningEffort = string;\nexport const V2ConfigReadResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ConfigReadResponse__ReasoningSummary = \"auto\" | \"concise\" | \"detailed\" | \"none\";\nexport const V2ConfigReadResponse__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type V2ConfigReadResponse__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ConfigReadResponse__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ConfigReadResponse__SandboxWorkspaceWrite = {\n  readonly exclude_slash_tmp?: boolean;\n  readonly exclude_tmpdir_env_var?: boolean;\n  readonly network_access?: boolean;\n  readonly writable_roots?: ReadonlyArray<string>;\n};\nexport const V2ConfigReadResponse__SandboxWorkspaceWrite = Schema.Struct({\n  exclude_slash_tmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  exclude_tmpdir_env_var: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  network_access: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  writable_roots: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n});\n\nexport type V2ConfigReadResponse__Verbosity = \"low\" | \"medium\" | \"high\";\nexport const V2ConfigReadResponse__Verbosity = Schema.Literals([\"low\", \"medium\", \"high\"]).annotate({\n  description:\n    \"Controls output length/detail on GPT-5 models via the Responses API. Serialized with lowercase values to match the OpenAI API.\",\n});\n\nexport type V2ConfigReadResponse__WebSearchContextSize = \"low\" | \"medium\" | \"high\";\nexport const V2ConfigReadResponse__WebSearchContextSize = Schema.Literals([\n  \"low\",\n  \"medium\",\n  \"high\",\n]);\n\nexport type V2ConfigReadResponse__WebSearchLocation = {\n  readonly city?: string | null;\n  readonly country?: string | null;\n  readonly region?: string | null;\n  readonly timezone?: string | null;\n};\nexport const V2ConfigReadResponse__WebSearchLocation = Schema.Struct({\n  city: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  country: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  region: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  timezone: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ConfigReadResponse__WebSearchMode = \"disabled\" | \"cached\" | \"indexed\" | \"live\";\nexport const V2ConfigReadResponse__WebSearchMode = Schema.Literals([\n  \"disabled\",\n  \"cached\",\n  \"indexed\",\n  \"live\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ConfigRequirementsReadResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigRequirementsReadResponse__ComputerUseRequirements = {\n  readonly allowLockedComputerUse?: boolean | null;\n};\nexport const V2ConfigRequirementsReadResponse__ComputerUseRequirements = Schema.Struct({\n  allowLockedComputerUse: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type V2ConfigRequirementsReadResponse__ConfiguredHookHandler =\n  | {\n      readonly async: boolean;\n      readonly command: string;\n      readonly commandWindows?: string | null;\n      readonly statusMessage?: string | null;\n      readonly timeoutSec?: number | null;\n      readonly type: \"command\";\n    }\n  | { readonly type: \"prompt\" }\n  | { readonly type: \"agent\" };\nexport const V2ConfigRequirementsReadResponse__ConfiguredHookHandler = Schema.Union(\n  [\n    Schema.Struct({\n      async: Schema.Boolean,\n      command: Schema.String,\n      commandWindows: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      timeoutSec: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"uint64\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"command\").annotate({ title: \"CommandConfiguredHookHandlerType\" }),\n    }).annotate({ title: \"CommandConfiguredHookHandler\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"prompt\").annotate({ title: \"PromptConfiguredHookHandlerType\" }),\n    }).annotate({ title: \"PromptConfiguredHookHandler\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"agent\").annotate({ title: \"AgentConfiguredHookHandlerType\" }),\n    }).annotate({ title: \"AgentConfiguredHookHandler\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigRequirementsReadResponse__NetworkDomainPermission = \"allow\" | \"deny\";\nexport const V2ConfigRequirementsReadResponse__NetworkDomainPermission = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = \"allow\" | \"deny\";\nexport const V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission = Schema.Literals([\n  \"allow\",\n  \"deny\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__ReasoningEffort = string;\nexport const V2ConfigRequirementsReadResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ConfigRequirementsReadResponse__ResidencyRequirement = \"us\";\nexport const V2ConfigRequirementsReadResponse__ResidencyRequirement = Schema.Literal(\"us\");\n\nexport type V2ConfigRequirementsReadResponse__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ConfigRequirementsReadResponse__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__WebSearchMode =\n  | \"disabled\"\n  | \"cached\"\n  | \"indexed\"\n  | \"live\";\nexport const V2ConfigRequirementsReadResponse__WebSearchMode = Schema.Literals([\n  \"disabled\",\n  \"cached\",\n  \"indexed\",\n  \"live\",\n]);\n\nexport type V2ConfigRequirementsReadResponse__WindowsSandboxSetupMode = \"elevated\" | \"unelevated\";\nexport const V2ConfigRequirementsReadResponse__WindowsSandboxSetupMode = Schema.Literals([\n  \"elevated\",\n  \"unelevated\",\n]);\n\nexport type V2ConfigValueWriteParams__MergeStrategy = \"replace\" | \"upsert\";\nexport const V2ConfigValueWriteParams__MergeStrategy = Schema.Literals([\"replace\", \"upsert\"]);\n\nexport type V2ConfigWarningNotification__TextPosition = {\n  readonly column: number;\n  readonly line: number;\n};\nexport const V2ConfigWarningNotification__TextPosition = Schema.Struct({\n  column: Schema.Number.annotate({\n    description: \"1-based column number (in Unicode scalar values).\",\n    format: \"uint\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  line: Schema.Number.annotate({ description: \"1-based line number.\", format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ConfigWriteResponse__AbsolutePathBuf = string;\nexport const V2ConfigWriteResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ConfigWriteResponse__WriteStatus = \"ok\" | \"okOverridden\";\nexport const V2ConfigWriteResponse__WriteStatus = Schema.Literals([\"ok\", \"okOverridden\"]);\n\nexport type V2ConsumeAccountRateLimitResetCreditResponse__ConsumeAccountRateLimitResetCreditOutcome =\n  \"reset\" | \"nothingToReset\" | \"noCredit\" | \"alreadyRedeemed\";\nexport const V2ConsumeAccountRateLimitResetCreditResponse__ConsumeAccountRateLimitResetCreditOutcome =\n  Schema.Literals([\"reset\", \"nothingToReset\", \"noCredit\", \"alreadyRedeemed\"]);\n\nexport type V2ErrorNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ErrorNotification__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ExperimentalFeatureListResponse__ExperimentalFeature = {\n  readonly announcement?: string | null;\n  readonly defaultEnabled: boolean;\n  readonly description?: string | null;\n  readonly displayName?: string | null;\n  readonly enabled: boolean;\n  readonly name: string;\n  readonly stage: \"beta\" | \"underDevelopment\" | \"stable\" | \"deprecated\" | \"removed\";\n};\nexport const V2ExperimentalFeatureListResponse__ExperimentalFeature = Schema.Struct({\n  announcement: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Announcement copy shown to users when the feature is introduced. Null when this feature is not in beta.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  defaultEnabled: Schema.Boolean.annotate({\n    description: \"Whether this feature is enabled by default.\",\n  }),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Short summary describing what the feature does. Null when this feature is not in beta.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  displayName: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"User-facing display name shown in the experimental features UI. Null when this feature is not in beta.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  enabled: Schema.Boolean.annotate({\n    description: \"Whether this feature is currently enabled in the loaded config.\",\n  }),\n  name: Schema.String.annotate({\n    description: \"Stable key used in config.toml and CLI flag toggles.\",\n  }),\n  stage: Schema.Literals([\"beta\", \"underDevelopment\", \"stable\", \"deprecated\", \"removed\"]).annotate({\n    description: \"Lifecycle stage of this feature flag.\",\n  }),\n});\n\nexport type V2ExternalAgentConfigDetectResponse__CommandMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__CommandMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2ExternalAgentConfigDetectResponse__HookMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__HookMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__McpServerMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__McpServerMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__PluginsMigration = {\n  readonly marketplaceName: string;\n  readonly pluginNames: ReadonlyArray<string>;\n};\nexport const V2ExternalAgentConfigDetectResponse__PluginsMigration = Schema.Struct({\n  marketplaceName: Schema.String,\n  pluginNames: Schema.Array(Schema.String),\n});\n\nexport type V2ExternalAgentConfigDetectResponse__SessionMigration = {\n  readonly cwd: string;\n  readonly path: string;\n  readonly title?: string | null;\n};\nexport const V2ExternalAgentConfigDetectResponse__SessionMigration = Schema.Struct({\n  cwd: Schema.String,\n  path: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ExternalAgentConfigDetectResponse__SkillMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__SkillMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__SubagentMigration = { readonly name: string };\nexport const V2ExternalAgentConfigDetectResponse__SubagentMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType =\n    | \"AGENTS_MD\"\n    | \"CONFIG\"\n    | \"SKILLS\"\n    | \"PLUGINS\"\n    | \"MCP_SERVER_CONFIG\"\n    | \"SUBAGENTS\"\n    | \"HOOKS\"\n    | \"COMMANDS\"\n    | \"MEMORY\"\n    | \"SESSIONS\";\nexport const V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType =\n    | \"AGENTS_MD\"\n    | \"CONFIG\"\n    | \"SKILLS\"\n    | \"PLUGINS\"\n    | \"MCP_SERVER_CONFIG\"\n    | \"SUBAGENTS\"\n    | \"HOOKS\"\n    | \"COMMANDS\"\n    | \"MEMORY\"\n    | \"SESSIONS\";\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorSource =\n  \"remoteMcpServersConfig\";\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorSource =\n  Schema.Literal(\"remoteMcpServersConfig\");\n\nexport type V2ExternalAgentConfigImportParams__CommandMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__CommandMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2ExternalAgentConfigImportParams__HookMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__HookMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportParams__McpServerMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__McpServerMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportParams__PluginsMigration = {\n  readonly marketplaceName: string;\n  readonly pluginNames: ReadonlyArray<string>;\n};\nexport const V2ExternalAgentConfigImportParams__PluginsMigration = Schema.Struct({\n  marketplaceName: Schema.String,\n  pluginNames: Schema.Array(Schema.String),\n});\n\nexport type V2ExternalAgentConfigImportParams__SessionMigration = {\n  readonly cwd: string;\n  readonly path: string;\n  readonly title?: string | null;\n};\nexport const V2ExternalAgentConfigImportParams__SessionMigration = Schema.Struct({\n  cwd: Schema.String,\n  path: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ExternalAgentConfigImportParams__SkillMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__SkillMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportParams__SubagentMigration = { readonly name: string };\nexport const V2ExternalAgentConfigImportParams__SubagentMigration = Schema.Struct({\n  name: Schema.String,\n});\n\nexport type V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType =\n  | \"AGENTS_MD\"\n  | \"CONFIG\"\n  | \"SKILLS\"\n  | \"PLUGINS\"\n  | \"MCP_SERVER_CONFIG\"\n  | \"SUBAGENTS\"\n  | \"HOOKS\"\n  | \"COMMANDS\"\n  | \"MEMORY\"\n  | \"SESSIONS\";\nexport const V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType =\n  Schema.Literals([\n    \"AGENTS_MD\",\n    \"CONFIG\",\n    \"SKILLS\",\n    \"PLUGINS\",\n    \"MCP_SERVER_CONFIG\",\n    \"SUBAGENTS\",\n    \"HOOKS\",\n    \"COMMANDS\",\n    \"MEMORY\",\n    \"SESSIONS\",\n  ]);\n\nexport type V2FileChangePatchUpdatedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2FileChangePatchUpdatedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2FsChangedNotification__AbsolutePathBuf = string;\nexport const V2FsChangedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsReadDirectoryResponse__FsReadDirectoryEntry = {\n  readonly fileName: string;\n  readonly isDirectory: boolean;\n  readonly isFile: boolean;\n};\nexport const V2FsReadDirectoryResponse__FsReadDirectoryEntry = Schema.Struct({\n  fileName: Schema.String.annotate({\n    description: \"Direct child entry name only, not an absolute or relative path.\",\n  }),\n  isDirectory: Schema.Boolean.annotate({\n    description: \"Whether this entry resolves to a directory.\",\n  }),\n  isFile: Schema.Boolean.annotate({\n    description: \"Whether this entry resolves to a regular file.\",\n  }),\n}).annotate({ description: \"A directory entry returned by `fs/readDirectory`.\" });\n\nexport type V2GetAccountRateLimitsResponse__CreditsSnapshot = {\n  readonly balance?: string | null;\n  readonly hasCredits: boolean;\n  readonly unlimited: boolean;\n};\nexport const V2GetAccountRateLimitsResponse__CreditsSnapshot = Schema.Struct({\n  balance: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  hasCredits: Schema.Boolean,\n  unlimited: Schema.Boolean,\n});\n\nexport type V2GetAccountRateLimitsResponse__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const V2GetAccountRateLimitsResponse__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type V2GetAccountRateLimitsResponse__RateLimitReachedType =\n  | \"rate_limit_reached\"\n  | \"workspace_owner_credits_depleted\"\n  | \"workspace_member_credits_depleted\"\n  | \"workspace_owner_usage_limit_reached\"\n  | \"workspace_member_usage_limit_reached\";\nexport const V2GetAccountRateLimitsResponse__RateLimitReachedType = Schema.Literals([\n  \"rate_limit_reached\",\n  \"workspace_owner_credits_depleted\",\n  \"workspace_member_credits_depleted\",\n  \"workspace_owner_usage_limit_reached\",\n  \"workspace_member_usage_limit_reached\",\n]);\n\nexport type V2GetAccountRateLimitsResponse__RateLimitResetCreditStatus =\n  | \"available\"\n  | \"redeeming\"\n  | \"redeemed\"\n  | \"unknown\";\nexport const V2GetAccountRateLimitsResponse__RateLimitResetCreditStatus = Schema.Literals([\n  \"available\",\n  \"redeeming\",\n  \"redeemed\",\n  \"unknown\",\n]);\n\nexport type V2GetAccountRateLimitsResponse__RateLimitResetType = \"codexRateLimits\" | \"unknown\";\nexport const V2GetAccountRateLimitsResponse__RateLimitResetType = Schema.Literals([\n  \"codexRateLimits\",\n  \"unknown\",\n]);\n\nexport type V2GetAccountRateLimitsResponse__RateLimitWindow = {\n  readonly resetsAt?: number | null;\n  readonly usedPercent: number;\n  readonly windowDurationMins?: number | null;\n};\nexport const V2GetAccountRateLimitsResponse__RateLimitWindow = Schema.Struct({\n  resetsAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  usedPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  windowDurationMins: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot = {\n  readonly limit: string;\n  readonly remainingPercent: number;\n  readonly resetsAt: number;\n  readonly used: string;\n};\nexport const V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot = Schema.Struct({\n  limit: Schema.String,\n  remainingPercent: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n  resetsAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  used: Schema.String,\n});\n\nexport type V2GetAccountResponse__PlanType =\n  | \"free\"\n  | \"go\"\n  | \"plus\"\n  | \"pro\"\n  | \"prolite\"\n  | \"team\"\n  | \"self_serve_business_usage_based\"\n  | \"business\"\n  | \"enterprise_cbp_usage_based\"\n  | \"enterprise\"\n  | \"edu\"\n  | \"unknown\";\nexport const V2GetAccountResponse__PlanType = Schema.Literals([\n  \"free\",\n  \"go\",\n  \"plus\",\n  \"pro\",\n  \"prolite\",\n  \"team\",\n  \"self_serve_business_usage_based\",\n  \"business\",\n  \"enterprise_cbp_usage_based\",\n  \"enterprise\",\n  \"edu\",\n  \"unknown\",\n]);\n\nexport type V2GetAccountTokenUsageResponse__AccountTokenUsageDailyBucket = {\n  readonly startDate: string;\n  readonly tokens: number;\n};\nexport const V2GetAccountTokenUsageResponse__AccountTokenUsageDailyBucket = Schema.Struct({\n  startDate: Schema.String,\n  tokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2GetAccountTokenUsageResponse__AccountTokenUsageSummary = {\n  readonly currentStreakDays?: number | null;\n  readonly lifetimeTokens?: number | null;\n  readonly longestRunningTurnSec?: number | null;\n  readonly longestStreakDays?: number | null;\n  readonly peakDailyTokens?: number | null;\n};\nexport const V2GetAccountTokenUsageResponse__AccountTokenUsageSummary = Schema.Struct({\n  currentStreakDays: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  lifetimeTokens: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  longestRunningTurnSec: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  longestStreakDays: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  peakDailyTokens: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type V2GetWorkspaceMessagesResponse__WorkspaceMessageType =\n  | \"headline\"\n  | \"announcement\"\n  | \"unknown\";\nexport const V2GetWorkspaceMessagesResponse__WorkspaceMessageType = Schema.Literals([\n  \"headline\",\n  \"announcement\",\n  \"unknown\",\n]);\n\nexport type V2HookCompletedNotification__AbsolutePathBuf = string;\nexport const V2HookCompletedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2HookCompletedNotification__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const V2HookCompletedNotification__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type V2HookCompletedNotification__HookExecutionMode = \"sync\" | \"async\";\nexport const V2HookCompletedNotification__HookExecutionMode = Schema.Literals([\"sync\", \"async\"]);\n\nexport type V2HookCompletedNotification__HookHandlerType = \"command\" | \"prompt\" | \"agent\";\nexport const V2HookCompletedNotification__HookHandlerType = Schema.Literals([\n  \"command\",\n  \"prompt\",\n  \"agent\",\n]);\n\nexport type V2HookCompletedNotification__HookOutputEntryKind =\n  | \"warning\"\n  | \"stop\"\n  | \"feedback\"\n  | \"context\"\n  | \"error\";\nexport const V2HookCompletedNotification__HookOutputEntryKind = Schema.Literals([\n  \"warning\",\n  \"stop\",\n  \"feedback\",\n  \"context\",\n  \"error\",\n]);\n\nexport type V2HookCompletedNotification__HookRunStatus =\n  | \"running\"\n  | \"completed\"\n  | \"failed\"\n  | \"blocked\"\n  | \"stopped\";\nexport const V2HookCompletedNotification__HookRunStatus = Schema.Literals([\n  \"running\",\n  \"completed\",\n  \"failed\",\n  \"blocked\",\n  \"stopped\",\n]);\n\nexport type V2HookCompletedNotification__HookScope = \"thread\" | \"turn\";\nexport const V2HookCompletedNotification__HookScope = Schema.Literals([\"thread\", \"turn\"]);\n\nexport type V2HooksListResponse__AbsolutePathBuf = string;\nexport const V2HooksListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2HooksListResponse__HookErrorInfo = {\n  readonly message: string;\n  readonly path: string;\n};\nexport const V2HooksListResponse__HookErrorInfo = Schema.Struct({\n  message: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2HooksListResponse__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const V2HooksListResponse__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type V2HooksListResponse__HookHandlerType = \"command\" | \"prompt\" | \"agent\";\nexport const V2HooksListResponse__HookHandlerType = Schema.Literals([\"command\", \"prompt\", \"agent\"]);\n\nexport type V2HooksListResponse__HookSource =\n  | \"system\"\n  | \"user\"\n  | \"project\"\n  | \"mdm\"\n  | \"sessionFlags\"\n  | \"plugin\"\n  | \"cloudRequirements\"\n  | \"cloudManagedConfig\"\n  | \"legacyManagedConfigFile\"\n  | \"legacyManagedConfigMdm\"\n  | \"unknown\";\nexport const V2HooksListResponse__HookSource = Schema.Literals([\n  \"system\",\n  \"user\",\n  \"project\",\n  \"mdm\",\n  \"sessionFlags\",\n  \"plugin\",\n  \"cloudRequirements\",\n  \"cloudManagedConfig\",\n  \"legacyManagedConfigFile\",\n  \"legacyManagedConfigMdm\",\n  \"unknown\",\n]);\n\nexport type V2HooksListResponse__HookTrustStatus = \"managed\" | \"untrusted\" | \"trusted\" | \"modified\";\nexport const V2HooksListResponse__HookTrustStatus = Schema.Literals([\n  \"managed\",\n  \"untrusted\",\n  \"trusted\",\n  \"modified\",\n]);\n\nexport type V2HookStartedNotification__AbsolutePathBuf = string;\nexport const V2HookStartedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2HookStartedNotification__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const V2HookStartedNotification__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type V2HookStartedNotification__HookExecutionMode = \"sync\" | \"async\";\nexport const V2HookStartedNotification__HookExecutionMode = Schema.Literals([\"sync\", \"async\"]);\n\nexport type V2HookStartedNotification__HookHandlerType = \"command\" | \"prompt\" | \"agent\";\nexport const V2HookStartedNotification__HookHandlerType = Schema.Literals([\n  \"command\",\n  \"prompt\",\n  \"agent\",\n]);\n\nexport type V2HookStartedNotification__HookOutputEntryKind =\n  | \"warning\"\n  | \"stop\"\n  | \"feedback\"\n  | \"context\"\n  | \"error\";\nexport const V2HookStartedNotification__HookOutputEntryKind = Schema.Literals([\n  \"warning\",\n  \"stop\",\n  \"feedback\",\n  \"context\",\n  \"error\",\n]);\n\nexport type V2HookStartedNotification__HookRunStatus =\n  | \"running\"\n  | \"completed\"\n  | \"failed\"\n  | \"blocked\"\n  | \"stopped\";\nexport const V2HookStartedNotification__HookRunStatus = Schema.Literals([\n  \"running\",\n  \"completed\",\n  \"failed\",\n  \"blocked\",\n  \"stopped\",\n]);\n\nexport type V2HookStartedNotification__HookScope = \"thread\" | \"turn\";\nexport const V2HookStartedNotification__HookScope = Schema.Literals([\"thread\", \"turn\"]);\n\nexport type V2ItemCompletedNotification__AbsolutePathBuf = string;\nexport const V2ItemCompletedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ItemCompletedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ItemCompletedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ItemCompletedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ItemCompletedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ItemCompletedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ItemCompletedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemCompletedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ItemCompletedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemCompletedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ItemCompletedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ItemCompletedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ItemCompletedNotification__LegacyAppPathString = string;\nexport const V2ItemCompletedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ItemCompletedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ItemCompletedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ItemCompletedNotification__McpToolCallError = { readonly message: string };\nexport const V2ItemCompletedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ItemCompletedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ItemCompletedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ItemCompletedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemCompletedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ItemCompletedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ItemCompletedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ItemCompletedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ItemCompletedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ItemCompletedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ItemCompletedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemCompletedNotification__ReasoningEffort = string;\nexport const V2ItemCompletedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ItemCompletedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ItemCompletedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ItemCompletedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ItemCompletedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ItemCompletedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ItemCompletedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf = string;\nexport const V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf =\n  Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions =\n  Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource = \"agent\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource =\n  Schema.Literal(\"agent\").annotate({\n    description: \"[UNSTABLE] Source that produced a terminal approval auto-review decision.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode =\n  | \"read\"\n  | \"write\"\n  | \"deny\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode =\n  Schema.Literals([\"read\", \"write\", \"deny\"]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus =\n  | \"inProgress\"\n  | \"approved\"\n  | \"denied\"\n  | \"timedOut\"\n  | \"aborted\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus =\n  Schema.Literals([\"inProgress\", \"approved\", \"denied\", \"timedOut\", \"aborted\"]).annotate({\n    description: \"[UNSTABLE] Lifecycle state for an approval auto-review.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource =\n  | \"shell\"\n  | \"unifiedExec\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource =\n  Schema.Literals([\"shell\", \"unifiedExec\"]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel =\n  | \"low\"\n  | \"medium\"\n  | \"high\"\n  | \"critical\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel = Schema.Literals(\n  [\"low\", \"medium\", \"high\", \"critical\"],\n).annotate({ description: \"[UNSTABLE] Risk level assigned by approval auto-review.\" });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization =\n  | \"unknown\"\n  | \"low\"\n  | \"medium\"\n  | \"high\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization =\n  Schema.Literals([\"unknown\", \"low\", \"medium\", \"high\"]).annotate({\n    description: \"[UNSTABLE] Authorization level assigned by approval auto-review.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString = string;\nexport const V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol =\n  | \"http\"\n  | \"https\"\n  | \"socks5Tcp\"\n  | \"socks5Udp\";\nexport const V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol =\n  Schema.Literals([\"http\", \"https\", \"socks5Tcp\", \"socks5Udp\"]);\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf = string;\nexport const V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf =\n  Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions = {\n  readonly enabled?: boolean | null;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions =\n  Schema.Struct({ enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])) });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode =\n  | \"read\"\n  | \"write\"\n  | \"deny\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode =\n  Schema.Literals([\"read\", \"write\", \"deny\"]);\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus =\n  | \"inProgress\"\n  | \"approved\"\n  | \"denied\"\n  | \"timedOut\"\n  | \"aborted\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus =\n  Schema.Literals([\"inProgress\", \"approved\", \"denied\", \"timedOut\", \"aborted\"]).annotate({\n    description: \"[UNSTABLE] Lifecycle state for an approval auto-review.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource =\n  | \"shell\"\n  | \"unifiedExec\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource =\n  Schema.Literals([\"shell\", \"unifiedExec\"]);\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel =\n  | \"low\"\n  | \"medium\"\n  | \"high\"\n  | \"critical\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel = Schema.Literals([\n  \"low\",\n  \"medium\",\n  \"high\",\n  \"critical\",\n]).annotate({ description: \"[UNSTABLE] Risk level assigned by approval auto-review.\" });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization =\n  | \"unknown\"\n  | \"low\"\n  | \"medium\"\n  | \"high\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization =\n  Schema.Literals([\"unknown\", \"low\", \"medium\", \"high\"]).annotate({\n    description: \"[UNSTABLE] Authorization level assigned by approval auto-review.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString = string;\nexport const V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol =\n  | \"http\"\n  | \"https\"\n  | \"socks5Tcp\"\n  | \"socks5Udp\";\nexport const V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol =\n  Schema.Literals([\"http\", \"https\", \"socks5Tcp\", \"socks5Udp\"]);\n\nexport type V2ItemStartedNotification__AbsolutePathBuf = string;\nexport const V2ItemStartedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ItemStartedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ItemStartedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ItemStartedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ItemStartedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ItemStartedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ItemStartedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ItemStartedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemStartedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ItemStartedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ItemStartedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ItemStartedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ItemStartedNotification__LegacyAppPathString = string;\nexport const V2ItemStartedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ItemStartedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ItemStartedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ItemStartedNotification__McpToolCallError = { readonly message: string };\nexport const V2ItemStartedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ItemStartedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ItemStartedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ItemStartedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ItemStartedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemStartedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ItemStartedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ItemStartedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ItemStartedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ItemStartedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ItemStartedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ItemStartedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ItemStartedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__ReasoningEffort = string;\nexport const V2ItemStartedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ItemStartedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ItemStartedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ItemStartedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ItemStartedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ItemStartedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ItemStartedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ListMcpServerStatusParams__McpServerStatusDetail = \"full\" | \"toolsAndAuthOnly\";\nexport const V2ListMcpServerStatusParams__McpServerStatusDetail = Schema.Literals([\n  \"full\",\n  \"toolsAndAuthOnly\",\n]);\n\nexport type V2ListMcpServerStatusResponse__McpAuthStatus =\n  | \"unsupported\"\n  | \"notLoggedIn\"\n  | \"bearerToken\"\n  | \"oAuth\";\nexport const V2ListMcpServerStatusResponse__McpAuthStatus = Schema.Literals([\n  \"unsupported\",\n  \"notLoggedIn\",\n  \"bearerToken\",\n  \"oAuth\",\n]);\n\nexport type V2ListMcpServerStatusResponse__McpServerInfo = {\n  readonly description?: string | null;\n  readonly icons?: ReadonlyArray<unknown> | null;\n  readonly name: string;\n  readonly title?: string | null;\n  readonly version: string;\n  readonly websiteUrl?: string | null;\n};\nexport const V2ListMcpServerStatusResponse__McpServerInfo = Schema.Struct({\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])),\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  version: Schema.String,\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"Presentation metadata advertised by an initialized MCP server.\" });\n\nexport type V2ListMcpServerStatusResponse__Resource = {\n  readonly _meta?: unknown;\n  readonly annotations?: unknown;\n  readonly description?: string | null;\n  readonly icons?: ReadonlyArray<unknown> | null;\n  readonly mimeType?: string | null;\n  readonly name: string;\n  readonly size?: number | null;\n  readonly title?: string | null;\n  readonly uri: string;\n};\nexport const V2ListMcpServerStatusResponse__Resource = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  annotations: Schema.optionalKey(Schema.Unknown),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])),\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  size: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n}).annotate({ description: \"A known resource that the server is capable of reading.\" });\n\nexport type V2ListMcpServerStatusResponse__ResourceTemplate = {\n  readonly annotations?: unknown;\n  readonly description?: string | null;\n  readonly mimeType?: string | null;\n  readonly name: string;\n  readonly title?: string | null;\n  readonly uriTemplate: string;\n};\nexport const V2ListMcpServerStatusResponse__ResourceTemplate = Schema.Struct({\n  annotations: Schema.optionalKey(Schema.Unknown),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uriTemplate: Schema.String,\n}).annotate({ description: \"A template description for resources available on the server.\" });\n\nexport type V2ListMcpServerStatusResponse__Tool = {\n  readonly _meta?: unknown;\n  readonly annotations?: unknown;\n  readonly description?: string | null;\n  readonly icons?: ReadonlyArray<unknown> | null;\n  readonly inputSchema: unknown;\n  readonly name: string;\n  readonly outputSchema?: unknown;\n  readonly title?: string | null;\n};\nexport const V2ListMcpServerStatusResponse__Tool = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  annotations: Schema.optionalKey(Schema.Unknown),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  icons: Schema.optionalKey(Schema.Union([Schema.Array(Schema.Unknown), Schema.Null])),\n  inputSchema: Schema.Unknown,\n  name: Schema.String,\n  outputSchema: Schema.optionalKey(Schema.Unknown),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"Definition for a tool the client can call.\" });\n\nexport type V2LoginAccountParams__LoginAppBrand = \"codex\" | \"chatgpt\";\nexport const V2LoginAccountParams__LoginAppBrand = Schema.Literals([\"codex\", \"chatgpt\"]);\n\nexport type V2MarketplaceAddResponse__AbsolutePathBuf = string;\nexport const V2MarketplaceAddResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2MarketplaceRemoveResponse__AbsolutePathBuf = string;\nexport const V2MarketplaceRemoveResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2MarketplaceUpgradeResponse__AbsolutePathBuf = string;\nexport const V2MarketplaceUpgradeResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2MarketplaceUpgradeResponse__MarketplaceUpgradeErrorInfo = {\n  readonly marketplaceName: string;\n  readonly message: string;\n};\nexport const V2MarketplaceUpgradeResponse__MarketplaceUpgradeErrorInfo = Schema.Struct({\n  marketplaceName: Schema.String,\n  message: Schema.String,\n});\n\nexport type V2McpResourceReadResponse__ResourceContent =\n  | {\n      readonly _meta?: unknown;\n      readonly mimeType?: string | null;\n      readonly text: string;\n      readonly uri: string;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly blob: string;\n      readonly mimeType?: string | null;\n      readonly uri: string;\n    };\nexport const V2McpResourceReadResponse__ResourceContent = Schema.Union([\n  Schema.Struct({\n    _meta: Schema.optionalKey(Schema.Unknown),\n    mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    text: Schema.String,\n    uri: Schema.String.annotate({ description: \"The URI of this resource.\" }),\n  }),\n  Schema.Struct({\n    _meta: Schema.optionalKey(Schema.Unknown),\n    blob: Schema.String,\n    mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    uri: Schema.String.annotate({ description: \"The URI of this resource.\" }),\n  }),\n]).annotate({ description: \"Contents returned when reading a resource from an MCP server.\" });\n\nexport type V2McpServerStatusUpdatedNotification__McpServerStartupFailureReason =\n  \"reauthenticationRequired\";\nexport const V2McpServerStatusUpdatedNotification__McpServerStartupFailureReason = Schema.Literal(\n  \"reauthenticationRequired\",\n);\n\nexport type V2McpServerStatusUpdatedNotification__McpServerStartupState =\n  | \"starting\"\n  | \"ready\"\n  | \"failed\"\n  | \"cancelled\";\nexport const V2McpServerStatusUpdatedNotification__McpServerStartupState = Schema.Literals([\n  \"starting\",\n  \"ready\",\n  \"failed\",\n  \"cancelled\",\n]);\n\nexport type V2ModelListResponse__InputModality = \"text\" | \"image\" | \"audio\";\nexport const V2ModelListResponse__InputModality = Schema.Literals([\n  \"text\",\n  \"image\",\n  \"audio\",\n]).annotate({ description: \"Canonical user-input modality tags advertised by a model.\" });\n\nexport type V2ModelListResponse__ModelAvailabilityNux = { readonly message: string };\nexport const V2ModelListResponse__ModelAvailabilityNux = Schema.Struct({ message: Schema.String });\n\nexport type V2ModelListResponse__ModelServiceTier = {\n  readonly description: string;\n  readonly id: string;\n  readonly name: string;\n};\nexport const V2ModelListResponse__ModelServiceTier = Schema.Struct({\n  description: Schema.String,\n  id: Schema.String,\n  name: Schema.String,\n});\n\nexport type V2ModelListResponse__ModelUpgradeInfo = {\n  readonly migrationMarkdown?: string | null;\n  readonly model: string;\n  readonly modelLink?: string | null;\n  readonly upgradeCopy?: string | null;\n};\nexport const V2ModelListResponse__ModelUpgradeInfo = Schema.Struct({\n  migrationMarkdown: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  modelLink: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  upgradeCopy: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ModelListResponse__ReasoningEffort = string;\nexport const V2ModelListResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ModelReroutedNotification__ModelRerouteReason = \"highRiskCyberActivity\";\nexport const V2ModelReroutedNotification__ModelRerouteReason =\n  Schema.Literal(\"highRiskCyberActivity\");\n\nexport type V2ModelVerificationNotification__ModelVerification = \"trustedAccessForCyber\";\nexport const V2ModelVerificationNotification__ModelVerification =\n  Schema.Literal(\"trustedAccessForCyber\");\n\nexport type V2PermissionProfileListResponse__PermissionProfileSummary = {\n  readonly allowed: boolean;\n  readonly description?: string | null;\n  readonly id: string;\n};\nexport const V2PermissionProfileListResponse__PermissionProfileSummary = Schema.Struct({\n  allowed: Schema.Boolean.annotate({\n    description: \"Whether the effective requirements allow selecting this profile.\",\n  }),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional user-facing description for display in clients.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({ description: \"Available permission profile identifier.\" }),\n});\n\nexport type V2PluginInstalledParams__AbsolutePathBuf = string;\nexport const V2PluginInstalledParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginInstalledResponse__AbsolutePathBuf = string;\nexport const V2PluginInstalledResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginInstalledResponse__MarketplaceInterface = {\n  readonly displayName?: string | null;\n};\nexport const V2PluginInstalledResponse__MarketplaceInterface = Schema.Struct({\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginInstalledResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginInstalledResponse__PluginAuthPolicy = Schema.Literals([\n  \"ON_INSTALL\",\n  \"ON_USE\",\n]);\n\nexport type V2PluginInstalledResponse__PluginInstallPolicy =\n  | \"NOT_AVAILABLE\"\n  | \"AVAILABLE\"\n  | \"INSTALLED_BY_DEFAULT\";\nexport const V2PluginInstalledResponse__PluginInstallPolicy = Schema.Literals([\n  \"NOT_AVAILABLE\",\n  \"AVAILABLE\",\n  \"INSTALLED_BY_DEFAULT\",\n]);\n\nexport type V2PluginInstalledResponse__PluginInstallPolicySource =\n  | \"WORKSPACE_SETTING\"\n  | \"IMPLICIT_CANONICAL_APP\";\nexport const V2PluginInstalledResponse__PluginInstallPolicySource = Schema.Literals([\n  \"WORKSPACE_SETTING\",\n  \"IMPLICIT_CANONICAL_APP\",\n]);\n\nexport type V2PluginInstalledResponse__PluginShareDiscoverability =\n  | \"LISTED\"\n  | \"UNLISTED\"\n  | \"PRIVATE\";\nexport const V2PluginInstalledResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginInstalledResponse__PluginSharePrincipalRole = \"reader\" | \"editor\" | \"owner\";\nexport const V2PluginInstalledResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginInstalledResponse__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginInstalledResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginInstallParams__AbsolutePathBuf = string;\nexport const V2PluginInstallParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginInstallResponse__AppSummary = {\n  readonly category?: string | null;\n  readonly description?: string | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly name: string;\n};\nexport const V2PluginInstallResponse__AppSummary = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - app metadata summary for plugin responses.\" });\n\nexport type V2PluginInstallResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginInstallResponse__PluginAuthPolicy = Schema.Literals([\"ON_INSTALL\", \"ON_USE\"]);\n\nexport type V2PluginListParams__AbsolutePathBuf = string;\nexport const V2PluginListParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginListParams__PluginListMarketplaceKind =\n  | \"local\"\n  | \"vertical\"\n  | \"workspace-directory\"\n  | \"shared-with-me\"\n  | \"created-by-me-remote\";\nexport const V2PluginListParams__PluginListMarketplaceKind = Schema.Literals([\n  \"local\",\n  \"vertical\",\n  \"workspace-directory\",\n  \"shared-with-me\",\n  \"created-by-me-remote\",\n]);\n\nexport type V2PluginListResponse__AbsolutePathBuf = string;\nexport const V2PluginListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginListResponse__MarketplaceInterface = { readonly displayName?: string | null };\nexport const V2PluginListResponse__MarketplaceInterface = Schema.Struct({\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginListResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginListResponse__PluginAuthPolicy = Schema.Literals([\"ON_INSTALL\", \"ON_USE\"]);\n\nexport type V2PluginListResponse__PluginInstallPolicy =\n  | \"NOT_AVAILABLE\"\n  | \"AVAILABLE\"\n  | \"INSTALLED_BY_DEFAULT\";\nexport const V2PluginListResponse__PluginInstallPolicy = Schema.Literals([\n  \"NOT_AVAILABLE\",\n  \"AVAILABLE\",\n  \"INSTALLED_BY_DEFAULT\",\n]);\n\nexport type V2PluginListResponse__PluginInstallPolicySource =\n  | \"WORKSPACE_SETTING\"\n  | \"IMPLICIT_CANONICAL_APP\";\nexport const V2PluginListResponse__PluginInstallPolicySource = Schema.Literals([\n  \"WORKSPACE_SETTING\",\n  \"IMPLICIT_CANONICAL_APP\",\n]);\n\nexport type V2PluginListResponse__PluginShareDiscoverability = \"LISTED\" | \"UNLISTED\" | \"PRIVATE\";\nexport const V2PluginListResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginListResponse__PluginSharePrincipalRole = \"reader\" | \"editor\" | \"owner\";\nexport const V2PluginListResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginListResponse__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginListResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginReadParams__AbsolutePathBuf = string;\nexport const V2PluginReadParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginReadResponse__AbsolutePathBuf = string;\nexport const V2PluginReadResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginReadResponse__AppSummary = {\n  readonly category?: string | null;\n  readonly description?: string | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly name: string;\n};\nexport const V2PluginReadResponse__AppSummary = Schema.Struct({\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - app metadata summary for plugin responses.\" });\n\nexport type V2PluginReadResponse__AppTemplateUnavailableReason =\n  | \"NOT_CONFIGURED_FOR_WORKSPACE\"\n  | \"NO_ACTIVE_WORKSPACE\";\nexport const V2PluginReadResponse__AppTemplateUnavailableReason = Schema.Literals([\n  \"NOT_CONFIGURED_FOR_WORKSPACE\",\n  \"NO_ACTIVE_WORKSPACE\",\n]);\n\nexport type V2PluginReadResponse__HookEventName =\n  | \"preToolUse\"\n  | \"permissionRequest\"\n  | \"postToolUse\"\n  | \"preCompact\"\n  | \"postCompact\"\n  | \"sessionStart\"\n  | \"sessionEnd\"\n  | \"userPromptSubmit\"\n  | \"subagentStart\"\n  | \"subagentStop\"\n  | \"stop\";\nexport const V2PluginReadResponse__HookEventName = Schema.Literals([\n  \"preToolUse\",\n  \"permissionRequest\",\n  \"postToolUse\",\n  \"preCompact\",\n  \"postCompact\",\n  \"sessionStart\",\n  \"sessionEnd\",\n  \"userPromptSubmit\",\n  \"subagentStart\",\n  \"subagentStop\",\n  \"stop\",\n]);\n\nexport type V2PluginReadResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginReadResponse__PluginAuthPolicy = Schema.Literals([\"ON_INSTALL\", \"ON_USE\"]);\n\nexport type V2PluginReadResponse__PluginInstallPolicy =\n  | \"NOT_AVAILABLE\"\n  | \"AVAILABLE\"\n  | \"INSTALLED_BY_DEFAULT\";\nexport const V2PluginReadResponse__PluginInstallPolicy = Schema.Literals([\n  \"NOT_AVAILABLE\",\n  \"AVAILABLE\",\n  \"INSTALLED_BY_DEFAULT\",\n]);\n\nexport type V2PluginReadResponse__PluginInstallPolicySource =\n  | \"WORKSPACE_SETTING\"\n  | \"IMPLICIT_CANONICAL_APP\";\nexport const V2PluginReadResponse__PluginInstallPolicySource = Schema.Literals([\n  \"WORKSPACE_SETTING\",\n  \"IMPLICIT_CANONICAL_APP\",\n]);\n\nexport type V2PluginReadResponse__PluginShareDiscoverability = \"LISTED\" | \"UNLISTED\" | \"PRIVATE\";\nexport const V2PluginReadResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginReadResponse__PluginSharePrincipalRole = \"reader\" | \"editor\" | \"owner\";\nexport const V2PluginReadResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginReadResponse__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginReadResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginReadResponse__ScheduledTaskWeekday =\n  | \"MO\"\n  | \"TU\"\n  | \"WE\"\n  | \"TH\"\n  | \"FR\"\n  | \"SA\"\n  | \"SU\";\nexport const V2PluginReadResponse__ScheduledTaskWeekday = Schema.Literals([\n  \"MO\",\n  \"TU\",\n  \"WE\",\n  \"TH\",\n  \"FR\",\n  \"SA\",\n  \"SU\",\n]);\n\nexport type V2PluginShareCheckoutResponse__AbsolutePathBuf = string;\nexport const V2PluginShareCheckoutResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginShareListResponse__AbsolutePathBuf = string;\nexport const V2PluginShareListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginShareListResponse__PluginAuthPolicy = \"ON_INSTALL\" | \"ON_USE\";\nexport const V2PluginShareListResponse__PluginAuthPolicy = Schema.Literals([\n  \"ON_INSTALL\",\n  \"ON_USE\",\n]);\n\nexport type V2PluginShareListResponse__PluginInstallPolicy =\n  | \"NOT_AVAILABLE\"\n  | \"AVAILABLE\"\n  | \"INSTALLED_BY_DEFAULT\";\nexport const V2PluginShareListResponse__PluginInstallPolicy = Schema.Literals([\n  \"NOT_AVAILABLE\",\n  \"AVAILABLE\",\n  \"INSTALLED_BY_DEFAULT\",\n]);\n\nexport type V2PluginShareListResponse__PluginInstallPolicySource =\n  | \"WORKSPACE_SETTING\"\n  | \"IMPLICIT_CANONICAL_APP\";\nexport const V2PluginShareListResponse__PluginInstallPolicySource = Schema.Literals([\n  \"WORKSPACE_SETTING\",\n  \"IMPLICIT_CANONICAL_APP\",\n]);\n\nexport type V2PluginShareListResponse__PluginShareDiscoverability =\n  | \"LISTED\"\n  | \"UNLISTED\"\n  | \"PRIVATE\";\nexport const V2PluginShareListResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginShareListResponse__PluginSharePrincipalRole = \"reader\" | \"editor\" | \"owner\";\nexport const V2PluginShareListResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginShareListResponse__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginShareListResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginShareSaveParams__AbsolutePathBuf = string;\nexport const V2PluginShareSaveParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2PluginShareSaveParams__PluginShareDiscoverability = \"LISTED\" | \"UNLISTED\" | \"PRIVATE\";\nexport const V2PluginShareSaveParams__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginShareSaveParams__PluginSharePrincipalType = \"user\" | \"group\" | \"workspace\";\nexport const V2PluginShareSaveParams__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginShareSaveParams__PluginShareTargetRole = \"reader\" | \"editor\";\nexport const V2PluginShareSaveParams__PluginShareTargetRole = Schema.Literals([\"reader\", \"editor\"]);\n\nexport type V2PluginShareUpdateTargetsParams__PluginSharePrincipalType =\n  | \"user\"\n  | \"group\"\n  | \"workspace\";\nexport const V2PluginShareUpdateTargetsParams__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2PluginShareUpdateTargetsParams__PluginShareTargetRole = \"reader\" | \"editor\";\nexport const V2PluginShareUpdateTargetsParams__PluginShareTargetRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n]);\n\nexport type V2PluginShareUpdateTargetsParams__PluginShareUpdateDiscoverability =\n  | \"UNLISTED\"\n  | \"PRIVATE\"\n  | \"LISTED\";\nexport const V2PluginShareUpdateTargetsParams__PluginShareUpdateDiscoverability = Schema.Literals([\n  \"UNLISTED\",\n  \"PRIVATE\",\n  \"LISTED\",\n]);\n\nexport type V2PluginShareUpdateTargetsResponse__PluginShareDiscoverability =\n  | \"LISTED\"\n  | \"UNLISTED\"\n  | \"PRIVATE\";\nexport const V2PluginShareUpdateTargetsResponse__PluginShareDiscoverability = Schema.Literals([\n  \"LISTED\",\n  \"UNLISTED\",\n  \"PRIVATE\",\n]);\n\nexport type V2PluginShareUpdateTargetsResponse__PluginSharePrincipalRole =\n  | \"reader\"\n  | \"editor\"\n  | \"owner\";\nexport const V2PluginShareUpdateTargetsResponse__PluginSharePrincipalRole = Schema.Literals([\n  \"reader\",\n  \"editor\",\n  \"owner\",\n]);\n\nexport type V2PluginShareUpdateTargetsResponse__PluginSharePrincipalType =\n  | \"user\"\n  | \"group\"\n  | \"workspace\";\nexport const V2PluginShareUpdateTargetsResponse__PluginSharePrincipalType = Schema.Literals([\n  \"user\",\n  \"group\",\n  \"workspace\",\n]);\n\nexport type V2RawResponseCompletedNotification__TokenUsageBreakdown = {\n  readonly cacheWriteInputTokens?: number;\n  readonly cachedInputTokens: number;\n  readonly inputTokens: number;\n  readonly outputTokens: number;\n  readonly reasoningOutputTokens: number;\n  readonly totalTokens: number;\n};\nexport const V2RawResponseCompletedNotification__TokenUsageBreakdown = Schema.Struct({\n  cacheWriteInputTokens: Schema.optionalKey(\n    Schema.Number.annotate({ default: 0, format: \"int64\" }).check(Schema.isInt()),\n  ),\n  cachedInputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  inputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  outputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  reasoningOutputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  totalTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2RawResponseItemCompletedNotification__AgentMessageInputContent =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const V2RawResponseItemCompletedNotification__AgentMessageInputContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"InputTextAgentMessageInputContent\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"EncryptedContentAgentMessageInputContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__ImageDetail =\n  | \"auto\"\n  | \"low\"\n  | \"high\"\n  | \"original\";\nexport const V2RawResponseItemCompletedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough = {\n  readonly turn_id?: string | null;\n};\nexport const V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough =\n  Schema.Struct({\n    turn_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  }).annotate({\n    description:\n      \"Internal Responses API passthrough metadata copied into underlying chat messages.\\n\\nResponses API strongly types this payload. Do not modify it without first getting API approval and making the corresponding Responses API change.\",\n  });\n\nexport type V2RawResponseItemCompletedNotification__LocalShellAction = {\n  readonly command: ReadonlyArray<string>;\n  readonly env?: { readonly [x: string]: string } | null;\n  readonly timeout_ms?: number | null;\n  readonly type: \"exec\";\n  readonly user?: string | null;\n  readonly working_directory?: string | null;\n};\nexport const V2RawResponseItemCompletedNotification__LocalShellAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.Array(Schema.String),\n      env: Schema.optionalKey(\n        Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n      ),\n      timeout_ms: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"uint64\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"exec\").annotate({ title: \"ExecLocalShellActionType\" }),\n      user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"ExecLocalShellAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__LocalShellStatus =\n  | \"completed\"\n  | \"in_progress\"\n  | \"incomplete\";\nexport const V2RawResponseItemCompletedNotification__LocalShellStatus = Schema.Literals([\n  \"completed\",\n  \"in_progress\",\n  \"incomplete\",\n]);\n\nexport type V2RawResponseItemCompletedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2RawResponseItemCompletedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2RawResponseItemCompletedNotification__ReasoningItemContent =\n  | { readonly text: string; readonly type: \"reasoning_text\" }\n  | { readonly text: string; readonly type: \"text\" };\nexport const V2RawResponseItemCompletedNotification__ReasoningItemContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"reasoning_text\").annotate({\n        title: \"ReasoningTextReasoningItemContentType\",\n      }),\n    }).annotate({ title: \"ReasoningTextReasoningItemContent\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"text\").annotate({ title: \"TextReasoningItemContentType\" }),\n    }).annotate({ title: \"TextReasoningItemContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary = {\n  readonly text: string;\n  readonly type: \"summary_text\";\n};\nexport const V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"summary_text\").annotate({\n        title: \"SummaryTextReasoningItemReasoningSummaryType\",\n      }),\n    }).annotate({ title: \"SummaryTextReasoningItemReasoningSummary\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"open_page\"; readonly url?: string | null }\n  | {\n      readonly pattern?: string | null;\n      readonly type: \"find_in_page\";\n      readonly url?: string | null;\n    }\n  | { readonly type: \"other\" };\nexport const V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"SearchResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"open_page\").annotate({\n        title: \"OpenPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"find_in_page\").annotate({\n        title: \"FindInPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"OtherResponsesApiWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RemoteControlStatusChangedNotification__RemoteControlConnectionStatus =\n  | \"disabled\"\n  | \"connecting\"\n  | \"connected\"\n  | \"errored\";\nexport const V2RemoteControlStatusChangedNotification__RemoteControlConnectionStatus =\n  Schema.Literals([\"disabled\", \"connecting\", \"connected\", \"errored\"]);\n\nexport type V2ReviewStartParams__ReviewDelivery = \"inline\" | \"detached\";\nexport const V2ReviewStartParams__ReviewDelivery = Schema.Literals([\"inline\", \"detached\"]);\n\nexport type V2ReviewStartParams__ReviewTarget =\n  | { readonly type: \"uncommittedChanges\" }\n  | { readonly branch: string; readonly type: \"baseBranch\" }\n  | { readonly sha: string; readonly title?: string | null; readonly type: \"commit\" }\n  | { readonly instructions: string; readonly type: \"custom\" };\nexport const V2ReviewStartParams__ReviewTarget = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"uncommittedChanges\").annotate({\n        title: \"UncommittedChangesReviewTargetType\",\n      }),\n    }).annotate({\n      title: \"UncommittedChangesReviewTarget\",\n      description: \"Review the working tree: staged, unstaged, and untracked files.\",\n    }),\n    Schema.Struct({\n      branch: Schema.String,\n      type: Schema.Literal(\"baseBranch\").annotate({ title: \"BaseBranchReviewTargetType\" }),\n    }).annotate({\n      title: \"BaseBranchReviewTarget\",\n      description: \"Review changes between the current branch and the given base branch.\",\n    }),\n    Schema.Struct({\n      sha: Schema.String,\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Optional human-readable label (e.g., commit subject) for UIs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"commit\").annotate({ title: \"CommitReviewTargetType\" }),\n    }).annotate({\n      title: \"CommitReviewTarget\",\n      description: \"Review the changes introduced by a specific commit.\",\n    }),\n    Schema.Struct({\n      instructions: Schema.String,\n      type: Schema.Literal(\"custom\").annotate({ title: \"CustomReviewTargetType\" }),\n    }).annotate({\n      title: \"CustomReviewTarget\",\n      description: \"Arbitrary instructions, equivalent to the old free-form prompt.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__AbsolutePathBuf = string;\nexport const V2ReviewStartResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ReviewStartResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ReviewStartResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ReviewStartResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ReviewStartResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ReviewStartResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ReviewStartResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ReviewStartResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ReviewStartResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ReviewStartResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ReviewStartResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ReviewStartResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ReviewStartResponse__LegacyAppPathString = string;\nexport const V2ReviewStartResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ReviewStartResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ReviewStartResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ReviewStartResponse__McpToolCallError = { readonly message: string };\nexport const V2ReviewStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ReviewStartResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ReviewStartResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ReviewStartResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ReviewStartResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ReviewStartResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ReviewStartResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ReviewStartResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ReviewStartResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ReviewStartResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ReviewStartResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ReviewStartResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ReviewStartResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ReviewStartResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ReviewStartResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__ReasoningEffort = string;\nexport const V2ReviewStartResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ReviewStartResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ReviewStartResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ReviewStartResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ReviewStartResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ReviewStartResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ReviewStartResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ReviewStartResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ReviewStartResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType = \"credits\" | \"usage_limit\";\nexport const V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType = Schema.Literals([\n  \"credits\",\n  \"usage_limit\",\n]);\n\nexport type V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus =\n  | \"sent\"\n  | \"cooldown_active\";\nexport const V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus = Schema.Literals([\n  \"sent\",\n  \"cooldown_active\",\n]);\n\nexport type V2ServerRequestResolvedNotification__RequestId = string | number;\nexport const V2ServerRequestResolvedNotification__RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]);\n\nexport type V2SkillsConfigWriteParams__AbsolutePathBuf = string;\nexport const V2SkillsConfigWriteParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2SkillsExtraRootsSetParams__AbsolutePathBuf = string;\nexport const V2SkillsExtraRootsSetParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2SkillsListResponse__AbsolutePathBuf = string;\nexport const V2SkillsListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2SkillsListResponse__SkillErrorInfo = {\n  readonly message: string;\n  readonly path: string;\n};\nexport const V2SkillsListResponse__SkillErrorInfo = Schema.Struct({\n  message: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2SkillsListResponse__SkillScope = \"user\" | \"repo\" | \"system\" | \"admin\";\nexport const V2SkillsListResponse__SkillScope = Schema.Literals([\n  \"user\",\n  \"repo\",\n  \"system\",\n  \"admin\",\n]);\n\nexport type V2SkillsListResponse__SkillToolDependency = {\n  readonly command?: string | null;\n  readonly description?: string | null;\n  readonly transport?: string | null;\n  readonly type: string;\n  readonly url?: string | null;\n  readonly value: string;\n};\nexport const V2SkillsListResponse__SkillToolDependency = Schema.Struct({\n  command: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  transport: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: Schema.String,\n  url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  value: Schema.String,\n});\n\nexport type V2ThreadForkParams__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadForkParams__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadForkParams__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadForkParams__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkParams__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ThreadForkParams__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ThreadForkParams__ThreadSource = string;\nexport const V2ThreadForkParams__ThreadSource = Schema.String;\n\nexport type V2ThreadForkResponse__AbsolutePathBuf = string;\nexport const V2ThreadForkResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadForkResponse__AgentPath = string;\nexport const V2ThreadForkResponse__AgentPath = Schema.String;\n\nexport type V2ThreadForkResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadForkResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadForkResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadForkResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadForkResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadForkResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadForkResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadForkResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadForkResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadForkResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadForkResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadForkResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadForkResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadForkResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadForkResponse__LegacyAppPathString = string;\nexport const V2ThreadForkResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadForkResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadForkResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadForkResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadForkResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadForkResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadForkResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadForkResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadForkResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadForkResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadForkResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadForkResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadForkResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadForkResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadForkResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadForkResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadForkResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadForkResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadForkResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__ReasoningEffort = string;\nexport const V2ThreadForkResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadForkResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadForkResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadForkResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadForkResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadForkResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadForkResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadForkResponse__ThreadId = string;\nexport const V2ThreadForkResponse__ThreadId = Schema.String;\n\nexport type V2ThreadForkResponse__ThreadSource = string;\nexport const V2ThreadForkResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadForkResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadForkResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadForkResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadForkResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadGoalGetResponse__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const V2ThreadGoalGetResponse__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type V2ThreadGoalSetParams__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const V2ThreadGoalSetParams__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type V2ThreadGoalSetResponse__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const V2ThreadGoalSetResponse__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type V2ThreadGoalUpdatedNotification__ThreadGoalStatus =\n  | \"active\"\n  | \"paused\"\n  | \"blocked\"\n  | \"usageLimited\"\n  | \"budgetLimited\"\n  | \"complete\";\nexport const V2ThreadGoalUpdatedNotification__ThreadGoalStatus = Schema.Literals([\n  \"active\",\n  \"paused\",\n  \"blocked\",\n  \"usageLimited\",\n  \"budgetLimited\",\n  \"complete\",\n]);\n\nexport type V2ThreadListParams__SortDirection = \"asc\" | \"desc\";\nexport const V2ThreadListParams__SortDirection = Schema.Literals([\"asc\", \"desc\"]);\n\nexport type V2ThreadListParams__ThreadListCwdFilter = string | ReadonlyArray<string>;\nexport const V2ThreadListParams__ThreadListCwdFilter = Schema.Union([\n  Schema.String,\n  Schema.Array(Schema.String),\n]);\n\nexport type V2ThreadListParams__ThreadSortKey = \"created_at\" | \"updated_at\" | \"recency_at\";\nexport const V2ThreadListParams__ThreadSortKey = Schema.Literals([\n  \"created_at\",\n  \"updated_at\",\n  \"recency_at\",\n]);\n\nexport type V2ThreadListParams__ThreadSourceKind =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"subAgent\"\n  | \"subAgentReview\"\n  | \"subAgentCompact\"\n  | \"subAgentThreadSpawn\"\n  | \"subAgentOther\"\n  | \"unknown\";\nexport const V2ThreadListParams__ThreadSourceKind = Schema.Literals([\n  \"cli\",\n  \"vscode\",\n  \"exec\",\n  \"appServer\",\n  \"subAgent\",\n  \"subAgentReview\",\n  \"subAgentCompact\",\n  \"subAgentThreadSpawn\",\n  \"subAgentOther\",\n  \"unknown\",\n]);\n\nexport type V2ThreadListResponse__AbsolutePathBuf = string;\nexport const V2ThreadListResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadListResponse__AgentPath = string;\nexport const V2ThreadListResponse__AgentPath = Schema.String;\n\nexport type V2ThreadListResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadListResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadListResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadListResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadListResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadListResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadListResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadListResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadListResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadListResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadListResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadListResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadListResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadListResponse__LegacyAppPathString = string;\nexport const V2ThreadListResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadListResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadListResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadListResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadListResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadListResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadListResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadListResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadListResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadListResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadListResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadListResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadListResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadListResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadListResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadListResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadListResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadListResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadListResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__ReasoningEffort = string;\nexport const V2ThreadListResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadListResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadListResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadListResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadListResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadListResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadListResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadListResponse__ThreadId = string;\nexport const V2ThreadListResponse__ThreadId = Schema.String;\n\nexport type V2ThreadListResponse__ThreadSource = string;\nexport const V2ThreadListResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadListResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadListResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadListResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadListResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams = Schema.Struct({\n  branch: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored branch unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  originUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored origin URL unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sha: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Omit to leave the stored commit unchanged, set to `null` to clear it, or provide a non-empty string to replace it.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadMetadataUpdateResponse__AbsolutePathBuf = string;\nexport const V2ThreadMetadataUpdateResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadMetadataUpdateResponse__AgentPath = string;\nexport const V2ThreadMetadataUpdateResponse__AgentPath = Schema.String;\n\nexport type V2ThreadMetadataUpdateResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadMetadataUpdateResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadMetadataUpdateResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadMetadataUpdateResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadMetadataUpdateResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadMetadataUpdateResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadMetadataUpdateResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadMetadataUpdateResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__LegacyAppPathString = string;\nexport const V2ThreadMetadataUpdateResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadMetadataUpdateResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadMetadataUpdateResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadMetadataUpdateResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadMetadataUpdateResponse__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadMetadataUpdateResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadMetadataUpdateResponse__McpToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadMetadataUpdateResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadMetadataUpdateResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadMetadataUpdateResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadMetadataUpdateResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadMetadataUpdateResponse__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadMetadataUpdateResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadMetadataUpdateResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__ReasoningEffort = string;\nexport const V2ThreadMetadataUpdateResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadMetadataUpdateResponse__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ThreadMetadataUpdateResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadMetadataUpdateResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadMetadataUpdateResponse__ThreadActiveFlag =\n  | \"waitingOnApproval\"\n  | \"waitingOnUserInput\";\nexport const V2ThreadMetadataUpdateResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__ThreadId = string;\nexport const V2ThreadMetadataUpdateResponse__ThreadId = Schema.String;\n\nexport type V2ThreadMetadataUpdateResponse__ThreadSource = string;\nexport const V2ThreadMetadataUpdateResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadMetadataUpdateResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadMetadataUpdateResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadMetadataUpdateResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__AbsolutePathBuf = string;\nexport const V2ThreadReadResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadReadResponse__AgentPath = string;\nexport const V2ThreadReadResponse__AgentPath = Schema.String;\n\nexport type V2ThreadReadResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadReadResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadReadResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadReadResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadReadResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadReadResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadReadResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadReadResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadReadResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadReadResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadReadResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadReadResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadReadResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadReadResponse__LegacyAppPathString = string;\nexport const V2ThreadReadResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadReadResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadReadResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadReadResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadReadResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadReadResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadReadResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadReadResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadReadResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadReadResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadReadResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadReadResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadReadResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadReadResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadReadResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadReadResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadReadResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadReadResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadReadResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__ReasoningEffort = string;\nexport const V2ThreadReadResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadReadResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadReadResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadReadResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadReadResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadReadResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadReadResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadReadResponse__ThreadId = string;\nexport const V2ThreadReadResponse__ThreadId = Schema.String;\n\nexport type V2ThreadReadResponse__ThreadSource = string;\nexport const V2ThreadReadResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadReadResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadReadResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadReadResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadReadResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk = {\n  readonly data: string;\n  readonly itemId?: string | null;\n  readonly numChannels: number;\n  readonly sampleRate: number;\n  readonly samplesPerChannel?: number | null;\n};\nexport const V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk = Schema.Struct(\n  {\n    data: Schema.String,\n    itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    numChannels: Schema.Number.annotate({ format: \"uint16\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    sampleRate: Schema.Number.annotate({ format: \"uint32\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    samplesPerChannel: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint32\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n  },\n).annotate({ description: \"EXPERIMENTAL - thread realtime audio chunk.\" });\n\nexport type V2ThreadRealtimeStartedNotification__RealtimeConversationVersion = \"v1\" | \"v2\" | \"v3\";\nexport const V2ThreadRealtimeStartedNotification__RealtimeConversationVersion = Schema.Literals([\n  \"v1\",\n  \"v2\",\n  \"v3\",\n]);\n\nexport type V2ThreadResumeParams__AgentMessageInputContent =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const V2ThreadResumeParams__AgentMessageInputContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"InputTextAgentMessageInputContent\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentAgentMessageInputContentType\",\n      }),\n    }).annotate({ title: \"EncryptedContentAgentMessageInputContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadResumeParams__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadResumeParams__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadResumeParams__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadResumeParams__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadResumeParams__InternalChatMessageMetadataPassthrough = {\n  readonly turn_id?: string | null;\n};\nexport const V2ThreadResumeParams__InternalChatMessageMetadataPassthrough = Schema.Struct({\n  turn_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({\n  description:\n    \"Internal Responses API passthrough metadata copied into underlying chat messages.\\n\\nResponses API strongly types this payload. Do not modify it without first getting API approval and making the corresponding Responses API change.\",\n});\n\nexport type V2ThreadResumeParams__LocalShellAction = {\n  readonly command: ReadonlyArray<string>;\n  readonly env?: { readonly [x: string]: string } | null;\n  readonly timeout_ms?: number | null;\n  readonly type: \"exec\";\n  readonly user?: string | null;\n  readonly working_directory?: string | null;\n};\nexport const V2ThreadResumeParams__LocalShellAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.Array(Schema.String),\n      env: Schema.optionalKey(\n        Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n      ),\n      timeout_ms: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"uint64\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"exec\").annotate({ title: \"ExecLocalShellActionType\" }),\n      user: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      working_directory: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"ExecLocalShellAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__LocalShellStatus = \"completed\" | \"in_progress\" | \"incomplete\";\nexport const V2ThreadResumeParams__LocalShellStatus = Schema.Literals([\n  \"completed\",\n  \"in_progress\",\n  \"incomplete\",\n]);\n\nexport type V2ThreadResumeParams__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadResumeParams__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadResumeParams__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const V2ThreadResumeParams__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type V2ThreadResumeParams__ReasoningItemContent =\n  | { readonly text: string; readonly type: \"reasoning_text\" }\n  | { readonly text: string; readonly type: \"text\" };\nexport const V2ThreadResumeParams__ReasoningItemContent = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"reasoning_text\").annotate({\n        title: \"ReasoningTextReasoningItemContentType\",\n      }),\n    }).annotate({ title: \"ReasoningTextReasoningItemContent\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"text\").annotate({ title: \"TextReasoningItemContentType\" }),\n    }).annotate({ title: \"TextReasoningItemContent\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ReasoningItemReasoningSummary = {\n  readonly text: string;\n  readonly type: \"summary_text\";\n};\nexport const V2ThreadResumeParams__ReasoningItemReasoningSummary = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"summary_text\").annotate({\n        title: \"SummaryTextReasoningItemReasoningSummaryType\",\n      }),\n    }).annotate({ title: \"SummaryTextReasoningItemReasoningSummary\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ResponsesApiWebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"open_page\"; readonly url?: string | null }\n  | {\n      readonly pattern?: string | null;\n      readonly type: \"find_in_page\";\n      readonly url?: string | null;\n    }\n  | { readonly type: \"other\" };\nexport const V2ThreadResumeParams__ResponsesApiWebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"SearchResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"open_page\").annotate({\n        title: \"OpenPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"find_in_page\").annotate({\n        title: \"FindInPageResponsesApiWebSearchActionType\",\n      }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageResponsesApiWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponsesApiWebSearchActionType\" }),\n    }).annotate({ title: \"OtherResponsesApiWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ThreadResumeParams__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ThreadResumeParams__SortDirection = \"asc\" | \"desc\";\nexport const V2ThreadResumeParams__SortDirection = Schema.Literals([\"asc\", \"desc\"]);\n\nexport type V2ThreadResumeParams__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadResumeParams__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadResumeResponse__AbsolutePathBuf = string;\nexport const V2ThreadResumeResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadResumeResponse__AgentPath = string;\nexport const V2ThreadResumeResponse__AgentPath = Schema.String;\n\nexport type V2ThreadResumeResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadResumeResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadResumeResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadResumeResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadResumeResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadResumeResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadResumeResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadResumeResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadResumeResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadResumeResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadResumeResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadResumeResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadResumeResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadResumeResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadResumeResponse__LegacyAppPathString = string;\nexport const V2ThreadResumeResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadResumeResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadResumeResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadResumeResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadResumeResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadResumeResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadResumeResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadResumeResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadResumeResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadResumeResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadResumeResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadResumeResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadResumeResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadResumeResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadResumeResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadResumeResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadResumeResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadResumeResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadResumeResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__ReasoningEffort = string;\nexport const V2ThreadResumeResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadResumeResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadResumeResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadResumeResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadResumeResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadResumeResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadResumeResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadResumeResponse__ThreadId = string;\nexport const V2ThreadResumeResponse__ThreadId = Schema.String;\n\nexport type V2ThreadResumeResponse__ThreadSource = string;\nexport const V2ThreadResumeResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadResumeResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadResumeResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadResumeResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadResumeResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__AbsolutePathBuf = string;\nexport const V2ThreadRollbackResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadRollbackResponse__AgentPath = string;\nexport const V2ThreadRollbackResponse__AgentPath = Schema.String;\n\nexport type V2ThreadRollbackResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadRollbackResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadRollbackResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadRollbackResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadRollbackResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadRollbackResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadRollbackResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadRollbackResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadRollbackResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadRollbackResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadRollbackResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadRollbackResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadRollbackResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadRollbackResponse__LegacyAppPathString = string;\nexport const V2ThreadRollbackResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadRollbackResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadRollbackResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadRollbackResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadRollbackResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadRollbackResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadRollbackResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadRollbackResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadRollbackResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadRollbackResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadRollbackResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadRollbackResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadRollbackResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadRollbackResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadRollbackResponse__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2ThreadRollbackResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadRollbackResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadRollbackResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadRollbackResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__ReasoningEffort = string;\nexport const V2ThreadRollbackResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadRollbackResponse__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ThreadRollbackResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadRollbackResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadRollbackResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadRollbackResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadRollbackResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadRollbackResponse__ThreadId = string;\nexport const V2ThreadRollbackResponse__ThreadId = Schema.String;\n\nexport type V2ThreadRollbackResponse__ThreadSource = string;\nexport const V2ThreadRollbackResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadRollbackResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadRollbackResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadRollbackResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadRollbackResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__AbsolutePathBuf = string;\nexport const V2ThreadSettingsUpdatedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadSettingsUpdatedNotification__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const V2ThreadSettingsUpdatedNotification__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type V2ThreadSettingsUpdatedNotification__ApprovalsReviewer =\n  | \"user\"\n  | \"auto_review\"\n  | \"guardian_subagent\";\nexport const V2ThreadSettingsUpdatedNotification__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadSettingsUpdatedNotification__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadSettingsUpdatedNotification__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__ModeKind = \"plan\" | \"default\";\nexport const V2ThreadSettingsUpdatedNotification__ModeKind = Schema.Literals([\n  \"plan\",\n  \"default\",\n]).annotate({ description: \"Initial collaboration mode to use when the TUI starts.\" });\n\nexport type V2ThreadSettingsUpdatedNotification__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const V2ThreadSettingsUpdatedNotification__Personality = Schema.Literals([\n  \"none\",\n  \"friendly\",\n  \"pragmatic\",\n]);\n\nexport type V2ThreadSettingsUpdatedNotification__ReasoningEffort = string;\nexport const V2ThreadSettingsUpdatedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadSettingsUpdatedNotification__ReasoningSummary =\n  | \"auto\"\n  | \"concise\"\n  | \"detailed\"\n  | \"none\";\nexport const V2ThreadSettingsUpdatedNotification__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type V2ThreadStartedNotification__AbsolutePathBuf = string;\nexport const V2ThreadStartedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadStartedNotification__AgentPath = string;\nexport const V2ThreadStartedNotification__AgentPath = Schema.String;\n\nexport type V2ThreadStartedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadStartedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadStartedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadStartedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadStartedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadStartedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadStartedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartedNotification__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadStartedNotification__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadStartedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadStartedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadStartedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadStartedNotification__LegacyAppPathString = string;\nexport const V2ThreadStartedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadStartedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadStartedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadStartedNotification__McpToolCallError = { readonly message: string };\nexport const V2ThreadStartedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadStartedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadStartedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadStartedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadStartedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadStartedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadStartedNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadStartedNotification__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2ThreadStartedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadStartedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadStartedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadStartedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__ReasoningEffort = string;\nexport const V2ThreadStartedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadStartedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ThreadStartedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadStartedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadStartedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadStartedNotification__ThreadActiveFlag =\n  | \"waitingOnApproval\"\n  | \"waitingOnUserInput\";\nexport const V2ThreadStartedNotification__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadStartedNotification__ThreadId = string;\nexport const V2ThreadStartedNotification__ThreadId = Schema.String;\n\nexport type V2ThreadStartedNotification__ThreadSource = string;\nexport const V2ThreadStartedNotification__ThreadSource = Schema.String;\n\nexport type V2ThreadStartedNotification__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadStartedNotification__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadStartedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadStartedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartParams__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadStartParams__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadStartParams__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadStartParams__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartParams__DynamicToolNamespaceTool = {\n  readonly deferLoading?: boolean;\n  readonly description: string;\n  readonly inputSchema: unknown;\n  readonly name: string;\n  readonly type: \"function\";\n};\nexport const V2ThreadStartParams__DynamicToolNamespaceTool = Schema.Union(\n  [\n    Schema.Struct({\n      deferLoading: Schema.optionalKey(Schema.Boolean),\n      description: Schema.String,\n      inputSchema: Schema.Unknown,\n      name: Schema.String,\n      type: Schema.Literal(\"function\").annotate({ title: \"FunctionDynamicToolNamespaceToolType\" }),\n    }).annotate({ title: \"FunctionDynamicToolNamespaceTool\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartParams__LegacyAppPathString = string;\nexport const V2ThreadStartParams__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadStartParams__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const V2ThreadStartParams__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type V2ThreadStartParams__SandboxMode =\n  | \"read-only\"\n  | \"workspace-write\"\n  | \"danger-full-access\";\nexport const V2ThreadStartParams__SandboxMode = Schema.Literals([\n  \"read-only\",\n  \"workspace-write\",\n  \"danger-full-access\",\n]);\n\nexport type V2ThreadStartParams__ThreadSource = string;\nexport const V2ThreadStartParams__ThreadSource = Schema.String;\n\nexport type V2ThreadStartParams__ThreadStartSource = \"startup\" | \"clear\";\nexport const V2ThreadStartParams__ThreadStartSource = Schema.Literals([\"startup\", \"clear\"]);\n\nexport type V2ThreadStartResponse__AbsolutePathBuf = string;\nexport const V2ThreadStartResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadStartResponse__AgentPath = string;\nexport const V2ThreadStartResponse__AgentPath = Schema.String;\n\nexport type V2ThreadStartResponse__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2ThreadStartResponse__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadStartResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadStartResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadStartResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadStartResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadStartResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadStartResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadStartResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadStartResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadStartResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadStartResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadStartResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadStartResponse__LegacyAppPathString = string;\nexport const V2ThreadStartResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadStartResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadStartResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadStartResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2ThreadStartResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadStartResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadStartResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadStartResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadStartResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadStartResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadStartResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadStartResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadStartResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2ThreadStartResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadStartResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadStartResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadStartResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__ReasoningEffort = string;\nexport const V2ThreadStartResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadStartResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2ThreadStartResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadStartResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadStartResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadStartResponse__ThreadActiveFlag = \"waitingOnApproval\" | \"waitingOnUserInput\";\nexport const V2ThreadStartResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadStartResponse__ThreadId = string;\nexport const V2ThreadStartResponse__ThreadId = Schema.String;\n\nexport type V2ThreadStartResponse__ThreadSource = string;\nexport const V2ThreadStartResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadStartResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadStartResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadStartResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadStartResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStatusChangedNotification__ThreadActiveFlag =\n  | \"waitingOnApproval\"\n  | \"waitingOnUserInput\";\nexport const V2ThreadStatusChangedNotification__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown = {\n  readonly cacheWriteInputTokens?: number;\n  readonly cachedInputTokens: number;\n  readonly inputTokens: number;\n  readonly outputTokens: number;\n  readonly reasoningOutputTokens: number;\n  readonly totalTokens: number;\n};\nexport const V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown = Schema.Struct({\n  cacheWriteInputTokens: Schema.optionalKey(\n    Schema.Number.annotate({ default: 0, format: \"int64\" }).check(Schema.isInt()),\n  ),\n  cachedInputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  inputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  outputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  reasoningOutputTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  totalTokens: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2ThreadUnarchiveResponse__AbsolutePathBuf = string;\nexport const V2ThreadUnarchiveResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadUnarchiveResponse__AgentPath = string;\nexport const V2ThreadUnarchiveResponse__AgentPath = Schema.String;\n\nexport type V2ThreadUnarchiveResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2ThreadUnarchiveResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2ThreadUnarchiveResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadUnarchiveResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadUnarchiveResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadUnarchiveResponse__GitInfo = {\n  readonly branch?: string | null;\n  readonly originUrl?: string | null;\n  readonly sha?: string | null;\n};\nexport const V2ThreadUnarchiveResponse__GitInfo = Schema.Struct({\n  branch: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  originUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadUnarchiveResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2ThreadUnarchiveResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2ThreadUnarchiveResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2ThreadUnarchiveResponse__LegacyAppPathString = string;\nexport const V2ThreadUnarchiveResponse__LegacyAppPathString = Schema.String;\n\nexport type V2ThreadUnarchiveResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2ThreadUnarchiveResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadUnarchiveResponse__McpToolCallError = { readonly message: string };\nexport const V2ThreadUnarchiveResponse__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2ThreadUnarchiveResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2ThreadUnarchiveResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadUnarchiveResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadUnarchiveResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2ThreadUnarchiveResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2ThreadUnarchiveResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2ThreadUnarchiveResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2ThreadUnarchiveResponse__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2ThreadUnarchiveResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2ThreadUnarchiveResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2ThreadUnarchiveResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2ThreadUnarchiveResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__ReasoningEffort = string;\nexport const V2ThreadUnarchiveResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2ThreadUnarchiveResponse__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2ThreadUnarchiveResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2ThreadUnarchiveResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2ThreadUnarchiveResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadUnarchiveResponse__ThreadActiveFlag =\n  | \"waitingOnApproval\"\n  | \"waitingOnUserInput\";\nexport const V2ThreadUnarchiveResponse__ThreadActiveFlag = Schema.Literals([\n  \"waitingOnApproval\",\n  \"waitingOnUserInput\",\n]);\n\nexport type V2ThreadUnarchiveResponse__ThreadId = string;\nexport const V2ThreadUnarchiveResponse__ThreadId = Schema.String;\n\nexport type V2ThreadUnarchiveResponse__ThreadSource = string;\nexport const V2ThreadUnarchiveResponse__ThreadSource = Schema.String;\n\nexport type V2ThreadUnarchiveResponse__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2ThreadUnarchiveResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2ThreadUnarchiveResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2ThreadUnarchiveResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus =\n  | \"notLoaded\"\n  | \"notSubscribed\"\n  | \"unsubscribed\";\nexport const V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus = Schema.Literals([\n  \"notLoaded\",\n  \"notSubscribed\",\n  \"unsubscribed\",\n]);\n\nexport type V2TurnCompletedNotification__AbsolutePathBuf = string;\nexport const V2TurnCompletedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2TurnCompletedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2TurnCompletedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2TurnCompletedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnCompletedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnCompletedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2TurnCompletedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2TurnCompletedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnCompletedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2TurnCompletedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnCompletedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2TurnCompletedNotification__LegacyAppPathString = string;\nexport const V2TurnCompletedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2TurnCompletedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2TurnCompletedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2TurnCompletedNotification__McpToolCallError = { readonly message: string };\nexport const V2TurnCompletedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2TurnCompletedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2TurnCompletedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnCompletedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnCompletedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2TurnCompletedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2TurnCompletedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2TurnCompletedNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2TurnCompletedNotification__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2TurnCompletedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnCompletedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnCompletedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2TurnCompletedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__ReasoningEffort = string;\nexport const V2TurnCompletedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2TurnCompletedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2TurnCompletedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2TurnCompletedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnCompletedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnCompletedNotification__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2TurnCompletedNotification__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2TurnCompletedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2TurnCompletedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnPlanUpdatedNotification__TurnPlanStepStatus =\n  | \"pending\"\n  | \"inProgress\"\n  | \"completed\";\nexport const V2TurnPlanUpdatedNotification__TurnPlanStepStatus = Schema.Literals([\n  \"pending\",\n  \"inProgress\",\n  \"completed\",\n]);\n\nexport type V2TurnStartedNotification__AbsolutePathBuf = string;\nexport const V2TurnStartedNotification__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2TurnStartedNotification__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2TurnStartedNotification__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2TurnStartedNotification__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnStartedNotification__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnStartedNotification__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2TurnStartedNotification__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartedNotification__DynamicToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2TurnStartedNotification__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartedNotification__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2TurnStartedNotification__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2TurnStartedNotification__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnStartedNotification__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2TurnStartedNotification__LegacyAppPathString = string;\nexport const V2TurnStartedNotification__LegacyAppPathString = Schema.String;\n\nexport type V2TurnStartedNotification__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2TurnStartedNotification__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2TurnStartedNotification__McpToolCallError = { readonly message: string };\nexport const V2TurnStartedNotification__McpToolCallError = Schema.Struct({\n  message: Schema.String,\n});\n\nexport type V2TurnStartedNotification__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2TurnStartedNotification__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2TurnStartedNotification__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnStartedNotification__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartedNotification__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2TurnStartedNotification__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2TurnStartedNotification__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2TurnStartedNotification__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2TurnStartedNotification__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2TurnStartedNotification__NonSteerableTurnKind = Schema.Literals([\n  \"review\",\n  \"compact\",\n]);\n\nexport type V2TurnStartedNotification__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnStartedNotification__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnStartedNotification__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2TurnStartedNotification__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartedNotification__ReasoningEffort = string;\nexport const V2TurnStartedNotification__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2TurnStartedNotification__SubAgentActivityKind =\n  | \"started\"\n  | \"interacted\"\n  | \"interrupted\";\nexport const V2TurnStartedNotification__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2TurnStartedNotification__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnStartedNotification__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnStartedNotification__TurnStatus =\n  | \"completed\"\n  | \"interrupted\"\n  | \"failed\"\n  | \"inProgress\";\nexport const V2TurnStartedNotification__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2TurnStartedNotification__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2TurnStartedNotification__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartParams__AbsolutePathBuf = string;\nexport const V2TurnStartParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2TurnStartParams__AdditionalContextKind = \"untrusted\" | \"application\";\nexport const V2TurnStartParams__AdditionalContextKind = Schema.Literals([\n  \"untrusted\",\n  \"application\",\n]);\n\nexport type V2TurnStartParams__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2TurnStartParams__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2TurnStartParams__AskForApproval =\n  | \"untrusted\"\n  | \"on-request\"\n  | \"never\"\n  | {\n      readonly granular: {\n        readonly mcp_elicitations: boolean;\n        readonly request_permissions?: boolean;\n        readonly rules: boolean;\n        readonly sandbox_approval: boolean;\n        readonly skill_approval?: boolean;\n      };\n    };\nexport const V2TurnStartParams__AskForApproval = Schema.Union(\n  [\n    Schema.Literals([\"untrusted\", \"on-request\", \"never\"]),\n    Schema.Struct({\n      granular: Schema.Struct({\n        mcp_elicitations: Schema.Boolean,\n        request_permissions: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        rules: Schema.Boolean,\n        sandbox_approval: Schema.Boolean,\n        skill_approval: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      }),\n    }).annotate({ title: \"GranularAskForApproval\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartParams__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnStartParams__ImageDetail = Schema.Literals([\"auto\", \"low\", \"high\", \"original\"]);\n\nexport type V2TurnStartParams__LegacyAppPathString = string;\nexport const V2TurnStartParams__LegacyAppPathString = Schema.String;\n\nexport type V2TurnStartParams__ModeKind = \"plan\" | \"default\";\nexport const V2TurnStartParams__ModeKind = Schema.Literals([\"plan\", \"default\"]).annotate({\n  description: \"Initial collaboration mode to use when the TUI starts.\",\n});\n\nexport type V2TurnStartParams__Personality = \"none\" | \"friendly\" | \"pragmatic\";\nexport const V2TurnStartParams__Personality = Schema.Literals([\"none\", \"friendly\", \"pragmatic\"]);\n\nexport type V2TurnStartParams__ReasoningEffort = string;\nexport const V2TurnStartParams__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2TurnStartParams__ReasoningSummary = \"auto\" | \"concise\" | \"detailed\" | \"none\";\nexport const V2TurnStartParams__ReasoningSummary = Schema.Union(\n  [\n    Schema.Literals([\"auto\", \"concise\", \"detailed\"]),\n    Schema.Literal(\"none\").annotate({ description: \"Option to disable reasoning summaries.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"A summary of the reasoning performed by the model. This can be useful for debugging and understanding the model's reasoning process. See https://platform.openai.com/docs/guides/reasoning?api-mode=responses#reasoning-summaries\",\n});\n\nexport type V2TurnStartParams__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnStartParams__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnStartResponse__AbsolutePathBuf = string;\nexport const V2TurnStartResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2TurnStartResponse__CollabAgentStatus =\n  | \"pendingInit\"\n  | \"running\"\n  | \"interrupted\"\n  | \"completed\"\n  | \"errored\"\n  | \"shutdown\"\n  | \"notFound\";\nexport const V2TurnStartResponse__CollabAgentStatus = Schema.Literals([\n  \"pendingInit\",\n  \"running\",\n  \"interrupted\",\n  \"completed\",\n  \"errored\",\n  \"shutdown\",\n  \"notFound\",\n]);\n\nexport type V2TurnStartResponse__CommandExecutionStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnStartResponse__CommandExecutionStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnStartResponse__DynamicToolCallOutputContentItem =\n  | { readonly text: string; readonly type: \"inputText\" }\n  | { readonly imageUrl: string; readonly type: \"inputImage\" }\n  | { readonly audioUrl: string; readonly type: \"inputAudio\" };\nexport const V2TurnStartResponse__DynamicToolCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"inputText\").annotate({\n        title: \"InputTextDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      imageUrl: Schema.String,\n      type: Schema.Literal(\"inputImage\").annotate({\n        title: \"InputImageDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageDynamicToolCallOutputContentItem\" }),\n    Schema.Struct({\n      audioUrl: Schema.String,\n      type: Schema.Literal(\"inputAudio\").annotate({\n        title: \"InputAudioDynamicToolCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioDynamicToolCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__DynamicToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnStartResponse__DynamicToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartResponse__HookPromptFragment = {\n  readonly hookRunId: string;\n  readonly text: string;\n};\nexport const V2TurnStartResponse__HookPromptFragment = Schema.Struct({\n  hookRunId: Schema.String,\n  text: Schema.String,\n});\n\nexport type V2TurnStartResponse__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnStartResponse__ImageDetail = Schema.Literals([\n  \"auto\",\n  \"low\",\n  \"high\",\n  \"original\",\n]);\n\nexport type V2TurnStartResponse__LegacyAppPathString = string;\nexport const V2TurnStartResponse__LegacyAppPathString = Schema.String;\n\nexport type V2TurnStartResponse__McpToolCallAppContext = {\n  readonly actionName?: string | null;\n  readonly appName?: string | null;\n  readonly connectorId: string;\n  readonly linkId?: string | null;\n  readonly resourceUri?: string | null;\n};\nexport const V2TurnStartResponse__McpToolCallAppContext = Schema.Struct({\n  actionName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  appName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  connectorId: Schema.String,\n  linkId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  resourceUri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2TurnStartResponse__McpToolCallError = { readonly message: string };\nexport const V2TurnStartResponse__McpToolCallError = Schema.Struct({ message: Schema.String });\n\nexport type V2TurnStartResponse__McpToolCallResult = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly structuredContent?: unknown;\n};\nexport const V2TurnStartResponse__McpToolCallResult = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n});\n\nexport type V2TurnStartResponse__McpToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnStartResponse__McpToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartResponse__MemoryCitationEntry = {\n  readonly lineEnd: number;\n  readonly lineStart: number;\n  readonly note: string;\n  readonly path: string;\n};\nexport const V2TurnStartResponse__MemoryCitationEntry = Schema.Struct({\n  lineEnd: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  lineStart: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  note: Schema.String,\n  path: Schema.String,\n});\n\nexport type V2TurnStartResponse__MessagePhase = \"commentary\" | \"final_answer\";\nexport const V2TurnStartResponse__MessagePhase = Schema.Literals([\n  \"commentary\",\n  \"final_answer\",\n]).annotate({\n  description:\n    'Classifies an assistant message as interim commentary or final answer text.\\n\\nProviders do not emit this consistently, so callers must treat `None` as \"phase unknown\" and keep compatibility behavior for legacy models.',\n});\n\nexport type V2TurnStartResponse__NonSteerableTurnKind = \"review\" | \"compact\";\nexport const V2TurnStartResponse__NonSteerableTurnKind = Schema.Literals([\"review\", \"compact\"]);\n\nexport type V2TurnStartResponse__PatchApplyStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\"\n  | \"declined\";\nexport const V2TurnStartResponse__PatchApplyStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n  \"declined\",\n]);\n\nexport type V2TurnStartResponse__PatchChangeKind =\n  | { readonly type: \"add\" }\n  | { readonly type: \"delete\" }\n  | { readonly move_path?: string | null; readonly type: \"update\" };\nexport const V2TurnStartResponse__PatchChangeKind = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"add\").annotate({ title: \"AddPatchChangeKindType\" }),\n    }).annotate({ title: \"AddPatchChangeKind\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"delete\").annotate({ title: \"DeletePatchChangeKindType\" }),\n    }).annotate({ title: \"DeletePatchChangeKind\" }),\n    Schema.Struct({\n      move_path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"update\").annotate({ title: \"UpdatePatchChangeKindType\" }),\n    }).annotate({ title: \"UpdatePatchChangeKind\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__ReasoningEffort = string;\nexport const V2TurnStartResponse__ReasoningEffort = Schema.String.annotate({\n  description: \"A non-empty reasoning effort value advertised by the model.\",\n}).check(Schema.isMinLength(1));\n\nexport type V2TurnStartResponse__SubAgentActivityKind = \"started\" | \"interacted\" | \"interrupted\";\nexport const V2TurnStartResponse__SubAgentActivityKind = Schema.Literals([\n  \"started\",\n  \"interacted\",\n  \"interrupted\",\n]);\n\nexport type V2TurnStartResponse__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnStartResponse__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnStartResponse__TurnStatus = \"completed\" | \"interrupted\" | \"failed\" | \"inProgress\";\nexport const V2TurnStartResponse__TurnStatus = Schema.Literals([\n  \"completed\",\n  \"interrupted\",\n  \"failed\",\n  \"inProgress\",\n]);\n\nexport type V2TurnStartResponse__WebSearchAction =\n  | {\n      readonly queries?: ReadonlyArray<string> | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly type: \"openPage\"; readonly url?: string | null }\n  | { readonly pattern?: string | null; readonly type: \"findInPage\"; readonly url?: string | null }\n  | { readonly type: \"other\" };\nexport const V2TurnStartResponse__WebSearchAction = Schema.Union(\n  [\n    Schema.Struct({\n      queries: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchWebSearchActionType\" }),\n    }).annotate({ title: \"SearchWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"openPage\").annotate({ title: \"OpenPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"OpenPageWebSearchAction\" }),\n    Schema.Struct({\n      pattern: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"findInPage\").annotate({ title: \"FindInPageWebSearchActionType\" }),\n      url: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ title: \"FindInPageWebSearchAction\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherWebSearchActionType\" }),\n    }).annotate({ title: \"OtherWebSearchAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnSteerParams__AdditionalContextKind = \"untrusted\" | \"application\";\nexport const V2TurnSteerParams__AdditionalContextKind = Schema.Literals([\n  \"untrusted\",\n  \"application\",\n]);\n\nexport type V2TurnSteerParams__ImageDetail = \"auto\" | \"low\" | \"high\" | \"original\";\nexport const V2TurnSteerParams__ImageDetail = Schema.Literals([\"auto\", \"low\", \"high\", \"original\"]);\n\nexport type V2TurnSteerParams__TextElement = {\n  readonly byteRange: { readonly end: number; readonly start: number };\n  readonly placeholder?: string | null;\n};\nexport const V2TurnSteerParams__TextElement = Schema.Struct({\n  byteRange: Schema.Struct({\n    end: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    start: Schema.Number.annotate({ format: \"uint\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({\n    description: \"Byte range in the parent `text` buffer that this element occupies.\",\n  }),\n  placeholder: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional human-readable placeholder for the element, displayed in the UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2WindowsSandboxReadinessResponse__WindowsSandboxReadiness =\n  | \"ready\"\n  | \"notConfigured\"\n  | \"updateRequired\";\nexport const V2WindowsSandboxReadinessResponse__WindowsSandboxReadiness = Schema.Literals([\n  \"ready\",\n  \"notConfigured\",\n  \"updateRequired\",\n]);\n\nexport type V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode =\n  | \"elevated\"\n  | \"unelevated\";\nexport const V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode = Schema.Literals([\n  \"elevated\",\n  \"unelevated\",\n]);\n\nexport type V2WindowsSandboxSetupStartParams__AbsolutePathBuf = string;\nexport const V2WindowsSandboxSetupStartParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode = \"elevated\" | \"unelevated\";\nexport const V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode = Schema.Literals([\n  \"elevated\",\n  \"unelevated\",\n]);\n\nexport type ApplyPatchApprovalResponse__NetworkPolicyAmendment = {\n  readonly action: ApplyPatchApprovalResponse__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const ApplyPatchApprovalResponse__NetworkPolicyAmendment = Schema.Struct({\n  action: ApplyPatchApprovalResponse__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type ClientRequest__PluginInstallParams = {\n  readonly marketplacePath?: ClientRequest__AbsolutePathBuf | null;\n  readonly pluginName: string;\n  readonly remoteMarketplaceName?: string | null;\n};\nexport const ClientRequest__PluginInstallParams = Schema.Struct({\n  marketplacePath: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])),\n  pluginName: Schema.String,\n  remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__PluginInstalledParams = {\n  readonly cwds?: ReadonlyArray<ClientRequest__AbsolutePathBuf> | null;\n  readonly installSuggestionPluginNames?: ReadonlyArray<string> | null;\n};\nexport const ClientRequest__PluginInstalledParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__AbsolutePathBuf).annotate({\n        description: \"Optional working directories used to discover repo marketplaces.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  installSuggestionPluginNames: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Additional uninstalled plugin names that should be returned when present locally. This is used by mention surfaces that intentionally expose install entrypoints.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__PluginReadParams = {\n  readonly marketplacePath?: ClientRequest__AbsolutePathBuf | null;\n  readonly pluginName: string;\n  readonly remoteMarketplaceName?: string | null;\n};\nexport const ClientRequest__PluginReadParams = Schema.Struct({\n  marketplacePath: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])),\n  pluginName: Schema.String,\n  remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<ClientRequest__AbsolutePathBuf>;\n    };\nexport const ClientRequest__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(ClientRequest__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__SkillsConfigWriteParams = {\n  readonly enabled: boolean;\n  readonly name?: string | null;\n  readonly path?: ClientRequest__AbsolutePathBuf | null;\n};\nexport const ClientRequest__SkillsConfigWriteParams = Schema.Struct({\n  enabled: Schema.Boolean,\n  name: Schema.optionalKey(\n    Schema.Union([Schema.String.annotate({ description: \"Name-based selector.\" }), Schema.Null]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Path-based selector.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__SkillsExtraRootsSetParams = {\n  readonly extraRoots: ReadonlyArray<ClientRequest__AbsolutePathBuf>;\n};\nexport const ClientRequest__SkillsExtraRootsSetParams = Schema.Struct({\n  extraRoots: Schema.Array(ClientRequest__AbsolutePathBuf),\n});\n\nexport type ClientRequest__SendAddCreditsNudgeEmailParams = {\n  readonly creditType: ClientRequest__AddCreditsNudgeCreditType;\n};\nexport const ClientRequest__SendAddCreditsNudgeEmailParams = Schema.Struct({\n  creditType: ClientRequest__AddCreditsNudgeCreditType,\n});\n\nexport type ClientRequest__ContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: ClientRequest__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly text: string; readonly type: \"output_text\" };\nexport const ClientRequest__ContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({ title: \"InputTextContentItemType\" }),\n    }).annotate({ title: \"InputTextContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({ title: \"InputImageContentItemType\" }),\n    }).annotate({ title: \"InputImageContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({ title: \"InputAudioContentItemType\" }),\n    }).annotate({ title: \"InputAudioContentItem\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"output_text\").annotate({ title: \"OutputTextContentItemType\" }),\n    }).annotate({ title: \"OutputTextContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__FunctionCallOutputContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: ClientRequest__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const ClientRequest__FunctionCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({\n        title: \"InputImageFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({\n        title: \"InputAudioFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"EncryptedContentFunctionCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.\",\n});\n\nexport type ClientRequest__InitializeParams = {\n  readonly capabilities?: ClientRequest__InitializeCapabilities | null;\n  readonly clientInfo: ClientRequest__ClientInfo;\n};\nexport const ClientRequest__InitializeParams = Schema.Struct({\n  capabilities: Schema.optionalKey(\n    Schema.Union([ClientRequest__InitializeCapabilities, Schema.Null]),\n  ),\n  clientInfo: ClientRequest__ClientInfo,\n});\n\nexport type ClientRequest__LoginAccountParams =\n  | { readonly apiKey: string; readonly type: \"apiKey\" }\n  | {\n      readonly appBrand?: ClientRequest__LoginAppBrand | null;\n      readonly codexStreamlinedLogin?: boolean;\n      readonly type: \"chatgpt\";\n      readonly useHostedLoginSuccessPage?: boolean;\n    }\n  | { readonly type: \"chatgptDeviceCode\" }\n  | {\n      readonly accessToken: string;\n      readonly chatgptAccountId: string;\n      readonly chatgptPlanType?: string | null;\n      readonly type: \"chatgptAuthTokens\";\n    }\n  | { readonly apiKey: string; readonly region: string; readonly type: \"amazonBedrock\" };\nexport const ClientRequest__LoginAccountParams = Schema.Union(\n  [\n    Schema.Struct({\n      apiKey: Schema.String,\n      type: Schema.Literal(\"apiKey\").annotate({ title: \"ApiKeyLoginAccountParamsType\" }),\n    }).annotate({ title: \"ApiKeyLoginAccountParams\" }),\n    Schema.Struct({\n      appBrand: Schema.optionalKey(Schema.Union([ClientRequest__LoginAppBrand, Schema.Null])),\n      codexStreamlinedLogin: Schema.optionalKey(Schema.Boolean),\n      type: Schema.Literal(\"chatgpt\").annotate({ title: \"ChatgptLoginAccountParamsType\" }),\n      useHostedLoginSuccessPage: Schema.optionalKey(Schema.Boolean),\n    }).annotate({ title: \"ChatgptLoginAccountParams\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"chatgptDeviceCode\").annotate({\n        title: \"ChatgptDeviceCodeLoginAccountParamsType\",\n      }),\n    }).annotate({ title: \"ChatgptDeviceCodeLoginAccountParams\" }),\n    Schema.Struct({\n      accessToken: Schema.String.annotate({\n        description:\n          \"Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.\",\n      }),\n      chatgptAccountId: Schema.String.annotate({\n        description: \"Workspace/account identifier supplied by the client.\",\n      }),\n      chatgptPlanType: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional plan type supplied by the client.\\n\\nWhen `null`, Codex attempts to derive the plan type from access-token claims. If unavailable, the plan defaults to `unknown`.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"chatgptAuthTokens\").annotate({\n        title: \"ChatgptAuthTokensLoginAccountParamsType\",\n      }),\n    }).annotate({\n      title: \"ChatgptAuthTokensLoginAccountParams\",\n      description:\n        \"[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.\",\n    }),\n    Schema.Struct({\n      apiKey: Schema.String,\n      region: Schema.String,\n      type: Schema.Literal(\"amazonBedrock\").annotate({\n        title: \"AmazonBedrockLoginAccountParamsType\",\n      }),\n    }).annotate({\n      title: \"AmazonBedrockLoginAccountParams\",\n      description: \"[UNSTABLE] Managed Amazon Bedrock login is experimental.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ListMcpServerStatusParams = {\n  readonly cursor?: string | null;\n  readonly detail?: ClientRequest__McpServerStatusDetail | null;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const ClientRequest__ListMcpServerStatusParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  detail: Schema.optionalKey(\n    Schema.Union([ClientRequest__McpServerStatusDetail, Schema.Null]).annotate({\n      description:\n        \"Controls how much MCP inventory data to fetch for each server. Defaults to `Full` when omitted.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a server-defined value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ClientRequest__ConfigEdit = {\n  readonly keyPath: string;\n  readonly mergeStrategy: ClientRequest__MergeStrategy;\n  readonly value: unknown;\n};\nexport const ClientRequest__ConfigEdit = Schema.Struct({\n  keyPath: Schema.String,\n  mergeStrategy: ClientRequest__MergeStrategy,\n  value: Schema.Unknown,\n});\n\nexport type ClientRequest__ConfigValueWriteParams = {\n  readonly expectedVersion?: string | null;\n  readonly filePath?: string | null;\n  readonly keyPath: string;\n  readonly mergeStrategy: ClientRequest__MergeStrategy;\n  readonly value: unknown;\n};\nexport const ClientRequest__ConfigValueWriteParams = Schema.Struct({\n  expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  filePath: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Path to the config file to write; defaults to the user's `config.toml` when omitted.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  keyPath: Schema.String,\n  mergeStrategy: ClientRequest__MergeStrategy,\n  value: Schema.Unknown,\n});\n\nexport type ClientRequest__PluginListParams = {\n  readonly cwds?: ReadonlyArray<ClientRequest__AbsolutePathBuf> | null;\n  readonly marketplaceKinds?: ReadonlyArray<ClientRequest__PluginListMarketplaceKind> | null;\n};\nexport const ClientRequest__PluginListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__AbsolutePathBuf).annotate({\n        description:\n          \"Optional working directories used to discover repo marketplaces. When omitted, only home-scoped marketplaces and the official curated marketplace are considered.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  marketplaceKinds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__PluginListMarketplaceKind).annotate({\n        description:\n          \"Optional marketplace kind filter. When omitted, only local marketplaces are queried, plus the default remote catalog when enabled by feature flag.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest__PluginShareTarget = {\n  readonly principalId: string;\n  readonly principalType: ClientRequest__PluginSharePrincipalType;\n  readonly role: ClientRequest__PluginShareTargetRole;\n};\nexport const ClientRequest__PluginShareTarget = Schema.Struct({\n  principalId: Schema.String,\n  principalType: ClientRequest__PluginSharePrincipalType,\n  role: ClientRequest__PluginShareTargetRole,\n});\n\nexport type ClientRequest__Settings = {\n  readonly developer_instructions?: string | null;\n  readonly model: string;\n  readonly reasoning_effort?: ClientRequest__ReasoningEffort | null;\n};\nexport const ClientRequest__Settings = Schema.Struct({\n  developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasoning_effort: Schema.optionalKey(Schema.Union([ClientRequest__ReasoningEffort, Schema.Null])),\n}).annotate({ description: \"Settings for a collaboration mode.\" });\n\nexport type ClientRequest__ReviewStartParams = {\n  readonly delivery?: ClientRequest__ReviewDelivery | null;\n  readonly target: ClientRequest__ReviewTarget;\n  readonly threadId: string;\n};\nexport const ClientRequest__ReviewStartParams = Schema.Struct({\n  delivery: Schema.optionalKey(\n    Schema.Union([ClientRequest__ReviewDelivery, Schema.Null]).annotate({\n      description:\n        \"Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`).\",\n    }),\n  ),\n  target: ClientRequest__ReviewTarget,\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadResumeParams = {\n  readonly approvalPolicy?: ClientRequest__AskForApproval | null;\n  readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly personality?: ClientRequest__Personality | null;\n  readonly sandbox?: ClientRequest__SandboxMode | null;\n  readonly serviceTier?: string | null;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadResumeParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Configuration overrides for the resumed thread, if any.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  personality: Schema.optionalKey(Schema.Union([ClientRequest__Personality, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n}).annotate({\n  description:\n    \"There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\\n\\nFor non-running threads, the precedence is: history > non-empty path > thread_id. If using history or a non-empty path for a non-running thread, the thread_id param will be ignored.\\n\\nIf thread_id identifies a running thread, app-server rejoins that thread and treats a non-empty path as a consistency check against the active rollout path. Empty string path values are treated as absent.\\n\\nPrefer using thread_id whenever possible.\",\n});\n\nexport type ClientRequest__MigrationDetails = {\n  readonly commands?: ReadonlyArray<ClientRequest__CommandMigration>;\n  readonly hooks?: ReadonlyArray<ClientRequest__HookMigration>;\n  readonly mcpServers?: ReadonlyArray<ClientRequest__McpServerMigration>;\n  readonly memory?: ReadonlyArray<string>;\n  readonly plugins?: ReadonlyArray<ClientRequest__PluginsMigration>;\n  readonly sessions?: ReadonlyArray<ClientRequest__SessionMigration>;\n  readonly skills?: ReadonlyArray<ClientRequest__SkillMigration>;\n  readonly subagents?: ReadonlyArray<ClientRequest__SubagentMigration>;\n};\nexport const ClientRequest__MigrationDetails = Schema.Struct({\n  commands: Schema.optionalKey(\n    Schema.Array(ClientRequest__CommandMigration).annotate({ default: [] }),\n  ),\n  hooks: Schema.optionalKey(Schema.Array(ClientRequest__HookMigration).annotate({ default: [] })),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(ClientRequest__McpServerMigration).annotate({ default: [] }),\n  ),\n  memory: Schema.optionalKey(Schema.Array(Schema.String)),\n  plugins: Schema.optionalKey(\n    Schema.Array(ClientRequest__PluginsMigration).annotate({ default: [] }),\n  ),\n  sessions: Schema.optionalKey(\n    Schema.Array(ClientRequest__SessionMigration).annotate({ default: [] }),\n  ),\n  skills: Schema.optionalKey(Schema.Array(ClientRequest__SkillMigration).annotate({ default: [] })),\n  subagents: Schema.optionalKey(\n    Schema.Array(ClientRequest__SubagentMigration).annotate({ default: [] }),\n  ),\n});\n\nexport type ClientRequest__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<ClientRequest__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: ClientRequest__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: ClientRequest__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const ClientRequest__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(ClientRequest__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ClientRequest__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ThreadGoalSetParams = {\n  readonly objective?: string | null;\n  readonly status?: ClientRequest__ThreadGoalStatus | null;\n  readonly threadId: string;\n  readonly tokenBudget?: number | null;\n};\nexport const ClientRequest__ThreadGoalSetParams = Schema.Struct({\n  objective: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: Schema.optionalKey(Schema.Union([ClientRequest__ThreadGoalStatus, Schema.Null])),\n  threadId: Schema.String,\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n});\n\nexport type ClientRequest__ThreadMetadataUpdateParams = {\n  readonly gitInfo?: ClientRequest__ThreadMetadataGitInfoUpdateParams | null;\n  readonly threadId: string;\n};\nexport const ClientRequest__ThreadMetadataUpdateParams = Schema.Struct({\n  gitInfo: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadMetadataGitInfoUpdateParams, Schema.Null]).annotate({\n      description:\n        \"Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value.\",\n    }),\n  ),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__ThreadForkParams = {\n  readonly approvalPolicy?: ClientRequest__AskForApproval | null;\n  readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly ephemeral?: boolean;\n  readonly lastTurnId?: string | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly sandbox?: ClientRequest__SandboxMode | null;\n  readonly serviceTier?: string | null;\n  readonly threadId: string;\n  readonly threadSource?: ClientRequest__ThreadSource | null;\n};\nexport const ClientRequest__ThreadForkParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  ephemeral: Schema.optionalKey(Schema.Boolean),\n  lastTurnId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional last turn id to fork through, inclusive.\\n\\nWhen specified, turns after `last_turn_id` are omitted from the fork. The referenced turn cannot be in progress.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Configuration overrides for the forked thread, if any.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  threadSource: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadSource, Schema.Null]).annotate({\n      description:\n        \"Optional client-supplied analytics source classification for this forked thread.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\\n\\nIf using a non-empty path, the thread_id param will be ignored. Empty string path values are treated as absent.\\n\\nPrefer using thread_id whenever possible.\",\n});\n\nexport type ClientRequest__ThreadListParams = {\n  readonly archived?: boolean | null;\n  readonly cursor?: string | null;\n  readonly cwd?: ClientRequest__ThreadListCwdFilter | null;\n  readonly limit?: number | null;\n  readonly modelProviders?: ReadonlyArray<string> | null;\n  readonly searchTerm?: string | null;\n  readonly sortDirection?: ClientRequest__SortDirection | null;\n  readonly sortKey?: ClientRequest__ThreadSortKey | null;\n  readonly sourceKinds?: ReadonlyArray<ClientRequest__ThreadSourceKind> | null;\n  readonly useStateDbOnly?: boolean;\n};\nexport const ClientRequest__ThreadListParams = Schema.Struct({\n  archived: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadListCwdFilter, Schema.Null]).annotate({\n      description:\n        \"Optional cwd filter or filters; when set, only threads whose session cwd exactly matches one of these paths are returned.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  modelProviders: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  searchTerm: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional substring filter for the extracted thread title.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sortDirection: Schema.optionalKey(\n    Schema.Union([ClientRequest__SortDirection, Schema.Null]).annotate({\n      description: \"Optional sort direction; defaults to descending (newest first).\",\n    }),\n  ),\n  sortKey: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadSortKey, Schema.Null]).annotate({\n      description: \"Optional sort key; defaults to created_at.\",\n    }),\n  ),\n  sourceKinds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__ThreadSourceKind).annotate({\n        description:\n          \"Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  useStateDbOnly: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"If true, return from the state DB without scanning JSONL rollouts to repair thread metadata. Omitted or false preserves scan-and-repair behavior.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__ThreadStartParams = {\n  readonly approvalPolicy?: ClientRequest__AskForApproval | null;\n  readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly ephemeral?: boolean | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly personality?: ClientRequest__Personality | null;\n  readonly sandbox?: ClientRequest__SandboxMode | null;\n  readonly serviceName?: string | null;\n  readonly serviceTier?: string | null;\n  readonly sessionStartSource?: ClientRequest__ThreadStartSource | null;\n  readonly threadSource?: ClientRequest__ThreadSource | null;\n};\nexport const ClientRequest__ThreadStartParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(Schema.Union([ClientRequest__AskForApproval, Schema.Null])),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  ephemeral: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  personality: Schema.optionalKey(Schema.Union([ClientRequest__Personality, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([ClientRequest__SandboxMode, Schema.Null])),\n  serviceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sessionStartSource: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadStartSource, Schema.Null]),\n  ),\n  threadSource: Schema.optionalKey(\n    Schema.Union([ClientRequest__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional client-supplied analytics source classification for this thread.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__WindowsSandboxSetupStartParams = {\n  readonly cwd?: ClientRequest__AbsolutePathBuf | null;\n  readonly mode: ClientRequest__WindowsSandboxSetupMode;\n};\nexport const ClientRequest__WindowsSandboxSetupStartParams = Schema.Struct({\n  cwd: Schema.optionalKey(Schema.Union([ClientRequest__AbsolutePathBuf, Schema.Null])),\n  mode: ClientRequest__WindowsSandboxSetupMode,\n});\n\nexport type CommandExecutionRequestApprovalParams__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: CommandExecutionRequestApprovalParams__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const CommandExecutionRequestApprovalParams__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: CommandExecutionRequestApprovalParams__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type CommandExecutionRequestApprovalParams__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: CommandExecutionRequestApprovalParams__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: CommandExecutionRequestApprovalParams__LegacyAppPathString | null;\n    };\nexport const CommandExecutionRequestApprovalParams__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([CommandExecutionRequestApprovalParams__LegacyAppPathString, Schema.Null]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([CommandExecutionRequestApprovalParams__LegacyAppPathString, Schema.Null]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type CommandExecutionRequestApprovalParams__NetworkApprovalContext = {\n  readonly host: string;\n  readonly protocol: CommandExecutionRequestApprovalParams__NetworkApprovalProtocol;\n};\nexport const CommandExecutionRequestApprovalParams__NetworkApprovalContext = Schema.Struct({\n  host: Schema.String,\n  protocol: CommandExecutionRequestApprovalParams__NetworkApprovalProtocol,\n});\n\nexport type CommandExecutionRequestApprovalParams__NetworkPolicyAmendment = {\n  readonly action: CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const CommandExecutionRequestApprovalParams__NetworkPolicyAmendment = Schema.Struct({\n  action: CommandExecutionRequestApprovalParams__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment = {\n  readonly action: CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment = Schema.Struct({\n  action: CommandExecutionRequestApprovalResponse__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type ExecCommandApprovalResponse__NetworkPolicyAmendment = {\n  readonly action: ExecCommandApprovalResponse__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const ExecCommandApprovalResponse__NetworkPolicyAmendment = Schema.Struct({\n  action: ExecCommandApprovalResponse__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type FuzzyFileSearchResponse__FuzzyFileSearchResult = {\n  readonly file_name: string;\n  readonly indices?: ReadonlyArray<number> | null;\n  readonly match_type: FuzzyFileSearchResponse__FuzzyFileSearchMatchType;\n  readonly path: string;\n  readonly root: string;\n  readonly score: number;\n};\nexport const FuzzyFileSearchResponse__FuzzyFileSearchResult = Schema.Struct({\n  file_name: Schema.String,\n  indices: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(\n        Schema.Number.annotate({ format: \"uint32\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  match_type: FuzzyFileSearchResponse__FuzzyFileSearchMatchType,\n  path: Schema.String,\n  root: Schema.String,\n  score: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"Superset of [`codex_file_search::FileMatch`]\" });\n\nexport type FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult = {\n  readonly file_name: string;\n  readonly indices?: ReadonlyArray<number> | null;\n  readonly match_type: FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType;\n  readonly path: string;\n  readonly root: string;\n  readonly score: number;\n};\nexport const FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult = Schema.Struct({\n  file_name: Schema.String,\n  indices: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(\n        Schema.Number.annotate({ format: \"uint32\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  match_type: FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchMatchType,\n  path: Schema.String,\n  root: Schema.String,\n  score: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"Superset of [`codex_file_search::FileMatch`]\" });\n\nexport type JSONRPCMessage__JSONRPCError = {\n  readonly error: JSONRPCMessage__JSONRPCErrorError;\n  readonly id: JSONRPCMessage__RequestId;\n};\nexport const JSONRPCMessage__JSONRPCError = Schema.Struct({\n  error: JSONRPCMessage__JSONRPCErrorError,\n  id: JSONRPCMessage__RequestId,\n}).annotate({ description: \"A response to a request that indicates an error occurred.\" });\n\nexport type JSONRPCMessage__JSONRPCResponse = {\n  readonly id: JSONRPCMessage__RequestId;\n  readonly result: unknown;\n};\nexport const JSONRPCMessage__JSONRPCResponse = Schema.Struct({\n  id: JSONRPCMessage__RequestId,\n  result: Schema.Unknown,\n}).annotate({ description: \"A successful (non-error) response to a request.\" });\n\nexport type JSONRPCMessage__JSONRPCRequest = {\n  readonly id: JSONRPCMessage__RequestId;\n  readonly method: string;\n  readonly params?: unknown;\n  readonly trace?: JSONRPCMessage__W3cTraceContext | null;\n};\nexport const JSONRPCMessage__JSONRPCRequest = Schema.Struct({\n  id: JSONRPCMessage__RequestId,\n  method: Schema.String,\n  params: Schema.optionalKey(Schema.Unknown),\n  trace: Schema.optionalKey(\n    Schema.Union([JSONRPCMessage__W3cTraceContext, Schema.Null]).annotate({\n      description: \"Optional W3C Trace Context for distributed tracing.\",\n    }),\n  ),\n}).annotate({ description: \"A request that expects a response.\" });\n\nexport type McpServerElicitationRequestParams__McpElicitationBooleanSchema = {\n  readonly default?: boolean | null;\n  readonly description?: string | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationBooleanType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationBooleanSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: McpServerElicitationRequestParams__McpElicitationBooleanType,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationTitledEnumItems = {\n  readonly anyOf: ReadonlyArray<McpServerElicitationRequestParams__McpElicitationConstOption>;\n};\nexport const McpServerElicitationRequestParams__McpElicitationTitledEnumItems = Schema.Struct({\n  anyOf: Schema.Array(McpServerElicitationRequestParams__McpElicitationConstOption),\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationNumberSchema = {\n  readonly default?: number | null;\n  readonly description?: string | null;\n  readonly maximum?: number | null;\n  readonly minimum?: number | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationNumberType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationNumberSchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  maximum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  minimum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: McpServerElicitationRequestParams__McpElicitationNumberType,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum: ReadonlyArray<string>;\n  readonly enumNames?: ReadonlyArray<string> | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    enum: Schema.Array(Schema.String),\n    enumNames: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationStringType,\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationStringSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly format?: McpServerElicitationRequestParams__McpElicitationStringFormat | null;\n  readonly maxLength?: number | null;\n  readonly minLength?: number | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationStringSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  format: Schema.optionalKey(\n    Schema.Union([McpServerElicitationRequestParams__McpElicitationStringFormat, Schema.Null]),\n  ),\n  maxLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: McpServerElicitationRequestParams__McpElicitationStringType,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly oneOf: ReadonlyArray<McpServerElicitationRequestParams__McpElicitationConstOption>;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    oneOf: Schema.Array(McpServerElicitationRequestParams__McpElicitationConstOption),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationStringType,\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationUntitledEnumItems = {\n  readonly enum: ReadonlyArray<string>;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationUntitledEnumItems = Schema.Struct({\n  enum: Schema.Array(Schema.String),\n  type: McpServerElicitationRequestParams__McpElicitationStringType,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum: ReadonlyArray<string>;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationStringType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    enum: Schema.Array(Schema.String),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationStringType,\n  });\n\nexport type PermissionsRequestApprovalParams__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: PermissionsRequestApprovalParams__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: PermissionsRequestApprovalParams__LegacyAppPathString | null;\n    };\nexport const PermissionsRequestApprovalParams__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([PermissionsRequestApprovalParams__LegacyAppPathString, Schema.Null]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([PermissionsRequestApprovalParams__LegacyAppPathString, Schema.Null]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type PermissionsRequestApprovalResponse__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: PermissionsRequestApprovalResponse__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: PermissionsRequestApprovalResponse__LegacyAppPathString | null;\n    };\nexport const PermissionsRequestApprovalResponse__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([PermissionsRequestApprovalResponse__LegacyAppPathString, Schema.Null]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([PermissionsRequestApprovalResponse__LegacyAppPathString, Schema.Null]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: ServerNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const ServerNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: ServerNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__FsChangedNotification = {\n  readonly changedPaths: ReadonlyArray<ServerNotification__AbsolutePathBuf>;\n  readonly watchId: string;\n};\nexport const ServerNotification__FsChangedNotification = Schema.Struct({\n  changedPaths: Schema.Array(ServerNotification__AbsolutePathBuf).annotate({\n    description: \"File or directory paths associated with this event.\",\n  }),\n  watchId: Schema.String.annotate({\n    description: \"Watch identifier previously provided to `fs/watch`.\",\n  }),\n}).annotate({ description: \"Filesystem watch notification emitted for `fs/watch` subscribers.\" });\n\nexport type ServerNotification__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<ServerNotification__AbsolutePathBuf>;\n    };\nexport const ServerNotification__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(ServerNotification__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__AppMetadata = {\n  readonly categories?: ReadonlyArray<string> | null;\n  readonly developer?: string | null;\n  readonly firstPartyRequiresInstall?: boolean | null;\n  readonly firstPartyType?: string | null;\n  readonly review?: ServerNotification__AppReview | null;\n  readonly screenshots?: ReadonlyArray<ServerNotification__AppScreenshot> | null;\n  readonly seoDescription?: string | null;\n  readonly showInComposerWhenUnlinked?: boolean | null;\n  readonly subCategories?: ReadonlyArray<string> | null;\n  readonly version?: string | null;\n  readonly versionId?: string | null;\n  readonly versionNotes?: string | null;\n};\nexport const ServerNotification__AppMetadata = Schema.Struct({\n  categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  review: Schema.optionalKey(Schema.Union([ServerNotification__AppReview, Schema.Null])),\n  screenshots: Schema.optionalKey(\n    Schema.Union([Schema.Array(ServerNotification__AppScreenshot), Schema.Null]),\n  ),\n  seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: ServerNotification__CollabAgentStatus;\n};\nexport const ServerNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: ServerNotification__CollabAgentStatus,\n});\n\nexport type ServerNotification__ExternalAgentConfigImportItemTypeFailure = {\n  readonly cwd?: string | null;\n  readonly errorType?: string | null;\n  readonly failureStage: string;\n  readonly itemType: ServerNotification__ExternalAgentConfigMigrationItemType;\n  readonly message: string;\n  readonly source?: string | null;\n  readonly subErrorType?: string | null;\n};\nexport const ServerNotification__ExternalAgentConfigImportItemTypeFailure = Schema.Struct({\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  errorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  failureStage: Schema.String,\n  itemType: ServerNotification__ExternalAgentConfigMigrationItemType,\n  message: Schema.String,\n  source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  subErrorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__ExternalAgentConfigImportItemTypeSuccess = {\n  readonly cwd?: string | null;\n  readonly itemType: ServerNotification__ExternalAgentConfigMigrationItemType;\n  readonly source?: string | null;\n  readonly target?: string | null;\n};\nexport const ServerNotification__ExternalAgentConfigImportItemTypeSuccess = Schema.Struct({\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  itemType: ServerNotification__ExternalAgentConfigMigrationItemType,\n  source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  target: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__FuzzyFileSearchResult = {\n  readonly file_name: string;\n  readonly indices?: ReadonlyArray<number> | null;\n  readonly match_type: ServerNotification__FuzzyFileSearchMatchType;\n  readonly path: string;\n  readonly root: string;\n  readonly score: number;\n};\nexport const ServerNotification__FuzzyFileSearchResult = Schema.Struct({\n  file_name: Schema.String,\n  indices: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(\n        Schema.Number.annotate({ format: \"uint32\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  match_type: ServerNotification__FuzzyFileSearchMatchType,\n  path: Schema.String,\n  root: Schema.String,\n  score: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"Superset of [`codex_file_search::FileMatch`]\" });\n\nexport type ServerNotification__GuardianApprovalReview = {\n  readonly rationale?: string | null;\n  readonly riskLevel?: ServerNotification__GuardianRiskLevel | null;\n  readonly status: ServerNotification__GuardianApprovalReviewStatus;\n  readonly userAuthorization?: ServerNotification__GuardianUserAuthorization | null;\n};\nexport const ServerNotification__GuardianApprovalReview = Schema.Struct({\n  rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  riskLevel: Schema.optionalKey(Schema.Union([ServerNotification__GuardianRiskLevel, Schema.Null])),\n  status: ServerNotification__GuardianApprovalReviewStatus,\n  userAuthorization: Schema.optionalKey(\n    Schema.Union([ServerNotification__GuardianUserAuthorization, Schema.Null]),\n  ),\n}).annotate({\n  description:\n    \"[UNSTABLE] Temporary approval auto-review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.\",\n});\n\nexport type ServerNotification__HookOutputEntry = {\n  readonly kind: ServerNotification__HookOutputEntryKind;\n  readonly text: string;\n};\nexport const ServerNotification__HookOutputEntry = Schema.Struct({\n  kind: ServerNotification__HookOutputEntryKind,\n  text: Schema.String,\n});\n\nexport type ServerNotification__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: ServerNotification__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: ServerNotification__LegacyAppPathString | null;\n    };\nexport const ServerNotification__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([ServerNotification__LegacyAppPathString, Schema.Null]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([ServerNotification__LegacyAppPathString, Schema.Null]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__McpServerStatusUpdatedNotification = {\n  readonly error?: string | null;\n  readonly failureReason?: ServerNotification__McpServerStartupFailureReason | null;\n  readonly name: string;\n  readonly status: ServerNotification__McpServerStartupState;\n  readonly threadId?: string | null;\n};\nexport const ServerNotification__McpServerStatusUpdatedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  failureReason: Schema.optionalKey(\n    Schema.Union([ServerNotification__McpServerStartupFailureReason, Schema.Null]),\n  ),\n  name: Schema.String,\n  status: ServerNotification__McpServerStartupState,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<ServerNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const ServerNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(ServerNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type ServerNotification__ModelReroutedNotification = {\n  readonly fromModel: string;\n  readonly reason: ServerNotification__ModelRerouteReason;\n  readonly threadId: string;\n  readonly toModel: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ModelReroutedNotification = Schema.Struct({\n  fromModel: Schema.String,\n  reason: ServerNotification__ModelRerouteReason,\n  threadId: Schema.String,\n  toModel: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__ModelVerificationNotification = {\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly verifications: ReadonlyArray<ServerNotification__ModelVerification>;\n};\nexport const ServerNotification__ModelVerificationNotification = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n  verifications: Schema.Array(ServerNotification__ModelVerification),\n});\n\nexport type ServerNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: ServerNotification__NonSteerableTurnKind;\n      };\n    };\nexport const ServerNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({ turnKind: ServerNotification__NonSteerableTurnKind }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type ServerNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: ServerNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const ServerNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: ServerNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type ServerNotification__AccountUpdatedNotification = {\n  readonly authMode?: ServerNotification__AuthMode | null;\n  readonly planType?: ServerNotification__PlanType | null;\n};\nexport const ServerNotification__AccountUpdatedNotification = Schema.Struct({\n  authMode: Schema.optionalKey(Schema.Union([ServerNotification__AuthMode, Schema.Null])),\n  planType: Schema.optionalKey(Schema.Union([ServerNotification__PlanType, Schema.Null])),\n});\n\nexport type ServerNotification__ThreadRealtimeStartedNotification = {\n  readonly realtimeSessionId?: string | null;\n  readonly threadId: string;\n  readonly version: ServerNotification__RealtimeConversationVersion;\n};\nexport const ServerNotification__ThreadRealtimeStartedNotification = Schema.Struct({\n  realtimeSessionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  version: ServerNotification__RealtimeConversationVersion,\n}).annotate({ description: \"EXPERIMENTAL - emitted when thread realtime startup is accepted.\" });\n\nexport type ServerNotification__Settings = {\n  readonly developer_instructions?: string | null;\n  readonly model: string;\n  readonly reasoning_effort?: ServerNotification__ReasoningEffort | null;\n};\nexport const ServerNotification__Settings = Schema.Struct({\n  developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasoning_effort: Schema.optionalKey(\n    Schema.Union([ServerNotification__ReasoningEffort, Schema.Null]),\n  ),\n}).annotate({ description: \"Settings for a collaboration mode.\" });\n\nexport type ServerNotification__RemoteControlStatusChangedNotification = {\n  readonly environmentId?: string | null;\n  readonly installationId: string;\n  readonly serverName: string;\n  readonly status: ServerNotification__RemoteControlConnectionStatus;\n};\nexport const ServerNotification__RemoteControlStatusChangedNotification = Schema.Struct({\n  environmentId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  installationId: Schema.String,\n  serverName: Schema.String,\n  status: ServerNotification__RemoteControlConnectionStatus,\n}).annotate({\n  description: \"Current remote-control connection status and remote identity exposed to clients.\",\n});\n\nexport type ServerNotification__ServerRequestResolvedNotification = {\n  readonly requestId: ServerNotification__RequestId;\n  readonly threadId: string;\n};\nexport const ServerNotification__ServerRequestResolvedNotification = Schema.Struct({\n  requestId: ServerNotification__RequestId,\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__RateLimitSnapshot = {\n  readonly credits?: ServerNotification__CreditsSnapshot | null;\n  readonly individualLimit?: ServerNotification__SpendControlLimitSnapshot | null;\n  readonly limitId?: string | null;\n  readonly limitName?: string | null;\n  readonly planType?: ServerNotification__PlanType | null;\n  readonly primary?: ServerNotification__RateLimitWindow | null;\n  readonly rateLimitReachedType?: ServerNotification__RateLimitReachedType | null;\n  readonly secondary?: ServerNotification__RateLimitWindow | null;\n  readonly spendControlReached?: boolean | null;\n};\nexport const ServerNotification__RateLimitSnapshot = Schema.Struct({\n  credits: Schema.optionalKey(Schema.Union([ServerNotification__CreditsSnapshot, Schema.Null])),\n  individualLimit: Schema.optionalKey(\n    Schema.Union([ServerNotification__SpendControlLimitSnapshot, Schema.Null]),\n  ),\n  limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  planType: Schema.optionalKey(Schema.Union([ServerNotification__PlanType, Schema.Null])),\n  primary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])),\n  rateLimitReachedType: Schema.optionalKey(\n    Schema.Union([ServerNotification__RateLimitReachedType, Schema.Null]),\n  ),\n  secondary: Schema.optionalKey(Schema.Union([ServerNotification__RateLimitWindow, Schema.Null])),\n  spendControlReached: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<ServerNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: ServerNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: ServerNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const ServerNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(ServerNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ServerNotification__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([ServerNotification__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__TextRange = {\n  readonly end: ServerNotification__TextPosition;\n  readonly start: ServerNotification__TextPosition;\n};\nexport const ServerNotification__TextRange = Schema.Struct({\n  end: ServerNotification__TextPosition,\n  start: ServerNotification__TextPosition,\n});\n\nexport type ServerNotification__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<ServerNotification__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const ServerNotification__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(ServerNotification__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ThreadGoal = {\n  readonly createdAt: number;\n  readonly objective: string;\n  readonly status: ServerNotification__ThreadGoalStatus;\n  readonly threadId: string;\n  readonly timeUsedSeconds: number;\n  readonly tokenBudget?: number | null;\n  readonly tokensUsed: number;\n  readonly updatedAt: number;\n};\nexport const ServerNotification__ThreadGoal = Schema.Struct({\n  createdAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  objective: Schema.String,\n  status: ServerNotification__ThreadGoalStatus,\n  threadId: Schema.String,\n  timeUsedSeconds: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  tokensUsed: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  updatedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type ServerNotification__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: ServerNotification__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: ServerNotification__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const ServerNotification__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(Schema.Union([ServerNotification__AgentPath, Schema.Null])),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: ServerNotification__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ThreadRealtimeOutputAudioDeltaNotification = {\n  readonly audio: ServerNotification__ThreadRealtimeAudioChunk;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadRealtimeOutputAudioDeltaNotification = Schema.Struct({\n  audio: ServerNotification__ThreadRealtimeAudioChunk,\n  threadId: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL - streamed output audio emitted by thread realtime.\" });\n\nexport type ServerNotification__ThreadTokenUsage = {\n  readonly last: ServerNotification__TokenUsageBreakdown;\n  readonly modelContextWindow?: number | null;\n  readonly total: ServerNotification__TokenUsageBreakdown;\n};\nexport const ServerNotification__ThreadTokenUsage = Schema.Struct({\n  last: ServerNotification__TokenUsageBreakdown,\n  modelContextWindow: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  total: ServerNotification__TokenUsageBreakdown,\n});\n\nexport type ServerNotification__TurnPlanStep = {\n  readonly status: ServerNotification__TurnPlanStepStatus;\n  readonly step: string;\n};\nexport const ServerNotification__TurnPlanStep = Schema.Struct({\n  status: ServerNotification__TurnPlanStepStatus,\n  step: Schema.String,\n});\n\nexport type ServerNotification__WindowsSandboxSetupCompletedNotification = {\n  readonly error?: string | null;\n  readonly mode: ServerNotification__WindowsSandboxSetupMode;\n  readonly success: boolean;\n};\nexport const ServerNotification__WindowsSandboxSetupCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  mode: ServerNotification__WindowsSandboxSetupMode,\n  success: Schema.Boolean,\n});\n\nexport type ServerRequest__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: ServerRequest__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const ServerRequest__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: ServerRequest__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__ChatgptAuthTokensRefreshParams = {\n  readonly previousAccountId?: string | null;\n  readonly reason: ServerRequest__ChatgptAuthTokensRefreshReason;\n};\nexport const ServerRequest__ChatgptAuthTokensRefreshParams = Schema.Struct({\n  previousAccountId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Workspace/account identifier that Codex was previously using.\\n\\nClients that manage multiple accounts/workspaces can use this as a hint to refresh the token for the correct workspace.\\n\\nThis may be `null` when the prior auth state did not include a workspace identifier (`chatgpt_account_id`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: ServerRequest__ChatgptAuthTokensRefreshReason,\n});\n\nexport type ServerRequest__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | { readonly kind: \"project_roots\"; readonly subpath?: ServerRequest__LegacyAppPathString | null }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: ServerRequest__LegacyAppPathString | null;\n    };\nexport const ServerRequest__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(Schema.Union([ServerRequest__LegacyAppPathString, Schema.Null])),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(Schema.Union([ServerRequest__LegacyAppPathString, Schema.Null])),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__McpElicitationBooleanSchema = {\n  readonly default?: boolean | null;\n  readonly description?: string | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationBooleanType;\n};\nexport const ServerRequest__McpElicitationBooleanSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationBooleanType,\n});\n\nexport type ServerRequest__McpElicitationTitledEnumItems = {\n  readonly anyOf: ReadonlyArray<ServerRequest__McpElicitationConstOption>;\n};\nexport const ServerRequest__McpElicitationTitledEnumItems = Schema.Struct({\n  anyOf: Schema.Array(ServerRequest__McpElicitationConstOption),\n});\n\nexport type ServerRequest__McpElicitationNumberSchema = {\n  readonly default?: number | null;\n  readonly description?: string | null;\n  readonly maximum?: number | null;\n  readonly minimum?: number | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationNumberType;\n};\nexport const ServerRequest__McpElicitationNumberSchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  maximum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  minimum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationNumberType,\n});\n\nexport type ServerRequest__McpElicitationLegacyTitledEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum: ReadonlyArray<string>;\n  readonly enumNames?: ReadonlyArray<string> | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationLegacyTitledEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  enum: Schema.Array(Schema.String),\n  enumNames: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__McpElicitationStringSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly format?: ServerRequest__McpElicitationStringFormat | null;\n  readonly maxLength?: number | null;\n  readonly minLength?: number | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationStringSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  format: Schema.optionalKey(\n    Schema.Union([ServerRequest__McpElicitationStringFormat, Schema.Null]),\n  ),\n  maxLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__McpElicitationTitledSingleSelectEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly oneOf: ReadonlyArray<ServerRequest__McpElicitationConstOption>;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationTitledSingleSelectEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  oneOf: Schema.Array(ServerRequest__McpElicitationConstOption),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__McpElicitationUntitledEnumItems = {\n  readonly enum: ReadonlyArray<string>;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationUntitledEnumItems = Schema.Struct({\n  enum: Schema.Array(Schema.String),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__McpElicitationUntitledSingleSelectEnumSchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum: ReadonlyArray<string>;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationStringType;\n};\nexport const ServerRequest__McpElicitationUntitledSingleSelectEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  enum: Schema.Array(Schema.String),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationStringType,\n});\n\nexport type ServerRequest__NetworkApprovalContext = {\n  readonly host: string;\n  readonly protocol: ServerRequest__NetworkApprovalProtocol;\n};\nexport const ServerRequest__NetworkApprovalContext = Schema.Struct({\n  host: Schema.String,\n  protocol: ServerRequest__NetworkApprovalProtocol,\n});\n\nexport type ServerRequest__NetworkPolicyAmendment = {\n  readonly action: ServerRequest__NetworkPolicyRuleAction;\n  readonly host: string;\n};\nexport const ServerRequest__NetworkPolicyAmendment = Schema.Struct({\n  action: ServerRequest__NetworkPolicyRuleAction,\n  host: Schema.String,\n});\n\nexport type ServerRequest__ApplyPatchApprovalParams = {\n  readonly callId: string;\n  readonly conversationId: ServerRequest__ThreadId;\n  readonly fileChanges: { readonly [x: string]: ServerRequest__FileChange };\n  readonly grantRoot?: string | null;\n  readonly reason?: string | null;\n};\nexport const ServerRequest__ApplyPatchApprovalParams = Schema.Struct({\n  callId: Schema.String.annotate({\n    description:\n      \"Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].\",\n  }),\n  conversationId: ServerRequest__ThreadId,\n  fileChanges: Schema.Record(Schema.String, ServerRequest__FileChange),\n  grantRoot: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for extra write access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerRequest__ExecCommandApprovalParams = {\n  readonly approvalId?: string | null;\n  readonly callId: string;\n  readonly command: ReadonlyArray<string>;\n  readonly conversationId: ServerRequest__ThreadId;\n  readonly cwd: string;\n  readonly parsedCmd: ReadonlyArray<ServerRequest__ParsedCommand>;\n  readonly reason?: string | null;\n};\nexport const ServerRequest__ExecCommandApprovalParams = Schema.Struct({\n  approvalId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Identifier for this specific approval callback.\" }),\n      Schema.Null,\n    ]),\n  ),\n  callId: Schema.String.annotate({\n    description:\n      \"Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].\",\n  }),\n  command: Schema.Array(Schema.String),\n  conversationId: ServerRequest__ThreadId,\n  cwd: Schema.String,\n  parsedCmd: Schema.Array(ServerRequest__ParsedCommand),\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerRequest__ToolRequestUserInputQuestion = {\n  readonly header: string;\n  readonly id: string;\n  readonly isOther?: boolean;\n  readonly isSecret?: boolean;\n  readonly options?: ReadonlyArray<ServerRequest__ToolRequestUserInputOption> | null;\n  readonly question: string;\n};\nexport const ServerRequest__ToolRequestUserInputQuestion = Schema.Struct({\n  header: Schema.String,\n  id: Schema.String,\n  isOther: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isSecret: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  options: Schema.optionalKey(\n    Schema.Union([Schema.Array(ServerRequest__ToolRequestUserInputOption), Schema.Null]),\n  ),\n  question: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL. Represents one request_user_input question and its required options.\",\n});\n\nexport type ToolRequestUserInputParams__ToolRequestUserInputQuestion = {\n  readonly header: string;\n  readonly id: string;\n  readonly isOther?: boolean;\n  readonly isSecret?: boolean;\n  readonly options?: ReadonlyArray<ToolRequestUserInputParams__ToolRequestUserInputOption> | null;\n  readonly question: string;\n};\nexport const ToolRequestUserInputParams__ToolRequestUserInputQuestion = Schema.Struct({\n  header: Schema.String,\n  id: Schema.String,\n  isOther: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isSecret: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  options: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ToolRequestUserInputParams__ToolRequestUserInputOption),\n      Schema.Null,\n    ]),\n  ),\n  question: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL. Represents one request_user_input question and its required options.\",\n});\n\nexport type V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = {\n  readonly credits?: V2AccountRateLimitsUpdatedNotification__CreditsSnapshot | null;\n  readonly individualLimit?: V2AccountRateLimitsUpdatedNotification__SpendControlLimitSnapshot | null;\n  readonly limitId?: string | null;\n  readonly limitName?: string | null;\n  readonly planType?: V2AccountRateLimitsUpdatedNotification__PlanType | null;\n  readonly primary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null;\n  readonly rateLimitReachedType?: V2AccountRateLimitsUpdatedNotification__RateLimitReachedType | null;\n  readonly secondary?: V2AccountRateLimitsUpdatedNotification__RateLimitWindow | null;\n  readonly spendControlReached?: boolean | null;\n};\nexport const V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot = Schema.Struct({\n  credits: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__CreditsSnapshot, Schema.Null]),\n  ),\n  individualLimit: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__SpendControlLimitSnapshot, Schema.Null]),\n  ),\n  limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  planType: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__PlanType, Schema.Null]),\n  ),\n  primary: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]),\n  ),\n  rateLimitReachedType: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitReachedType, Schema.Null]),\n  ),\n  secondary: Schema.optionalKey(\n    Schema.Union([V2AccountRateLimitsUpdatedNotification__RateLimitWindow, Schema.Null]),\n  ),\n  spendControlReached: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2AppListUpdatedNotification__AppMetadata = {\n  readonly categories?: ReadonlyArray<string> | null;\n  readonly developer?: string | null;\n  readonly firstPartyRequiresInstall?: boolean | null;\n  readonly firstPartyType?: string | null;\n  readonly review?: V2AppListUpdatedNotification__AppReview | null;\n  readonly screenshots?: ReadonlyArray<V2AppListUpdatedNotification__AppScreenshot> | null;\n  readonly seoDescription?: string | null;\n  readonly showInComposerWhenUnlinked?: boolean | null;\n  readonly subCategories?: ReadonlyArray<string> | null;\n  readonly version?: string | null;\n  readonly versionId?: string | null;\n  readonly versionNotes?: string | null;\n};\nexport const V2AppListUpdatedNotification__AppMetadata = Schema.Struct({\n  categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  review: Schema.optionalKey(Schema.Union([V2AppListUpdatedNotification__AppReview, Schema.Null])),\n  screenshots: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2AppListUpdatedNotification__AppScreenshot), Schema.Null]),\n  ),\n  seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2AppsListResponse__AppMetadata = {\n  readonly categories?: ReadonlyArray<string> | null;\n  readonly developer?: string | null;\n  readonly firstPartyRequiresInstall?: boolean | null;\n  readonly firstPartyType?: string | null;\n  readonly review?: V2AppsListResponse__AppReview | null;\n  readonly screenshots?: ReadonlyArray<V2AppsListResponse__AppScreenshot> | null;\n  readonly seoDescription?: string | null;\n  readonly showInComposerWhenUnlinked?: boolean | null;\n  readonly subCategories?: ReadonlyArray<string> | null;\n  readonly version?: string | null;\n  readonly versionId?: string | null;\n  readonly versionNotes?: string | null;\n};\nexport const V2AppsListResponse__AppMetadata = Schema.Struct({\n  categories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  developer: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  firstPartyRequiresInstall: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  firstPartyType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  review: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppReview, Schema.Null])),\n  screenshots: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2AppsListResponse__AppScreenshot), Schema.Null]),\n  ),\n  seoDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  showInComposerWhenUnlinked: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  subCategories: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  version: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  versionNotes: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2AppsReadResponse__ConnectorMetadata = {\n  readonly description?: string | null;\n  readonly iconUrl?: string | null;\n  readonly id: string;\n  readonly name: string;\n  readonly toolSummaries?: ReadonlyArray<V2AppsReadResponse__AppToolSummary> | null;\n};\nexport const V2AppsReadResponse__ConnectorMetadata = Schema.Struct({\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  id: Schema.String,\n  name: Schema.String,\n  toolSummaries: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2AppsReadResponse__AppToolSummary), Schema.Null]),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - metadata returned by app/read.\" });\n\nexport type V2CommandExecParams__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2CommandExecParams__AbsolutePathBuf>;\n    };\nexport const V2CommandExecParams__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2CommandExecParams__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigBatchWriteParams__ConfigEdit = {\n  readonly keyPath: string;\n  readonly mergeStrategy: V2ConfigBatchWriteParams__MergeStrategy;\n  readonly value: unknown;\n};\nexport const V2ConfigBatchWriteParams__ConfigEdit = Schema.Struct({\n  keyPath: Schema.String,\n  mergeStrategy: V2ConfigBatchWriteParams__MergeStrategy,\n  value: Schema.Unknown,\n});\n\nexport type V2ConfigReadResponse__ConfigLayerSource =\n  | { readonly domain: string; readonly key: string; readonly type: \"mdm\" }\n  | { readonly file: string; readonly type: \"system\" }\n  | { readonly id: string; readonly name: string; readonly type: \"enterpriseManaged\" }\n  | { readonly file: string; readonly profile?: string | null; readonly type: \"user\" }\n  | { readonly dotCodexFolder: V2ConfigReadResponse__AbsolutePathBuf; readonly type: \"project\" }\n  | { readonly type: \"sessionFlags\" }\n  | {\n      readonly file: V2ConfigReadResponse__AbsolutePathBuf;\n      readonly type: \"legacyManagedConfigTomlFromFile\";\n    }\n  | { readonly type: \"legacyManagedConfigTomlFromMdm\" };\nexport const V2ConfigReadResponse__ConfigLayerSource = Schema.Union(\n  [\n    Schema.Struct({\n      domain: Schema.String,\n      key: Schema.String,\n      type: Schema.Literal(\"mdm\").annotate({ title: \"MdmConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"MdmConfigLayerSource\",\n      description: \"Managed preferences layer delivered by MDM (macOS only).\",\n    }),\n    Schema.Struct({\n      file: Schema.String.annotate({\n        description:\n          \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n      }),\n      type: Schema.Literal(\"system\").annotate({ title: \"SystemConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"SystemConfigLayerSource\",\n      description: \"Managed config layer from a file (usually `managed_config.toml`).\",\n    }),\n    Schema.Struct({\n      id: Schema.String.annotate({ description: \"Stable identifier for the delivered layer.\" }),\n      name: Schema.String.annotate({\n        description:\n          \"Admin-facing name for the delivered layer. This is surfaced in diagnostics so users know which cloud layer needs administrator attention.\",\n      }),\n      type: Schema.Literal(\"enterpriseManaged\").annotate({\n        title: \"EnterpriseManagedConfigLayerSourceType\",\n      }),\n    }).annotate({\n      title: \"EnterpriseManagedConfigLayerSource\",\n      description: \"Enterprise-managed config layer delivered by the cloud config bundle.\",\n    }),\n    Schema.Struct({\n      file: Schema.String.annotate({\n        description:\n          \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n      }),\n      profile: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Name of the selected profile-v2 config layered on top of the base user config, when this layer represents one.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"user\").annotate({ title: \"UserConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"UserConfigLayerSource\",\n      description:\n        \"User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory\",\n    }),\n    Schema.Struct({\n      dotCodexFolder: V2ConfigReadResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"project\").annotate({ title: \"ProjectConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"ProjectConfigLayerSource\",\n      description:\n        \"Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"sessionFlags\").annotate({ title: \"SessionFlagsConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"SessionFlagsConfigLayerSource\",\n      description: \"Session-layer overrides supplied via `-c`/`--config`.\",\n    }),\n    Schema.Struct({\n      file: V2ConfigReadResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"legacyManagedConfigTomlFromFile\").annotate({\n        title: \"LegacyManagedConfigTomlFromFileConfigLayerSourceType\",\n      }),\n    }).annotate({\n      title: \"LegacyManagedConfigTomlFromFileConfigLayerSource\",\n      description:\n        '`managed_config.toml` was designed to be a config that was loaded as the last layer on top of everything else. This scheme did not quite work out as intended, but we keep this variant as a \"best effort\" while we phase out `managed_config.toml` in favor of `requirements.toml`.',\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"legacyManagedConfigTomlFromMdm\").annotate({\n        title: \"LegacyManagedConfigTomlFromMdmConfigLayerSourceType\",\n      }),\n    }).annotate({ title: \"LegacyManagedConfigTomlFromMdmConfigLayerSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ConfigReadResponse__AppsDefaultConfig = {\n  readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null;\n  readonly default_tools_approval_mode?: V2ConfigReadResponse__AppToolApproval | null;\n  readonly destructive_enabled?: boolean;\n  readonly enabled?: boolean;\n  readonly open_world_enabled?: boolean;\n};\nexport const V2ConfigReadResponse__AppsDefaultConfig = Schema.Struct({\n  approvals_reviewer: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]),\n  ),\n  default_tools_approval_mode: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]),\n  ),\n  destructive_enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),\n  enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),\n  open_world_enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),\n});\n\nexport type V2ConfigReadResponse__WebSearchToolConfig = {\n  readonly allowed_domains?: ReadonlyArray<string> | null;\n  readonly context_size?: V2ConfigReadResponse__WebSearchContextSize | null;\n  readonly location?: V2ConfigReadResponse__WebSearchLocation | null;\n};\nexport const V2ConfigReadResponse__WebSearchToolConfig = Schema.Struct({\n  allowed_domains: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  context_size: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__WebSearchContextSize, Schema.Null]),\n  ),\n  location: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__WebSearchLocation, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup = {\n  readonly hooks: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookHandler>;\n  readonly matcher?: string | null;\n};\nexport const V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup = Schema.Struct({\n  hooks: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookHandler),\n  matcher: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ConfigRequirementsReadResponse__NewThreadModelDefaults = {\n  readonly model?: string | null;\n  readonly modelReasoningEffort?: V2ConfigRequirementsReadResponse__ReasoningEffort | null;\n  readonly serviceTier?: string | null;\n};\nexport const V2ConfigRequirementsReadResponse__NewThreadModelDefaults = Schema.Struct({\n  model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  modelReasoningEffort: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ReasoningEffort, Schema.Null]),\n  ),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ConfigWarningNotification__TextRange = {\n  readonly end: V2ConfigWarningNotification__TextPosition;\n  readonly start: V2ConfigWarningNotification__TextPosition;\n};\nexport const V2ConfigWarningNotification__TextRange = Schema.Struct({\n  end: V2ConfigWarningNotification__TextPosition,\n  start: V2ConfigWarningNotification__TextPosition,\n});\n\nexport type V2ConfigWriteResponse__ConfigLayerSource =\n  | { readonly domain: string; readonly key: string; readonly type: \"mdm\" }\n  | { readonly file: string; readonly type: \"system\" }\n  | { readonly id: string; readonly name: string; readonly type: \"enterpriseManaged\" }\n  | { readonly file: string; readonly profile?: string | null; readonly type: \"user\" }\n  | { readonly dotCodexFolder: V2ConfigWriteResponse__AbsolutePathBuf; readonly type: \"project\" }\n  | { readonly type: \"sessionFlags\" }\n  | {\n      readonly file: V2ConfigWriteResponse__AbsolutePathBuf;\n      readonly type: \"legacyManagedConfigTomlFromFile\";\n    }\n  | { readonly type: \"legacyManagedConfigTomlFromMdm\" };\nexport const V2ConfigWriteResponse__ConfigLayerSource = Schema.Union(\n  [\n    Schema.Struct({\n      domain: Schema.String,\n      key: Schema.String,\n      type: Schema.Literal(\"mdm\").annotate({ title: \"MdmConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"MdmConfigLayerSource\",\n      description: \"Managed preferences layer delivered by MDM (macOS only).\",\n    }),\n    Schema.Struct({\n      file: Schema.String.annotate({\n        description:\n          \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n      }),\n      type: Schema.Literal(\"system\").annotate({ title: \"SystemConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"SystemConfigLayerSource\",\n      description: \"Managed config layer from a file (usually `managed_config.toml`).\",\n    }),\n    Schema.Struct({\n      id: Schema.String.annotate({ description: \"Stable identifier for the delivered layer.\" }),\n      name: Schema.String.annotate({\n        description:\n          \"Admin-facing name for the delivered layer. This is surfaced in diagnostics so users know which cloud layer needs administrator attention.\",\n      }),\n      type: Schema.Literal(\"enterpriseManaged\").annotate({\n        title: \"EnterpriseManagedConfigLayerSourceType\",\n      }),\n    }).annotate({\n      title: \"EnterpriseManagedConfigLayerSource\",\n      description: \"Enterprise-managed config layer delivered by the cloud config bundle.\",\n    }),\n    Schema.Struct({\n      file: Schema.String.annotate({\n        description:\n          \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n      }),\n      profile: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Name of the selected profile-v2 config layered on top of the base user config, when this layer represents one.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"user\").annotate({ title: \"UserConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"UserConfigLayerSource\",\n      description:\n        \"User config layer from $CODEX_HOME/config.toml. This layer is special in that it is expected to be: - writable by the user - generally outside the workspace directory\",\n    }),\n    Schema.Struct({\n      dotCodexFolder: V2ConfigWriteResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"project\").annotate({ title: \"ProjectConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"ProjectConfigLayerSource\",\n      description:\n        \"Path to a .codex/ folder within a project. There could be multiple of these between `cwd` and the project/repo root.\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"sessionFlags\").annotate({ title: \"SessionFlagsConfigLayerSourceType\" }),\n    }).annotate({\n      title: \"SessionFlagsConfigLayerSource\",\n      description: \"Session-layer overrides supplied via `-c`/`--config`.\",\n    }),\n    Schema.Struct({\n      file: V2ConfigWriteResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"legacyManagedConfigTomlFromFile\").annotate({\n        title: \"LegacyManagedConfigTomlFromFileConfigLayerSourceType\",\n      }),\n    }).annotate({\n      title: \"LegacyManagedConfigTomlFromFileConfigLayerSource\",\n      description:\n        '`managed_config.toml` was designed to be a config that was loaded as the last layer on top of everything else. This scheme did not quite work out as intended, but we keep this variant as a \"best effort\" while we phase out `managed_config.toml` in favor of `requirements.toml`.',\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"legacyManagedConfigTomlFromMdm\").annotate({\n        title: \"LegacyManagedConfigTomlFromMdmConfigLayerSourceType\",\n      }),\n    }).annotate({ title: \"LegacyManagedConfigTomlFromMdmConfigLayerSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ErrorNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ErrorNotification__NonSteerableTurnKind;\n      };\n    };\nexport const V2ErrorNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ErrorNotification__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ExternalAgentConfigDetectResponse__MigrationDetails = {\n  readonly commands?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__CommandMigration>;\n  readonly hooks?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__HookMigration>;\n  readonly mcpServers?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__McpServerMigration>;\n  readonly memory?: ReadonlyArray<string>;\n  readonly plugins?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__PluginsMigration>;\n  readonly sessions?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__SessionMigration>;\n  readonly skills?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__SkillMigration>;\n  readonly subagents?: ReadonlyArray<V2ExternalAgentConfigDetectResponse__SubagentMigration>;\n};\nexport const V2ExternalAgentConfigDetectResponse__MigrationDetails = Schema.Struct({\n  commands: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__CommandMigration).annotate({ default: [] }),\n  ),\n  hooks: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__HookMigration).annotate({ default: [] }),\n  ),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__McpServerMigration).annotate({ default: [] }),\n  ),\n  memory: Schema.optionalKey(Schema.Array(Schema.String)),\n  plugins: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__PluginsMigration).annotate({ default: [] }),\n  ),\n  sessions: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__SessionMigration).annotate({ default: [] }),\n  ),\n  skills: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__SkillMigration).annotate({ default: [] }),\n  ),\n  subagents: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigDetectResponse__SubagentMigration).annotate({ default: [] }),\n  ),\n});\n\nexport type V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeFailure =\n  {\n    readonly cwd?: string | null;\n    readonly errorType?: string | null;\n    readonly failureStage: string;\n    readonly itemType: V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType;\n    readonly message: string;\n    readonly source?: string | null;\n    readonly subErrorType?: string | null;\n  };\nexport const V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeFailure =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    errorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    failureStage: Schema.String,\n    itemType:\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType,\n    message: Schema.String,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    subErrorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeSuccess =\n  {\n    readonly cwd?: string | null;\n    readonly itemType: V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType;\n    readonly source?: string | null;\n    readonly target?: string | null;\n  };\nexport const V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeSuccess =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    itemType:\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    target: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeFailure =\n  {\n    readonly cwd?: string | null;\n    readonly errorType?: string | null;\n    readonly failureStage: string;\n    readonly itemType: V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType;\n    readonly message: string;\n    readonly source?: string | null;\n    readonly subErrorType?: string | null;\n  };\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeFailure =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    errorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    failureStage: Schema.String,\n    itemType:\n      V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType,\n    message: Schema.String,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    subErrorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeSuccess =\n  {\n    readonly cwd?: string | null;\n    readonly itemType: V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType;\n    readonly source?: string | null;\n    readonly target?: string | null;\n  };\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeSuccess =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    itemType:\n      V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigMigrationItemType,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    target: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorCandidate =\n  {\n    readonly name: string;\n    readonly sessionCount: number;\n    readonly source: V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorSource;\n  };\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorCandidate =\n  Schema.Struct({\n    name: Schema.String,\n    sessionCount: Schema.Number.annotate({ format: \"uint32\" })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    source: V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorSource,\n  });\n\nexport type V2ExternalAgentConfigImportParams__MigrationDetails = {\n  readonly commands?: ReadonlyArray<V2ExternalAgentConfigImportParams__CommandMigration>;\n  readonly hooks?: ReadonlyArray<V2ExternalAgentConfigImportParams__HookMigration>;\n  readonly mcpServers?: ReadonlyArray<V2ExternalAgentConfigImportParams__McpServerMigration>;\n  readonly memory?: ReadonlyArray<string>;\n  readonly plugins?: ReadonlyArray<V2ExternalAgentConfigImportParams__PluginsMigration>;\n  readonly sessions?: ReadonlyArray<V2ExternalAgentConfigImportParams__SessionMigration>;\n  readonly skills?: ReadonlyArray<V2ExternalAgentConfigImportParams__SkillMigration>;\n  readonly subagents?: ReadonlyArray<V2ExternalAgentConfigImportParams__SubagentMigration>;\n};\nexport const V2ExternalAgentConfigImportParams__MigrationDetails = Schema.Struct({\n  commands: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__CommandMigration).annotate({ default: [] }),\n  ),\n  hooks: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__HookMigration).annotate({ default: [] }),\n  ),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__McpServerMigration).annotate({ default: [] }),\n  ),\n  memory: Schema.optionalKey(Schema.Array(Schema.String)),\n  plugins: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__PluginsMigration).annotate({ default: [] }),\n  ),\n  sessions: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__SessionMigration).annotate({ default: [] }),\n  ),\n  skills: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__SkillMigration).annotate({ default: [] }),\n  ),\n  subagents: Schema.optionalKey(\n    Schema.Array(V2ExternalAgentConfigImportParams__SubagentMigration).annotate({ default: [] }),\n  ),\n});\n\nexport type V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeFailure =\n  {\n    readonly cwd?: string | null;\n    readonly errorType?: string | null;\n    readonly failureStage: string;\n    readonly itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType;\n    readonly message: string;\n    readonly source?: string | null;\n    readonly subErrorType?: string | null;\n  };\nexport const V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeFailure =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    errorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    failureStage: Schema.String,\n    itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType,\n    message: Schema.String,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    subErrorType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeSuccess =\n  {\n    readonly cwd?: string | null;\n    readonly itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType;\n    readonly source?: string | null;\n    readonly target?: string | null;\n  };\nexport const V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeSuccess =\n  Schema.Struct({\n    cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType,\n    source: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    target: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  });\n\nexport type V2FileChangePatchUpdatedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2FileChangePatchUpdatedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2FileChangePatchUpdatedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2FileChangePatchUpdatedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2GetAccountRateLimitsResponse__RateLimitResetCredit = {\n  readonly description?: string | null;\n  readonly expiresAt?: number | null;\n  readonly grantedAt: number;\n  readonly id: string;\n  readonly resetType: V2GetAccountRateLimitsResponse__RateLimitResetType;\n  readonly status: V2GetAccountRateLimitsResponse__RateLimitResetCreditStatus;\n  readonly title?: string | null;\n};\nexport const V2GetAccountRateLimitsResponse__RateLimitResetCredit = Schema.Struct({\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Backend-provided display description for this credit, or `null` when unavailable.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  expiresAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Unix timestamp in seconds when the credit expires, or `null` if it does not expire.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  grantedAt: Schema.Number.annotate({\n    description: \"Unix timestamp in seconds when the credit was granted.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  id: Schema.String.annotate({ description: \"Opaque backend identifier for this reset credit.\" }),\n  resetType: V2GetAccountRateLimitsResponse__RateLimitResetType,\n  status: V2GetAccountRateLimitsResponse__RateLimitResetCreditStatus,\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Backend-provided display title for this credit, or `null` when unavailable.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2GetAccountRateLimitsResponse__RateLimitSnapshot = {\n  readonly credits?: V2GetAccountRateLimitsResponse__CreditsSnapshot | null;\n  readonly individualLimit?: V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot | null;\n  readonly limitId?: string | null;\n  readonly limitName?: string | null;\n  readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null;\n  readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;\n  readonly rateLimitReachedType?: V2GetAccountRateLimitsResponse__RateLimitReachedType | null;\n  readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;\n  readonly spendControlReached?: boolean | null;\n};\nexport const V2GetAccountRateLimitsResponse__RateLimitSnapshot = Schema.Struct({\n  credits: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__CreditsSnapshot, Schema.Null]),\n  ),\n  individualLimit: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot, Schema.Null]),\n  ),\n  limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  planType: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__PlanType, Schema.Null]),\n  ),\n  primary: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),\n  ),\n  rateLimitReachedType: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__RateLimitReachedType, Schema.Null]),\n  ),\n  secondary: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),\n  ),\n  spendControlReached: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2GetAccountResponse__Account =\n  | { readonly type: \"apiKey\" }\n  | {\n      readonly email: string | null;\n      readonly planType: V2GetAccountResponse__PlanType;\n      readonly type: \"chatgpt\";\n    }\n  | { readonly type: \"amazonBedrock\"; readonly usesCodexManagedCredentials?: boolean };\nexport const V2GetAccountResponse__Account = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"apiKey\").annotate({ title: \"ApiKeyAccountType\" }),\n    }).annotate({ title: \"ApiKeyAccount\" }),\n    Schema.Struct({\n      email: Schema.Union([Schema.String, Schema.Null]),\n      planType: V2GetAccountResponse__PlanType,\n      type: Schema.Literal(\"chatgpt\").annotate({ title: \"ChatgptAccountType\" }),\n    }).annotate({ title: \"ChatgptAccount\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"amazonBedrock\").annotate({ title: \"AmazonBedrockAccountType\" }),\n      usesCodexManagedCredentials: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n    }).annotate({ title: \"AmazonBedrockAccount\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2GetWorkspaceMessagesResponse__WorkspaceMessage = {\n  readonly archivedAt?: number | null;\n  readonly createdAt?: number | null;\n  readonly messageBody: string;\n  readonly messageId: string;\n  readonly messageType: V2GetWorkspaceMessagesResponse__WorkspaceMessageType;\n};\nexport const V2GetWorkspaceMessagesResponse__WorkspaceMessage = Schema.Struct({\n  archivedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the message was archived.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  createdAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the message was created.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  messageBody: Schema.String,\n  messageId: Schema.String,\n  messageType: V2GetWorkspaceMessagesResponse__WorkspaceMessageType,\n});\n\nexport type V2HookCompletedNotification__HookOutputEntry = {\n  readonly kind: V2HookCompletedNotification__HookOutputEntryKind;\n  readonly text: string;\n};\nexport const V2HookCompletedNotification__HookOutputEntry = Schema.Struct({\n  kind: V2HookCompletedNotification__HookOutputEntryKind,\n  text: Schema.String,\n});\n\nexport type V2HooksListResponse__HookMetadata = {\n  readonly command?: string | null;\n  readonly currentHash: string;\n  readonly displayOrder: number;\n  readonly enabled: boolean;\n  readonly eventName: V2HooksListResponse__HookEventName;\n  readonly handlerType: V2HooksListResponse__HookHandlerType;\n  readonly isManaged: boolean;\n  readonly key: string;\n  readonly matcher?: string | null;\n  readonly pluginId?: string | null;\n  readonly source: V2HooksListResponse__HookSource;\n  readonly sourcePath: V2HooksListResponse__AbsolutePathBuf;\n  readonly statusMessage?: string | null;\n  readonly timeoutSec: number;\n  readonly trustStatus: V2HooksListResponse__HookTrustStatus;\n};\nexport const V2HooksListResponse__HookMetadata = Schema.Struct({\n  command: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  currentHash: Schema.String,\n  displayOrder: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  enabled: Schema.Boolean,\n  eventName: V2HooksListResponse__HookEventName,\n  handlerType: V2HooksListResponse__HookHandlerType,\n  isManaged: Schema.Boolean,\n  key: Schema.String,\n  matcher: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  source: V2HooksListResponse__HookSource,\n  sourcePath: V2HooksListResponse__AbsolutePathBuf,\n  statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  timeoutSec: Schema.Number.annotate({ format: \"uint64\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  trustStatus: V2HooksListResponse__HookTrustStatus,\n});\n\nexport type V2HookStartedNotification__HookOutputEntry = {\n  readonly kind: V2HookStartedNotification__HookOutputEntryKind;\n  readonly text: string;\n};\nexport const V2HookStartedNotification__HookOutputEntry = Schema.Struct({\n  kind: V2HookStartedNotification__HookOutputEntryKind,\n  text: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ItemCompletedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ItemCompletedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ItemCompletedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemCompletedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ItemCompletedNotification__CollabAgentStatus;\n};\nexport const V2ItemCompletedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ItemCompletedNotification__CollabAgentStatus,\n});\n\nexport type V2ItemCompletedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ItemCompletedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ItemCompletedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ItemCompletedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ItemCompletedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ItemCompletedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ItemCompletedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ItemCompletedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ItemCompletedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ItemCompletedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ItemCompletedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ItemCompletedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ItemCompletedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ItemCompletedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview = {\n  readonly rationale?: string | null;\n  readonly riskLevel?: V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel | null;\n  readonly status: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus;\n  readonly userAuthorization?: V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization | null;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview =\n  Schema.Struct({\n    rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    riskLevel: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewCompletedNotification__GuardianRiskLevel,\n        Schema.Null,\n      ]),\n    ),\n    status: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewStatus,\n    userAuthorization: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewCompletedNotification__GuardianUserAuthorization,\n        Schema.Null,\n      ]),\n    ),\n  }).annotate({\n    description:\n      \"[UNSTABLE] Temporary approval auto-review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString | null;\n    };\nexport const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath =\n  Schema.Union(\n    [\n      Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n        title: \"RootFileSystemSpecialPath\",\n      }),\n      Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n        title: \"MinimalFileSystemSpecialPath\",\n      }),\n      Schema.Struct({\n        kind: Schema.Literal(\"project_roots\"),\n        subpath: Schema.optionalKey(\n          Schema.Union([\n            V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n      Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n        title: \"TmpdirFileSystemSpecialPath\",\n      }),\n      Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n        title: \"SlashTmpFileSystemSpecialPath\",\n      }),\n      Schema.Struct({\n        kind: Schema.Literal(\"unknown\"),\n        path: Schema.String,\n        subpath: Schema.optionalKey(\n          Schema.Union([\n            V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n            Schema.Null,\n          ]),\n        ),\n      }),\n    ],\n    { mode: \"oneOf\" },\n  );\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview = {\n  readonly rationale?: string | null;\n  readonly riskLevel?: V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel | null;\n  readonly status: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus;\n  readonly userAuthorization?: V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization | null;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview =\n  Schema.Struct({\n    rationale: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    riskLevel: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewStartedNotification__GuardianRiskLevel,\n        Schema.Null,\n      ]),\n    ),\n    status: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewStatus,\n    userAuthorization: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewStartedNotification__GuardianUserAuthorization,\n        Schema.Null,\n      ]),\n    ),\n  }).annotate({\n    description:\n      \"[UNSTABLE] Temporary approval auto-review payload used by `item/autoApprovalReview/*` notifications. This shape is expected to change soon.\",\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath =\n  | { readonly kind: \"root\" }\n  | { readonly kind: \"minimal\" }\n  | {\n      readonly kind: \"project_roots\";\n      readonly subpath?: V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString | null;\n    }\n  | { readonly kind: \"tmpdir\" }\n  | { readonly kind: \"slash_tmp\" }\n  | {\n      readonly kind: \"unknown\";\n      readonly path: string;\n      readonly subpath?: V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString | null;\n    };\nexport const V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath = Schema.Union(\n  [\n    Schema.Struct({ kind: Schema.Literal(\"root\") }).annotate({\n      title: \"RootFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"minimal\") }).annotate({\n      title: \"MinimalFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"project_roots\"),\n      subpath: Schema.optionalKey(\n        Schema.Union([\n          V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString,\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"KindFileSystemSpecialPath\" }),\n    Schema.Struct({ kind: Schema.Literal(\"tmpdir\") }).annotate({\n      title: \"TmpdirFileSystemSpecialPath\",\n    }),\n    Schema.Struct({ kind: Schema.Literal(\"slash_tmp\") }).annotate({\n      title: \"SlashTmpFileSystemSpecialPath\",\n    }),\n    Schema.Struct({\n      kind: Schema.Literal(\"unknown\"),\n      path: Schema.String,\n      subpath: Schema.optionalKey(\n        Schema.Union([\n          V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString,\n          Schema.Null,\n        ]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ItemStartedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ItemStartedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ItemStartedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ItemStartedNotification__CollabAgentStatus;\n};\nexport const V2ItemStartedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ItemStartedNotification__CollabAgentStatus,\n});\n\nexport type V2ItemStartedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ItemStartedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ItemStartedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ItemStartedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ItemStartedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ItemStartedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ItemStartedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ItemStartedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ItemStartedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ItemStartedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ItemStartedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ItemStartedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ItemStartedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ItemStartedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ListMcpServerStatusResponse__McpServerStatus = {\n  readonly authStatus: V2ListMcpServerStatusResponse__McpAuthStatus;\n  readonly name: string;\n  readonly resourceTemplates: ReadonlyArray<V2ListMcpServerStatusResponse__ResourceTemplate>;\n  readonly resources: ReadonlyArray<V2ListMcpServerStatusResponse__Resource>;\n  readonly serverInfo?: V2ListMcpServerStatusResponse__McpServerInfo | null;\n  readonly tools: { readonly [x: string]: V2ListMcpServerStatusResponse__Tool };\n};\nexport const V2ListMcpServerStatusResponse__McpServerStatus = Schema.Struct({\n  authStatus: V2ListMcpServerStatusResponse__McpAuthStatus,\n  name: Schema.String,\n  resourceTemplates: Schema.Array(V2ListMcpServerStatusResponse__ResourceTemplate),\n  resources: Schema.Array(V2ListMcpServerStatusResponse__Resource),\n  serverInfo: Schema.optionalKey(\n    Schema.Union([V2ListMcpServerStatusResponse__McpServerInfo, Schema.Null]),\n  ),\n  tools: Schema.Record(Schema.String, V2ListMcpServerStatusResponse__Tool),\n});\n\nexport type V2ModelListResponse__ReasoningEffortOption = {\n  readonly description: string;\n  readonly reasoningEffort: V2ModelListResponse__ReasoningEffort;\n};\nexport const V2ModelListResponse__ReasoningEffortOption = Schema.Struct({\n  description: Schema.String,\n  reasoningEffort: V2ModelListResponse__ReasoningEffort,\n});\n\nexport type V2PluginInstalledResponse__MarketplaceLoadErrorInfo = {\n  readonly marketplacePath: V2PluginInstalledResponse__AbsolutePathBuf;\n  readonly message: string;\n};\nexport const V2PluginInstalledResponse__MarketplaceLoadErrorInfo = Schema.Struct({\n  marketplacePath: V2PluginInstalledResponse__AbsolutePathBuf,\n  message: Schema.String,\n});\n\nexport type V2PluginInstalledResponse__PluginInterface = {\n  readonly brandColor?: string | null;\n  readonly capabilities: ReadonlyArray<string>;\n  readonly category?: string | null;\n  readonly composerIcon?: V2PluginInstalledResponse__AbsolutePathBuf | null;\n  readonly composerIconUrl?: string | null;\n  readonly defaultPrompt?: ReadonlyArray<string> | null;\n  readonly developerName?: string | null;\n  readonly displayName?: string | null;\n  readonly logo?: V2PluginInstalledResponse__AbsolutePathBuf | null;\n  readonly logoDark?: V2PluginInstalledResponse__AbsolutePathBuf | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly longDescription?: string | null;\n  readonly privacyPolicyUrl?: string | null;\n  readonly screenshotUrls: ReadonlyArray<string>;\n  readonly screenshots: ReadonlyArray<V2PluginInstalledResponse__AbsolutePathBuf>;\n  readonly shortDescription?: string | null;\n  readonly termsOfServiceUrl?: string | null;\n  readonly websiteUrl?: string | null;\n};\nexport const V2PluginInstalledResponse__PluginInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  capabilities: Schema.Array(Schema.String),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  composerIcon: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local composer icon path, resolved from the installed plugin package.\",\n    }),\n  ),\n  composerIconUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote composer icon URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  defaultPrompt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logo: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoDark: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local dark-mode logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  logoUrlDark: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote dark-mode logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  screenshotUrls: Schema.Array(Schema.String).annotate({\n    description: \"Remote screenshot URLs from the plugin catalog.\",\n  }),\n  screenshots: Schema.Array(V2PluginInstalledResponse__AbsolutePathBuf).annotate({\n    description: \"Local screenshot paths, resolved from the installed plugin package.\",\n  }),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginInstalledResponse__PluginSource =\n  | { readonly path: V2PluginInstalledResponse__AbsolutePathBuf; readonly type: \"local\" }\n  | {\n      readonly path?: string | null;\n      readonly refName?: string | null;\n      readonly sha?: string | null;\n      readonly type: \"git\";\n      readonly url: string;\n    }\n  | {\n      readonly package: string;\n      readonly registry?: string | null;\n      readonly type: \"npm\";\n      readonly version?: string | null;\n    }\n  | { readonly type: \"remote\" };\nexport const V2PluginInstalledResponse__PluginSource = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2PluginInstalledResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"local\").annotate({ title: \"LocalPluginSourceType\" }),\n    }).annotate({ title: \"LocalPluginSource\" }),\n    Schema.Struct({\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"git\").annotate({ title: \"GitPluginSourceType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"GitPluginSource\" }),\n    Schema.Struct({\n      package: Schema.String,\n      registry: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional HTTPS registry URL. Authentication stays in the user's npm config.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"npm\").annotate({ title: \"NpmPluginSourceType\" }),\n      version: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional npm version or version range.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"NpmPluginSource\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"remote\").annotate({ title: \"RemotePluginSourceType\" }),\n    }).annotate({\n      title: \"RemotePluginSource\",\n      description:\n        \"The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginInstalledResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginInstalledResponse__PluginSharePrincipalType;\n  readonly role: V2PluginInstalledResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginInstalledResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginInstalledResponse__PluginSharePrincipalType,\n  role: V2PluginInstalledResponse__PluginSharePrincipalRole,\n});\n\nexport type V2PluginListResponse__MarketplaceLoadErrorInfo = {\n  readonly marketplacePath: V2PluginListResponse__AbsolutePathBuf;\n  readonly message: string;\n};\nexport const V2PluginListResponse__MarketplaceLoadErrorInfo = Schema.Struct({\n  marketplacePath: V2PluginListResponse__AbsolutePathBuf,\n  message: Schema.String,\n});\n\nexport type V2PluginListResponse__PluginInterface = {\n  readonly brandColor?: string | null;\n  readonly capabilities: ReadonlyArray<string>;\n  readonly category?: string | null;\n  readonly composerIcon?: V2PluginListResponse__AbsolutePathBuf | null;\n  readonly composerIconUrl?: string | null;\n  readonly defaultPrompt?: ReadonlyArray<string> | null;\n  readonly developerName?: string | null;\n  readonly displayName?: string | null;\n  readonly logo?: V2PluginListResponse__AbsolutePathBuf | null;\n  readonly logoDark?: V2PluginListResponse__AbsolutePathBuf | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly longDescription?: string | null;\n  readonly privacyPolicyUrl?: string | null;\n  readonly screenshotUrls: ReadonlyArray<string>;\n  readonly screenshots: ReadonlyArray<V2PluginListResponse__AbsolutePathBuf>;\n  readonly shortDescription?: string | null;\n  readonly termsOfServiceUrl?: string | null;\n  readonly websiteUrl?: string | null;\n};\nexport const V2PluginListResponse__PluginInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  capabilities: Schema.Array(Schema.String),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  composerIcon: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local composer icon path, resolved from the installed plugin package.\",\n    }),\n  ),\n  composerIconUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote composer icon URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  defaultPrompt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logo: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoDark: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local dark-mode logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  logoUrlDark: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote dark-mode logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  screenshotUrls: Schema.Array(Schema.String).annotate({\n    description: \"Remote screenshot URLs from the plugin catalog.\",\n  }),\n  screenshots: Schema.Array(V2PluginListResponse__AbsolutePathBuf).annotate({\n    description: \"Local screenshot paths, resolved from the installed plugin package.\",\n  }),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginListResponse__PluginSource =\n  | { readonly path: V2PluginListResponse__AbsolutePathBuf; readonly type: \"local\" }\n  | {\n      readonly path?: string | null;\n      readonly refName?: string | null;\n      readonly sha?: string | null;\n      readonly type: \"git\";\n      readonly url: string;\n    }\n  | {\n      readonly package: string;\n      readonly registry?: string | null;\n      readonly type: \"npm\";\n      readonly version?: string | null;\n    }\n  | { readonly type: \"remote\" };\nexport const V2PluginListResponse__PluginSource = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2PluginListResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"local\").annotate({ title: \"LocalPluginSourceType\" }),\n    }).annotate({ title: \"LocalPluginSource\" }),\n    Schema.Struct({\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"git\").annotate({ title: \"GitPluginSourceType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"GitPluginSource\" }),\n    Schema.Struct({\n      package: Schema.String,\n      registry: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional HTTPS registry URL. Authentication stays in the user's npm config.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"npm\").annotate({ title: \"NpmPluginSourceType\" }),\n      version: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional npm version or version range.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"NpmPluginSource\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"remote\").annotate({ title: \"RemotePluginSourceType\" }),\n    }).annotate({\n      title: \"RemotePluginSource\",\n      description:\n        \"The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginListResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginListResponse__PluginSharePrincipalType;\n  readonly role: V2PluginListResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginListResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginListResponse__PluginSharePrincipalType,\n  role: V2PluginListResponse__PluginSharePrincipalRole,\n});\n\nexport type V2PluginReadResponse__PluginInterface = {\n  readonly brandColor?: string | null;\n  readonly capabilities: ReadonlyArray<string>;\n  readonly category?: string | null;\n  readonly composerIcon?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly composerIconUrl?: string | null;\n  readonly defaultPrompt?: ReadonlyArray<string> | null;\n  readonly developerName?: string | null;\n  readonly displayName?: string | null;\n  readonly logo?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly logoDark?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly longDescription?: string | null;\n  readonly privacyPolicyUrl?: string | null;\n  readonly screenshotUrls: ReadonlyArray<string>;\n  readonly screenshots: ReadonlyArray<V2PluginReadResponse__AbsolutePathBuf>;\n  readonly shortDescription?: string | null;\n  readonly termsOfServiceUrl?: string | null;\n  readonly websiteUrl?: string | null;\n};\nexport const V2PluginReadResponse__PluginInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  capabilities: Schema.Array(Schema.String),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  composerIcon: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local composer icon path, resolved from the installed plugin package.\",\n    }),\n  ),\n  composerIconUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote composer icon URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  defaultPrompt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logo: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoDark: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local dark-mode logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  logoUrlDark: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote dark-mode logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  screenshotUrls: Schema.Array(Schema.String).annotate({\n    description: \"Remote screenshot URLs from the plugin catalog.\",\n  }),\n  screenshots: Schema.Array(V2PluginReadResponse__AbsolutePathBuf).annotate({\n    description: \"Local screenshot paths, resolved from the installed plugin package.\",\n  }),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__PluginSource =\n  | { readonly path: V2PluginReadResponse__AbsolutePathBuf; readonly type: \"local\" }\n  | {\n      readonly path?: string | null;\n      readonly refName?: string | null;\n      readonly sha?: string | null;\n      readonly type: \"git\";\n      readonly url: string;\n    }\n  | {\n      readonly package: string;\n      readonly registry?: string | null;\n      readonly type: \"npm\";\n      readonly version?: string | null;\n    }\n  | { readonly type: \"remote\" };\nexport const V2PluginReadResponse__PluginSource = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2PluginReadResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"local\").annotate({ title: \"LocalPluginSourceType\" }),\n    }).annotate({ title: \"LocalPluginSource\" }),\n    Schema.Struct({\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"git\").annotate({ title: \"GitPluginSourceType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"GitPluginSource\" }),\n    Schema.Struct({\n      package: Schema.String,\n      registry: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional HTTPS registry URL. Authentication stays in the user's npm config.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"npm\").annotate({ title: \"NpmPluginSourceType\" }),\n      version: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional npm version or version range.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"NpmPluginSource\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"remote\").annotate({ title: \"RemotePluginSourceType\" }),\n    }).annotate({\n      title: \"RemotePluginSource\",\n      description:\n        \"The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginReadResponse__SkillInterface = {\n  readonly brandColor?: string | null;\n  readonly defaultPrompt?: string | null;\n  readonly displayName?: string | null;\n  readonly iconLarge?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly iconSmall?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly shortDescription?: string | null;\n};\nexport const V2PluginReadResponse__SkillInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconLarge: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])),\n  iconSmall: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__AppTemplateSummary = {\n  readonly canonicalConnectorId?: string | null;\n  readonly category?: string | null;\n  readonly description?: string | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly materializedAppIds: ReadonlyArray<string>;\n  readonly name: string;\n  readonly reason?: V2PluginReadResponse__AppTemplateUnavailableReason | null;\n  readonly templateId: string;\n};\nexport const V2PluginReadResponse__AppTemplateSummary = Schema.Struct({\n  canonicalConnectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  materializedAppIds: Schema.Array(Schema.String),\n  name: Schema.String,\n  reason: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AppTemplateUnavailableReason, Schema.Null]),\n  ),\n  templateId: Schema.String,\n});\n\nexport type V2PluginReadResponse__PluginHookSummary = {\n  readonly eventName: V2PluginReadResponse__HookEventName;\n  readonly key: string;\n};\nexport const V2PluginReadResponse__PluginHookSummary = Schema.Struct({\n  eventName: V2PluginReadResponse__HookEventName,\n  key: Schema.String,\n});\n\nexport type V2PluginReadResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginReadResponse__PluginSharePrincipalType;\n  readonly role: V2PluginReadResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginReadResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginReadResponse__PluginSharePrincipalType,\n  role: V2PluginReadResponse__PluginSharePrincipalRole,\n});\n\nexport type V2PluginReadResponse__ScheduledTaskSchedule =\n  | {\n      readonly days?: ReadonlyArray<V2PluginReadResponse__ScheduledTaskWeekday> | null;\n      readonly intervalHours: number;\n      readonly type: \"hourly\";\n    }\n  | { readonly time: string; readonly type: \"daily\" }\n  | { readonly time: string; readonly type: \"weekdays\" }\n  | {\n      readonly days: ReadonlyArray<V2PluginReadResponse__ScheduledTaskWeekday>;\n      readonly time: string;\n      readonly type: \"weekly\";\n    };\nexport const V2PluginReadResponse__ScheduledTaskSchedule = Schema.Union(\n  [\n    Schema.Struct({\n      days: Schema.optionalKey(\n        Schema.Union([Schema.Array(V2PluginReadResponse__ScheduledTaskWeekday), Schema.Null]),\n      ),\n      intervalHours: Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      type: Schema.Literal(\"hourly\").annotate({ title: \"HourlyScheduledTaskScheduleType\" }),\n    }).annotate({ title: \"HourlyScheduledTaskSchedule\" }),\n    Schema.Struct({\n      time: Schema.String,\n      type: Schema.Literal(\"daily\").annotate({ title: \"DailyScheduledTaskScheduleType\" }),\n    }).annotate({ title: \"DailyScheduledTaskSchedule\" }),\n    Schema.Struct({\n      time: Schema.String,\n      type: Schema.Literal(\"weekdays\").annotate({ title: \"WeekdaysScheduledTaskScheduleType\" }),\n    }).annotate({ title: \"WeekdaysScheduledTaskSchedule\" }),\n    Schema.Struct({\n      days: Schema.Array(V2PluginReadResponse__ScheduledTaskWeekday),\n      time: Schema.String,\n      type: Schema.Literal(\"weekly\").annotate({ title: \"WeeklyScheduledTaskScheduleType\" }),\n    }).annotate({ title: \"WeeklyScheduledTaskSchedule\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginShareListResponse__PluginInterface = {\n  readonly brandColor?: string | null;\n  readonly capabilities: ReadonlyArray<string>;\n  readonly category?: string | null;\n  readonly composerIcon?: V2PluginShareListResponse__AbsolutePathBuf | null;\n  readonly composerIconUrl?: string | null;\n  readonly defaultPrompt?: ReadonlyArray<string> | null;\n  readonly developerName?: string | null;\n  readonly displayName?: string | null;\n  readonly logo?: V2PluginShareListResponse__AbsolutePathBuf | null;\n  readonly logoDark?: V2PluginShareListResponse__AbsolutePathBuf | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly longDescription?: string | null;\n  readonly privacyPolicyUrl?: string | null;\n  readonly screenshotUrls: ReadonlyArray<string>;\n  readonly screenshots: ReadonlyArray<V2PluginShareListResponse__AbsolutePathBuf>;\n  readonly shortDescription?: string | null;\n  readonly termsOfServiceUrl?: string | null;\n  readonly websiteUrl?: string | null;\n};\nexport const V2PluginShareListResponse__PluginInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  capabilities: Schema.Array(Schema.String),\n  category: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  composerIcon: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local composer icon path, resolved from the installed plugin package.\",\n    }),\n  ),\n  composerIconUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote composer icon URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  defaultPrompt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Starter prompts for the plugin. Capped at 3 entries with a maximum of 128 characters per entry.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  developerName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logo: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoDark: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Local dark-mode logo path, resolved from the installed plugin package.\",\n    }),\n  ),\n  logoUrl: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  logoUrlDark: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Remote dark-mode logo URL from the plugin catalog.\" }),\n      Schema.Null,\n    ]),\n  ),\n  longDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  privacyPolicyUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  screenshotUrls: Schema.Array(Schema.String).annotate({\n    description: \"Remote screenshot URLs from the plugin catalog.\",\n  }),\n  screenshots: Schema.Array(V2PluginShareListResponse__AbsolutePathBuf).annotate({\n    description: \"Local screenshot paths, resolved from the installed plugin package.\",\n  }),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  termsOfServiceUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  websiteUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginShareListResponse__PluginSource =\n  | { readonly path: V2PluginShareListResponse__AbsolutePathBuf; readonly type: \"local\" }\n  | {\n      readonly path?: string | null;\n      readonly refName?: string | null;\n      readonly sha?: string | null;\n      readonly type: \"git\";\n      readonly url: string;\n    }\n  | {\n      readonly package: string;\n      readonly registry?: string | null;\n      readonly type: \"npm\";\n      readonly version?: string | null;\n    }\n  | { readonly type: \"remote\" };\nexport const V2PluginShareListResponse__PluginSource = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2PluginShareListResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"local\").annotate({ title: \"LocalPluginSourceType\" }),\n    }).annotate({ title: \"LocalPluginSource\" }),\n    Schema.Struct({\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      sha: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"git\").annotate({ title: \"GitPluginSourceType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"GitPluginSource\" }),\n    Schema.Struct({\n      package: Schema.String,\n      registry: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional HTTPS registry URL. Authentication stays in the user's npm config.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"npm\").annotate({ title: \"NpmPluginSourceType\" }),\n      version: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional npm version or version range.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"NpmPluginSource\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"remote\").annotate({ title: \"RemotePluginSourceType\" }),\n    }).annotate({\n      title: \"RemotePluginSource\",\n      description:\n        \"The plugin is available in the remote catalog. Download metadata is kept server-side and is not exposed through the app-server API.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2PluginShareListResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginShareListResponse__PluginSharePrincipalType;\n  readonly role: V2PluginShareListResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginShareListResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginShareListResponse__PluginSharePrincipalType,\n  role: V2PluginShareListResponse__PluginSharePrincipalRole,\n});\n\nexport type V2PluginShareSaveParams__PluginShareTarget = {\n  readonly principalId: string;\n  readonly principalType: V2PluginShareSaveParams__PluginSharePrincipalType;\n  readonly role: V2PluginShareSaveParams__PluginShareTargetRole;\n};\nexport const V2PluginShareSaveParams__PluginShareTarget = Schema.Struct({\n  principalId: Schema.String,\n  principalType: V2PluginShareSaveParams__PluginSharePrincipalType,\n  role: V2PluginShareSaveParams__PluginShareTargetRole,\n});\n\nexport type V2PluginShareUpdateTargetsParams__PluginShareTarget = {\n  readonly principalId: string;\n  readonly principalType: V2PluginShareUpdateTargetsParams__PluginSharePrincipalType;\n  readonly role: V2PluginShareUpdateTargetsParams__PluginShareTargetRole;\n};\nexport const V2PluginShareUpdateTargetsParams__PluginShareTarget = Schema.Struct({\n  principalId: Schema.String,\n  principalType: V2PluginShareUpdateTargetsParams__PluginSharePrincipalType,\n  role: V2PluginShareUpdateTargetsParams__PluginShareTargetRole,\n});\n\nexport type V2PluginShareUpdateTargetsResponse__PluginSharePrincipal = {\n  readonly name: string;\n  readonly principalId: string;\n  readonly principalType: V2PluginShareUpdateTargetsResponse__PluginSharePrincipalType;\n  readonly role: V2PluginShareUpdateTargetsResponse__PluginSharePrincipalRole;\n};\nexport const V2PluginShareUpdateTargetsResponse__PluginSharePrincipal = Schema.Struct({\n  name: Schema.String,\n  principalId: Schema.String,\n  principalType: V2PluginShareUpdateTargetsResponse__PluginSharePrincipalType,\n  role: V2PluginShareUpdateTargetsResponse__PluginSharePrincipalRole,\n});\n\nexport type V2RawResponseItemCompletedNotification__ContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: V2RawResponseItemCompletedNotification__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly text: string; readonly type: \"output_text\" };\nexport const V2RawResponseItemCompletedNotification__ContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({ title: \"InputTextContentItemType\" }),\n    }).annotate({ title: \"InputTextContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2RawResponseItemCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({ title: \"InputImageContentItemType\" }),\n    }).annotate({ title: \"InputImageContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({ title: \"InputAudioContentItemType\" }),\n    }).annotate({ title: \"InputAudioContentItem\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"output_text\").annotate({ title: \"OutputTextContentItemType\" }),\n    }).annotate({ title: \"OutputTextContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: V2RawResponseItemCompletedNotification__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2RawResponseItemCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({\n        title: \"InputImageFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({\n        title: \"InputAudioFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"EncryptedContentFunctionCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.\",\n});\n\nexport type V2ReviewStartResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ReviewStartResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ReviewStartResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ReviewStartResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ReviewStartResponse__CollabAgentStatus;\n};\nexport const V2ReviewStartResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ReviewStartResponse__CollabAgentStatus,\n});\n\nexport type V2ReviewStartResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ReviewStartResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ReviewStartResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ReviewStartResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ReviewStartResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ReviewStartResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ReviewStartResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ReviewStartResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ReviewStartResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ReviewStartResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ReviewStartResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ReviewStartResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ReviewStartResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ReviewStartResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ReviewStartResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ReviewStartResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ReviewStartResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ReviewStartResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ReviewStartResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ReviewStartResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2SkillsListResponse__SkillInterface = {\n  readonly brandColor?: string | null;\n  readonly defaultPrompt?: string | null;\n  readonly displayName?: string | null;\n  readonly iconLarge?: V2SkillsListResponse__AbsolutePathBuf | null;\n  readonly iconSmall?: V2SkillsListResponse__AbsolutePathBuf | null;\n  readonly shortDescription?: string | null;\n};\nexport const V2SkillsListResponse__SkillInterface = Schema.Struct({\n  brandColor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  defaultPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  displayName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconLarge: Schema.optionalKey(Schema.Union([V2SkillsListResponse__AbsolutePathBuf, Schema.Null])),\n  iconSmall: Schema.optionalKey(Schema.Union([V2SkillsListResponse__AbsolutePathBuf, Schema.Null])),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2SkillsListResponse__SkillDependencies = {\n  readonly tools: ReadonlyArray<V2SkillsListResponse__SkillToolDependency>;\n};\nexport const V2SkillsListResponse__SkillDependencies = Schema.Struct({\n  tools: Schema.Array(V2SkillsListResponse__SkillToolDependency),\n});\n\nexport type V2ThreadForkResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadForkResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadForkResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadForkResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadForkResponse__CollabAgentStatus;\n};\nexport const V2ThreadForkResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadForkResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadForkResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadForkResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadForkResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadForkResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadForkResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadForkResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadForkResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadForkResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadForkResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadForkResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadForkResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadForkResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadForkResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadForkResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadForkResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadForkResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadForkResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadForkResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadForkResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadForkResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadForkResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadForkResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadForkResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadGoalGetResponse__ThreadGoal = {\n  readonly createdAt: number;\n  readonly objective: string;\n  readonly status: V2ThreadGoalGetResponse__ThreadGoalStatus;\n  readonly threadId: string;\n  readonly timeUsedSeconds: number;\n  readonly tokenBudget?: number | null;\n  readonly tokensUsed: number;\n  readonly updatedAt: number;\n};\nexport const V2ThreadGoalGetResponse__ThreadGoal = Schema.Struct({\n  createdAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  objective: Schema.String,\n  status: V2ThreadGoalGetResponse__ThreadGoalStatus,\n  threadId: Schema.String,\n  timeUsedSeconds: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  tokensUsed: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  updatedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2ThreadGoalSetResponse__ThreadGoal = {\n  readonly createdAt: number;\n  readonly objective: string;\n  readonly status: V2ThreadGoalSetResponse__ThreadGoalStatus;\n  readonly threadId: string;\n  readonly timeUsedSeconds: number;\n  readonly tokenBudget?: number | null;\n  readonly tokensUsed: number;\n  readonly updatedAt: number;\n};\nexport const V2ThreadGoalSetResponse__ThreadGoal = Schema.Struct({\n  createdAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  objective: Schema.String,\n  status: V2ThreadGoalSetResponse__ThreadGoalStatus,\n  threadId: Schema.String,\n  timeUsedSeconds: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  tokensUsed: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  updatedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2ThreadGoalUpdatedNotification__ThreadGoal = {\n  readonly createdAt: number;\n  readonly objective: string;\n  readonly status: V2ThreadGoalUpdatedNotification__ThreadGoalStatus;\n  readonly threadId: string;\n  readonly timeUsedSeconds: number;\n  readonly tokenBudget?: number | null;\n  readonly tokensUsed: number;\n  readonly updatedAt: number;\n};\nexport const V2ThreadGoalUpdatedNotification__ThreadGoal = Schema.Struct({\n  createdAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  objective: Schema.String,\n  status: V2ThreadGoalUpdatedNotification__ThreadGoalStatus,\n  threadId: Schema.String,\n  timeUsedSeconds: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  tokensUsed: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  updatedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n});\n\nexport type V2ThreadListResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadListResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadListResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadListResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadListResponse__CollabAgentStatus;\n};\nexport const V2ThreadListResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadListResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadListResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadListResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadListResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadListResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadListResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadListResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadListResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadListResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadListResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadListResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadListResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadListResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadListResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadListResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadListResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadListResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadListResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadListResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadListResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadListResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadListResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadListResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadListResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadListResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadListResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadMetadataUpdateResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadMetadataUpdateResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadMetadataUpdateResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadMetadataUpdateResponse__CollabAgentStatus;\n};\nexport const V2ThreadMetadataUpdateResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadMetadataUpdateResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadMetadataUpdateResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadMetadataUpdateResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadMetadataUpdateResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadMetadataUpdateResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadMetadataUpdateResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadMetadataUpdateResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadMetadataUpdateResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadMetadataUpdateResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadMetadataUpdateResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadMetadataUpdateResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadMetadataUpdateResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadMetadataUpdateResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadMetadataUpdateResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadMetadataUpdateResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadMetadataUpdateResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadMetadataUpdateResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadMetadataUpdateResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadMetadataUpdateResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadMetadataUpdateResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadMetadataUpdateResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadMetadataUpdateResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadMetadataUpdateResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadReadResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadReadResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadReadResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadReadResponse__CollabAgentStatus;\n};\nexport const V2ThreadReadResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadReadResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadReadResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadReadResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadReadResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadReadResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadReadResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadReadResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadReadResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadReadResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadReadResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadReadResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadReadResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadReadResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadReadResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadReadResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadReadResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadReadResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadReadResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadReadResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadReadResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadReadResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadReadResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadReadResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadReadResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadReadResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadReadResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: V2ThreadResumeParams__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly text: string; readonly type: \"output_text\" };\nexport const V2ThreadResumeParams__ContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({ title: \"InputTextContentItemType\" }),\n    }).annotate({ title: \"InputTextContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__ImageDetail, Schema.Null])),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({ title: \"InputImageContentItemType\" }),\n    }).annotate({ title: \"InputImageContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({ title: \"InputAudioContentItemType\" }),\n    }).annotate({ title: \"InputAudioContentItem\" }),\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"output_text\").annotate({ title: \"OutputTextContentItemType\" }),\n    }).annotate({ title: \"OutputTextContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__FunctionCallOutputContentItem =\n  | { readonly text: string; readonly type: \"input_text\" }\n  | {\n      readonly detail?: V2ThreadResumeParams__ImageDetail | null;\n      readonly image_url: string;\n      readonly type: \"input_image\";\n    }\n  | { readonly audio_url: string; readonly type: \"input_audio\" }\n  | { readonly encrypted_content: string; readonly type: \"encrypted_content\" };\nexport const V2ThreadResumeParams__FunctionCallOutputContentItem = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      type: Schema.Literal(\"input_text\").annotate({\n        title: \"InputTextFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputTextFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__ImageDetail, Schema.Null])),\n      image_url: Schema.String,\n      type: Schema.Literal(\"input_image\").annotate({\n        title: \"InputImageFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputImageFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      audio_url: Schema.String,\n      type: Schema.Literal(\"input_audio\").annotate({\n        title: \"InputAudioFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"InputAudioFunctionCallOutputContentItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      type: Schema.Literal(\"encrypted_content\").annotate({\n        title: \"EncryptedContentFunctionCallOutputContentItemType\",\n      }),\n    }).annotate({ title: \"EncryptedContentFunctionCallOutputContentItem\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Responses API compatible content items that can be returned by a tool call. This is a subset of ContentItem with the types we support as function call outputs.\",\n});\n\nexport type V2ThreadResumeResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadResumeResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadResumeResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadResumeResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadResumeResponse__CollabAgentStatus;\n};\nexport const V2ThreadResumeResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadResumeResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadResumeResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadResumeResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadResumeResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadResumeResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadResumeResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadResumeResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadResumeResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadResumeResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadResumeResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadResumeResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadResumeResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadResumeResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadResumeResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadResumeResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadResumeResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadResumeResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadResumeResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadResumeResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadResumeResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadResumeResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadResumeResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadResumeResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadResumeResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadRollbackResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadRollbackResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadRollbackResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadRollbackResponse__CollabAgentStatus;\n};\nexport const V2ThreadRollbackResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadRollbackResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadRollbackResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadRollbackResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadRollbackResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadRollbackResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadRollbackResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadRollbackResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadRollbackResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadRollbackResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadRollbackResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadRollbackResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadRollbackResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadRollbackResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadRollbackResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadRollbackResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadRollbackResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadRollbackResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadRollbackResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadRollbackResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadRollbackResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadRollbackResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadRollbackResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadRollbackResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadRollbackResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2ThreadSettingsUpdatedNotification__AbsolutePathBuf>;\n    };\nexport const V2ThreadSettingsUpdatedNotification__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2ThreadSettingsUpdatedNotification__AbsolutePathBuf).annotate({\n          default: [],\n        }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__Settings = {\n  readonly developer_instructions?: string | null;\n  readonly model: string;\n  readonly reasoning_effort?: V2ThreadSettingsUpdatedNotification__ReasoningEffort | null;\n};\nexport const V2ThreadSettingsUpdatedNotification__Settings = Schema.Struct({\n  developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasoning_effort: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__ReasoningEffort, Schema.Null]),\n  ),\n}).annotate({ description: \"Settings for a collaboration mode.\" });\n\nexport type V2ThreadStartedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadStartedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadStartedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadStartedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadStartedNotification__CollabAgentStatus;\n};\nexport const V2ThreadStartedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadStartedNotification__CollabAgentStatus,\n});\n\nexport type V2ThreadStartedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadStartedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadStartedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadStartedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadStartedNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadStartedNotification__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadStartedNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadStartedNotification__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadStartedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadStartedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadStartedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadStartedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadStartedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadStartedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadStartedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadStartedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadStartedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadStartedNotification__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadStartedNotification__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadStartedNotification__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadStartedNotification__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadStartedNotification__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadStartResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadStartResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadStartResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadStartResponse__CollabAgentStatus;\n};\nexport const V2ThreadStartResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadStartResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadStartResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadStartResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadStartResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadStartResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadStartResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadStartResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadStartResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadStartResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadStartResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadStartResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadStartResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadStartResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadStartResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadStartResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadStartResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadStartResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadStartResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadStartResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadStartResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadStartResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadStartResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadStartResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadStartResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStatusChangedNotification__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadStatusChangedNotification__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadStatusChangedNotification__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadStatusChangedNotification__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage = {\n  readonly last: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown;\n  readonly modelContextWindow?: number | null;\n  readonly total: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown;\n};\nexport const V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage = Schema.Struct({\n  last: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown,\n  modelContextWindow: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  total: V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown,\n});\n\nexport type V2ThreadUnarchiveResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2ThreadUnarchiveResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2ThreadUnarchiveResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2ThreadUnarchiveResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2ThreadUnarchiveResponse__CollabAgentStatus;\n};\nexport const V2ThreadUnarchiveResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2ThreadUnarchiveResponse__CollabAgentStatus,\n});\n\nexport type V2ThreadUnarchiveResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2ThreadUnarchiveResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2ThreadUnarchiveResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2ThreadUnarchiveResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2ThreadUnarchiveResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2ThreadUnarchiveResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2ThreadUnarchiveResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2ThreadUnarchiveResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2ThreadUnarchiveResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2ThreadUnarchiveResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2ThreadUnarchiveResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2ThreadUnarchiveResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2ThreadUnarchiveResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2ThreadUnarchiveResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2ThreadUnarchiveResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2ThreadUnarchiveResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2ThreadUnarchiveResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__SubAgentSource =\n  | \"review\"\n  | \"compact\"\n  | \"memory_consolidation\"\n  | {\n      readonly thread_spawn: {\n        readonly agent_nickname?: string | null;\n        readonly agent_path?: V2ThreadUnarchiveResponse__AgentPath | null;\n        readonly agent_role?: string | null;\n        readonly depth: number;\n        readonly parent_thread_id: V2ThreadUnarchiveResponse__ThreadId;\n      };\n    }\n  | { readonly other: string };\nexport const V2ThreadUnarchiveResponse__SubAgentSource = Schema.Union(\n  [\n    Schema.Literals([\"review\", \"compact\", \"memory_consolidation\"]),\n    Schema.Struct({\n      thread_spawn: Schema.Struct({\n        agent_nickname: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        agent_path: Schema.optionalKey(\n          Schema.Union([V2ThreadUnarchiveResponse__AgentPath, Schema.Null]),\n        ),\n        agent_role: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        depth: Schema.Number.annotate({ format: \"int32\" }).check(Schema.isInt()),\n        parent_thread_id: V2ThreadUnarchiveResponse__ThreadId,\n      }),\n    }).annotate({ title: \"ThreadSpawnSubAgentSource\" }),\n    Schema.Struct({ other: Schema.String }).annotate({ title: \"OtherSubAgentSource\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2TurnCompletedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2TurnCompletedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2TurnCompletedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2TurnCompletedNotification__CollabAgentStatus;\n};\nexport const V2TurnCompletedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2TurnCompletedNotification__CollabAgentStatus,\n});\n\nexport type V2TurnCompletedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2TurnCompletedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2TurnCompletedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2TurnCompletedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2TurnCompletedNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2TurnCompletedNotification__NonSteerableTurnKind;\n      };\n    };\nexport const V2TurnCompletedNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2TurnCompletedNotification__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2TurnCompletedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2TurnCompletedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2TurnCompletedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2TurnCompletedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnCompletedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnCompletedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnCompletedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnCompletedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnCompletedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnPlanUpdatedNotification__TurnPlanStep = {\n  readonly status: V2TurnPlanUpdatedNotification__TurnPlanStepStatus;\n  readonly step: string;\n};\nexport const V2TurnPlanUpdatedNotification__TurnPlanStep = Schema.Struct({\n  status: V2TurnPlanUpdatedNotification__TurnPlanStepStatus,\n  step: Schema.String,\n});\n\nexport type V2TurnStartedNotification__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2TurnStartedNotification__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2TurnStartedNotification__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2TurnStartedNotification__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartedNotification__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2TurnStartedNotification__CollabAgentStatus;\n};\nexport const V2TurnStartedNotification__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2TurnStartedNotification__CollabAgentStatus,\n});\n\nexport type V2TurnStartedNotification__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2TurnStartedNotification__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2TurnStartedNotification__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2TurnStartedNotification__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2TurnStartedNotification__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2TurnStartedNotification__NonSteerableTurnKind;\n      };\n    };\nexport const V2TurnStartedNotification__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2TurnStartedNotification__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2TurnStartedNotification__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2TurnStartedNotification__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2TurnStartedNotification__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2TurnStartedNotification__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2TurnStartedNotification__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnStartedNotification__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnStartedNotification__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnStartedNotification__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnStartedNotification__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnStartedNotification__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__ImageDetail, Schema.Null]),\n      ),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartParams__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2TurnStartParams__AbsolutePathBuf>;\n    };\nexport const V2TurnStartParams__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2TurnStartParams__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartParams__Settings = {\n  readonly developer_instructions?: string | null;\n  readonly model: string;\n  readonly reasoning_effort?: V2TurnStartParams__ReasoningEffort | null;\n};\nexport const V2TurnStartParams__Settings = Schema.Struct({\n  developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasoning_effort: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__ReasoningEffort, Schema.Null]),\n  ),\n}).annotate({ description: \"Settings for a collaboration mode.\" });\n\nexport type V2TurnStartParams__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnStartParams__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnStartParams__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnStartParams__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnStartParams__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnStartParams__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnStartParams__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnStartParams__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__CommandAction =\n  | {\n      readonly command: string;\n      readonly name: string;\n      readonly path: V2TurnStartResponse__AbsolutePathBuf;\n      readonly type: \"read\";\n    }\n  | { readonly command: string; readonly path?: string | null; readonly type: \"listFiles\" }\n  | {\n      readonly command: string;\n      readonly path?: string | null;\n      readonly query?: string | null;\n      readonly type: \"search\";\n    }\n  | { readonly command: string; readonly type: \"unknown\" };\nexport const V2TurnStartResponse__CommandAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      name: Schema.String,\n      path: V2TurnStartResponse__AbsolutePathBuf,\n      type: Schema.Literal(\"read\").annotate({ title: \"ReadCommandActionType\" }),\n    }).annotate({ title: \"ReadCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"listFiles\").annotate({ title: \"ListFilesCommandActionType\" }),\n    }).annotate({ title: \"ListFilesCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      path: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      query: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"search\").annotate({ title: \"SearchCommandActionType\" }),\n    }).annotate({ title: \"SearchCommandAction\" }),\n    Schema.Struct({\n      command: Schema.String,\n      type: Schema.Literal(\"unknown\").annotate({ title: \"UnknownCommandActionType\" }),\n    }).annotate({ title: \"UnknownCommandAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__CollabAgentState = {\n  readonly message?: string | null;\n  readonly status: V2TurnStartResponse__CollabAgentStatus;\n};\nexport const V2TurnStartResponse__CollabAgentState = Schema.Struct({\n  message: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: V2TurnStartResponse__CollabAgentStatus,\n});\n\nexport type V2TurnStartResponse__MemoryCitation = {\n  readonly entries: ReadonlyArray<V2TurnStartResponse__MemoryCitationEntry>;\n  readonly threadIds: ReadonlyArray<string>;\n};\nexport const V2TurnStartResponse__MemoryCitation = Schema.Struct({\n  entries: Schema.Array(V2TurnStartResponse__MemoryCitationEntry),\n  threadIds: Schema.Array(Schema.String),\n});\n\nexport type V2TurnStartResponse__CodexErrorInfo =\n  | \"contextWindowExceeded\"\n  | \"sessionBudgetExceeded\"\n  | \"usageLimitExceeded\"\n  | \"serverOverloaded\"\n  | \"cyberPolicy\"\n  | \"internalServerError\"\n  | \"unauthorized\"\n  | \"badRequest\"\n  | \"threadRollbackFailed\"\n  | \"sandboxError\"\n  | \"other\"\n  | { readonly httpConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamConnectionFailed: { readonly httpStatusCode?: number | null } }\n  | { readonly responseStreamDisconnected: { readonly httpStatusCode?: number | null } }\n  | { readonly responseTooManyFailedAttempts: { readonly httpStatusCode?: number | null } }\n  | {\n      readonly activeTurnNotSteerable: {\n        readonly turnKind: V2TurnStartResponse__NonSteerableTurnKind;\n      };\n    };\nexport const V2TurnStartResponse__CodexErrorInfo = Schema.Union(\n  [\n    Schema.Literals([\n      \"contextWindowExceeded\",\n      \"sessionBudgetExceeded\",\n      \"usageLimitExceeded\",\n      \"serverOverloaded\",\n      \"cyberPolicy\",\n      \"internalServerError\",\n      \"unauthorized\",\n      \"badRequest\",\n      \"threadRollbackFailed\",\n      \"sandboxError\",\n      \"other\",\n    ]),\n    Schema.Struct({\n      httpConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({ title: \"HttpConnectionFailedCodexErrorInfo\" }),\n    Schema.Struct({\n      responseStreamConnectionFailed: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamConnectionFailedCodexErrorInfo\",\n      description: \"Failed to connect to the response SSE stream.\",\n    }),\n    Schema.Struct({\n      responseStreamDisconnected: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseStreamDisconnectedCodexErrorInfo\",\n      description:\n        \"The response SSE stream disconnected in the middle of a turn before completion.\",\n    }),\n    Schema.Struct({\n      responseTooManyFailedAttempts: Schema.Struct({\n        httpStatusCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"uint16\" })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n      }),\n    }).annotate({\n      title: \"ResponseTooManyFailedAttemptsCodexErrorInfo\",\n      description: \"Reached the retry limit for responses.\",\n    }),\n    Schema.Struct({\n      activeTurnNotSteerable: Schema.Struct({\n        turnKind: V2TurnStartResponse__NonSteerableTurnKind,\n      }),\n    }).annotate({\n      title: \"ActiveTurnNotSteerableCodexErrorInfo\",\n      description:\n        \"Returned when `turn/start` or `turn/steer` is submitted while the current active turn cannot accept same-turn steering, for example `/review` or manual `/compact`.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"This translation layer make sure that we expose codex error code in camel case.\\n\\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.\",\n});\n\nexport type V2TurnStartResponse__FileUpdateChange = {\n  readonly diff: string;\n  readonly kind: V2TurnStartResponse__PatchChangeKind;\n  readonly path: string;\n};\nexport const V2TurnStartResponse__FileUpdateChange = Schema.Struct({\n  diff: Schema.String,\n  kind: V2TurnStartResponse__PatchChangeKind,\n  path: Schema.String,\n});\n\nexport type V2TurnStartResponse__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnStartResponse__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnStartResponse__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnStartResponse__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnStartResponse__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnStartResponse__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnStartResponse__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnStartResponse__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnSteerParams__UserInput =\n  | {\n      readonly text: string;\n      readonly text_elements?: ReadonlyArray<V2TurnSteerParams__TextElement>;\n      readonly type: \"text\";\n    }\n  | {\n      readonly detail?: V2TurnSteerParams__ImageDetail | null;\n      readonly type: \"image\";\n      readonly url: string;\n    }\n  | {\n      readonly detail?: V2TurnSteerParams__ImageDetail | null;\n      readonly path: string;\n      readonly type: \"localImage\";\n    }\n  | { readonly type: \"audio\"; readonly url: string }\n  | { readonly path: string; readonly type: \"localAudio\" }\n  | { readonly name: string; readonly path: string; readonly type: \"skill\" }\n  | { readonly name: string; readonly path: string; readonly type: \"mention\" };\nexport const V2TurnSteerParams__UserInput = Schema.Union(\n  [\n    Schema.Struct({\n      text: Schema.String,\n      text_elements: Schema.optionalKey(\n        Schema.Array(V2TurnSteerParams__TextElement).annotate({\n          description: \"UI-defined spans within `text` used to render or persist special elements.\",\n          default: [],\n        }),\n      ),\n      type: Schema.Literal(\"text\").annotate({ title: \"TextUserInputType\" }),\n    }).annotate({ title: \"TextUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnSteerParams__ImageDetail, Schema.Null])),\n      type: Schema.Literal(\"image\").annotate({ title: \"ImageUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"ImageUserInput\" }),\n    Schema.Struct({\n      detail: Schema.optionalKey(Schema.Union([V2TurnSteerParams__ImageDetail, Schema.Null])),\n      path: Schema.String,\n      type: Schema.Literal(\"localImage\").annotate({ title: \"LocalImageUserInputType\" }),\n    }).annotate({ title: \"LocalImageUserInput\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\").annotate({ title: \"AudioUserInputType\" }),\n      url: Schema.String,\n    }).annotate({ title: \"AudioUserInput\" }),\n    Schema.Struct({\n      path: Schema.String,\n      type: Schema.Literal(\"localAudio\").annotate({ title: \"LocalAudioUserInputType\" }),\n    }).annotate({ title: \"LocalAudioUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"skill\").annotate({ title: \"SkillUserInputType\" }),\n    }).annotate({ title: \"SkillUserInput\" }),\n    Schema.Struct({\n      name: Schema.String,\n      path: Schema.String,\n      type: Schema.Literal(\"mention\").annotate({ title: \"MentionUserInputType\" }),\n    }).annotate({ title: \"MentionUserInput\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ApplyPatchApprovalResponse__ReviewDecision =\n  | \"approved\"\n  | {\n      readonly approved_execpolicy_amendment: {\n        readonly proposed_execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | \"approved_for_session\"\n  | {\n      readonly network_policy_amendment: {\n        readonly network_policy_amendment: ApplyPatchApprovalResponse__NetworkPolicyAmendment;\n      };\n    }\n  | \"denied\"\n  | \"timed_out\"\n  | \"abort\";\nexport const ApplyPatchApprovalResponse__ReviewDecision = Schema.Union(\n  [\n    Schema.Literal(\"approved\").annotate({\n      description: \"User has approved this command and the agent should execute it.\",\n    }),\n    Schema.Struct({\n      approved_execpolicy_amendment: Schema.Struct({\n        proposed_execpolicy_amendment: Schema.Array(Schema.String),\n      }),\n    }).annotate({\n      title: \"ApprovedExecpolicyAmendmentReviewDecision\",\n      description:\n        \"User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.\",\n    }),\n    Schema.Literal(\"approved_for_session\").annotate({\n      description:\n        \"User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.\",\n    }),\n    Schema.Struct({\n      network_policy_amendment: Schema.Struct({\n        network_policy_amendment: ApplyPatchApprovalResponse__NetworkPolicyAmendment,\n      }),\n    }).annotate({\n      title: \"NetworkPolicyAmendmentReviewDecision\",\n      description:\n        \"User chose to persist a network policy rule (allow/deny) for future requests to the same host.\",\n    }),\n    Schema.Literal(\"denied\").annotate({\n      description:\n        \"User has denied this command and the agent should not execute it, but it should continue the session and try something else.\",\n    }),\n    Schema.Literal(\"timed_out\").annotate({\n      description: \"Automatic approval review timed out before reaching a decision.\",\n    }),\n    Schema.Literal(\"abort\").annotate({\n      description:\n        \"User has denied this command and the agent should not do anything until the user's next command.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"User's decision in response to an ExecApprovalRequest.\" });\n\nexport type ClientRequest__CommandExecParams = {\n  readonly command: ReadonlyArray<string>;\n  readonly cwd?: string | null;\n  readonly disableOutputCap?: boolean;\n  readonly disableTimeout?: boolean;\n  readonly env?: { readonly [x: string]: string | null } | null;\n  readonly outputBytesCap?: number | null;\n  readonly processId?: string | null;\n  readonly sandboxPolicy?: ClientRequest__SandboxPolicy | null;\n  readonly size?: ClientRequest__CommandExecTerminalSize | null;\n  readonly streamStdin?: boolean;\n  readonly streamStdoutStderr?: boolean;\n  readonly timeoutMs?: number | null;\n  readonly tty?: boolean;\n};\nexport const ClientRequest__CommandExecParams = Schema.Struct({\n  command: Schema.Array(Schema.String).annotate({\n    description: \"Command argv vector. Empty arrays are rejected.\",\n  }),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional working directory. Defaults to the server cwd.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  disableOutputCap: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Disable stdout/stderr capture truncation for this request.\\n\\nCannot be combined with `outputBytesCap`.\",\n    }),\n  ),\n  disableTimeout: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Disable the timeout entirely for this request.\\n\\nCannot be combined with `timeoutMs`.\",\n    }),\n  ),\n  env: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Null])).annotate({\n        description:\n          \"Optional environment overrides merged into the server-computed environment.\\n\\nMatching names override inherited values. Set a key to `null` to unset an inherited variable.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outputBytesCap: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Optional per-stream stdout/stderr capture cap in bytes.\\n\\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.\",\n        format: \"uint\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  processId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional client-supplied, connection-scoped process id.\\n\\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sandboxPolicy: Schema.optionalKey(\n    Schema.Union([ClientRequest__SandboxPolicy, Schema.Null]).annotate({\n      description:\n        \"Optional sandbox policy for this command.\\n\\nUses the same shape as thread/turn execution sandbox configuration and defaults to the user's configured policy when omitted. Cannot be combined with `permissionProfile`.\",\n    }),\n  ),\n  size: Schema.optionalKey(\n    Schema.Union([ClientRequest__CommandExecTerminalSize, Schema.Null]).annotate({\n      description: \"Optional initial PTY size in character cells. Only valid when `tty` is true.\",\n    }),\n  ),\n  streamStdin: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Allow follow-up `command/exec/write` requests to write stdin bytes.\\n\\nRequires a client-supplied `processId`.\",\n    }),\n  ),\n  streamStdoutStderr: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Stream stdout/stderr via `command/exec/outputDelta` notifications.\\n\\nStreamed bytes are not duplicated into the final response and require a client-supplied `processId`.\",\n    }),\n  ),\n  timeoutMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Optional timeout in milliseconds.\\n\\nWhen omitted, the server default applies. Cannot be combined with `disableTimeout`.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  tty: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Enable PTY mode.\\n\\nThis implies `streamStdin` and `streamStdoutStderr`.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Run a standalone command (argv vector) in the server sandbox without creating a thread or turn.\\n\\nThe final `command/exec` response is deferred until the process exits and is sent only after all `command/exec/outputDelta` notifications for that connection have been emitted.\",\n});\n\nexport type ClientRequest__FunctionCallOutputBody =\n  | string\n  | ReadonlyArray<ClientRequest__FunctionCallOutputContentItem>;\nexport const ClientRequest__FunctionCallOutputBody = Schema.Union([\n  Schema.String,\n  Schema.Array(ClientRequest__FunctionCallOutputContentItem),\n]);\n\nexport type ClientRequest__ConfigBatchWriteParams = {\n  readonly edits: ReadonlyArray<ClientRequest__ConfigEdit>;\n  readonly expectedVersion?: string | null;\n  readonly filePath?: string | null;\n  readonly reloadUserConfig?: boolean;\n};\nexport const ClientRequest__ConfigBatchWriteParams = Schema.Struct({\n  edits: Schema.Array(ClientRequest__ConfigEdit),\n  expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  filePath: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Path to the config file to write; defaults to the user's `config.toml` when omitted.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reloadUserConfig: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, hot-reload the updated user config into all loaded threads after writing.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__PluginShareSaveParams = {\n  readonly discoverability?: ClientRequest__PluginShareDiscoverability | null;\n  readonly pluginPath: ClientRequest__AbsolutePathBuf;\n  readonly remotePluginId?: string | null;\n  readonly shareTargets?: ReadonlyArray<ClientRequest__PluginShareTarget> | null;\n};\nexport const ClientRequest__PluginShareSaveParams = Schema.Struct({\n  discoverability: Schema.optionalKey(\n    Schema.Union([ClientRequest__PluginShareDiscoverability, Schema.Null]),\n  ),\n  pluginPath: ClientRequest__AbsolutePathBuf,\n  remotePluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  shareTargets: Schema.optionalKey(\n    Schema.Union([Schema.Array(ClientRequest__PluginShareTarget), Schema.Null]),\n  ),\n});\n\nexport type ClientRequest__PluginShareUpdateTargetsParams = {\n  readonly discoverability: ClientRequest__PluginShareUpdateDiscoverability;\n  readonly remotePluginId: string;\n  readonly shareTargets: ReadonlyArray<ClientRequest__PluginShareTarget>;\n};\nexport const ClientRequest__PluginShareUpdateTargetsParams = Schema.Struct({\n  discoverability: ClientRequest__PluginShareUpdateDiscoverability,\n  remotePluginId: Schema.String,\n  shareTargets: Schema.Array(ClientRequest__PluginShareTarget),\n});\n\nexport type ClientRequest__ExternalAgentConfigMigrationItem = {\n  readonly cwd?: string | null;\n  readonly description: string;\n  readonly details?: ClientRequest__MigrationDetails | null;\n  readonly itemType: ClientRequest__ExternalAgentConfigMigrationItemType;\n};\nexport const ClientRequest__ExternalAgentConfigMigrationItem = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Null or empty means home-scoped migration; non-empty means repo-scoped migration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String,\n  details: Schema.optionalKey(Schema.Union([ClientRequest__MigrationDetails, Schema.Null])),\n  itemType: ClientRequest__ExternalAgentConfigMigrationItemType,\n});\n\nexport type ClientRequest__TurnStartParams = {\n  readonly approvalPolicy?: ClientRequest__AskForApproval | null;\n  readonly approvalsReviewer?: ClientRequest__ApprovalsReviewer | null;\n  readonly clientUserMessageId?: string | null;\n  readonly cwd?: string | null;\n  readonly effort?: ClientRequest__ReasoningEffort | null;\n  readonly input: ReadonlyArray<ClientRequest__UserInput>;\n  readonly model?: string | null;\n  readonly outputSchema?: unknown;\n  readonly personality?: ClientRequest__Personality | null;\n  readonly sandboxPolicy?: ClientRequest__SandboxPolicy | null;\n  readonly serviceTier?: string | null;\n  readonly summary?: ClientRequest__ReasoningSummary | null;\n  readonly threadId: string;\n};\nexport const ClientRequest__TurnStartParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([ClientRequest__AskForApproval, Schema.Null]).annotate({\n      description: \"Override the approval policy for this turn and subsequent turns.\",\n    }),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([ClientRequest__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this turn and subsequent turns.\",\n    }),\n  ),\n  clientUserMessageId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the working directory for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  effort: Schema.optionalKey(\n    Schema.Union([ClientRequest__ReasoningEffort, Schema.Null]).annotate({\n      description: \"Override the reasoning effort for this turn and subsequent turns.\",\n    }),\n  ),\n  input: Schema.Array(ClientRequest__UserInput),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the model for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outputSchema: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description:\n        \"Optional JSON Schema used to constrain the final assistant message for this turn.\",\n    }),\n  ),\n  personality: Schema.optionalKey(\n    Schema.Union([ClientRequest__Personality, Schema.Null]).annotate({\n      description: \"Override the personality for this turn and subsequent turns.\",\n    }),\n  ),\n  sandboxPolicy: Schema.optionalKey(\n    Schema.Union([ClientRequest__SandboxPolicy, Schema.Null]).annotate({\n      description: \"Override the sandbox policy for this turn and subsequent turns.\",\n    }),\n  ),\n  serviceTier: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the service tier for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  summary: Schema.optionalKey(\n    Schema.Union([ClientRequest__ReasoningSummary, Schema.Null]).annotate({\n      description: \"Override the reasoning summary for this turn and subsequent turns.\",\n    }),\n  ),\n  threadId: Schema.String,\n});\n\nexport type ClientRequest__TurnSteerParams = {\n  readonly clientUserMessageId?: string | null;\n  readonly expectedTurnId: string;\n  readonly input: ReadonlyArray<ClientRequest__UserInput>;\n  readonly threadId: string;\n};\nexport const ClientRequest__TurnSteerParams = Schema.Struct({\n  clientUserMessageId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  expectedTurnId: Schema.String.annotate({\n    description:\n      \"Required active turn id precondition. The request fails when it does not match the currently active turn.\",\n  }),\n  input: Schema.Array(ClientRequest__UserInput),\n  threadId: Schema.String,\n});\n\nexport type CommandExecutionRequestApprovalParams__FileSystemPath =\n  | {\n      readonly path: CommandExecutionRequestApprovalParams__LegacyAppPathString;\n      readonly type: \"path\";\n    }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: CommandExecutionRequestApprovalParams__FileSystemSpecialPath;\n    };\nexport const CommandExecutionRequestApprovalParams__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: CommandExecutionRequestApprovalParams__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: CommandExecutionRequestApprovalParams__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision =\n  | \"accept\"\n  | \"acceptForSession\"\n  | {\n      readonly acceptWithExecpolicyAmendment: {\n        readonly execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | {\n      readonly applyNetworkPolicyAmendment: {\n        readonly network_policy_amendment: CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment;\n      };\n    }\n  | \"decline\"\n  | \"cancel\";\nexport const CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision =\n  Schema.Union(\n    [\n      Schema.Literal(\"accept\").annotate({ description: \"User approved the command.\" }),\n      Schema.Literal(\"acceptForSession\").annotate({\n        description:\n          \"User approved the command and future prompts in the same session-scoped approval cache should run without prompting.\",\n      }),\n      Schema.Struct({\n        acceptWithExecpolicyAmendment: Schema.Struct({\n          execpolicy_amendment: Schema.Array(Schema.String),\n        }),\n      }).annotate({\n        title: \"AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision\",\n        description:\n          \"User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.\",\n      }),\n      Schema.Struct({\n        applyNetworkPolicyAmendment: Schema.Struct({\n          network_policy_amendment: CommandExecutionRequestApprovalResponse__NetworkPolicyAmendment,\n        }),\n      }).annotate({\n        title: \"ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision\",\n        description: \"User chose a persistent network policy rule (allow/deny) for this host.\",\n      }),\n      Schema.Literal(\"decline\").annotate({\n        description: \"User denied the command. The agent will continue the turn.\",\n      }),\n      Schema.Literal(\"cancel\").annotate({\n        description: \"User denied the command. The turn will also be immediately interrupted.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  );\n\nexport type ExecCommandApprovalResponse__ReviewDecision =\n  | \"approved\"\n  | {\n      readonly approved_execpolicy_amendment: {\n        readonly proposed_execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | \"approved_for_session\"\n  | {\n      readonly network_policy_amendment: {\n        readonly network_policy_amendment: ExecCommandApprovalResponse__NetworkPolicyAmendment;\n      };\n    }\n  | \"denied\"\n  | \"timed_out\"\n  | \"abort\";\nexport const ExecCommandApprovalResponse__ReviewDecision = Schema.Union(\n  [\n    Schema.Literal(\"approved\").annotate({\n      description: \"User has approved this command and the agent should execute it.\",\n    }),\n    Schema.Struct({\n      approved_execpolicy_amendment: Schema.Struct({\n        proposed_execpolicy_amendment: Schema.Array(Schema.String),\n      }),\n    }).annotate({\n      title: \"ApprovedExecpolicyAmendmentReviewDecision\",\n      description:\n        \"User has approved this command and wants to apply the proposed execpolicy amendment so future matching commands are permitted.\",\n    }),\n    Schema.Literal(\"approved_for_session\").annotate({\n      description:\n        \"User has approved this request and wants future prompts in the same session-scoped approval cache to be automatically approved for the remainder of the session.\",\n    }),\n    Schema.Struct({\n      network_policy_amendment: Schema.Struct({\n        network_policy_amendment: ExecCommandApprovalResponse__NetworkPolicyAmendment,\n      }),\n    }).annotate({\n      title: \"NetworkPolicyAmendmentReviewDecision\",\n      description:\n        \"User chose to persist a network policy rule (allow/deny) for future requests to the same host.\",\n    }),\n    Schema.Literal(\"denied\").annotate({\n      description:\n        \"User has denied this command and the agent should not execute it, but it should continue the session and try something else.\",\n    }),\n    Schema.Literal(\"timed_out\").annotate({\n      description: \"Automatic approval review timed out before reaching a decision.\",\n    }),\n    Schema.Literal(\"abort\").annotate({\n      description:\n        \"User has denied this command and the agent should not do anything until the user's next command.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"User's decision in response to an ExecApprovalRequest.\" });\n\nexport type McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items: McpServerElicitationRequestParams__McpElicitationTitledEnumItems;\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationArrayType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    items: McpServerElicitationRequestParams__McpElicitationTitledEnumItems,\n    maxItems: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint64\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n    minItems: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint64\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationArrayType,\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items: McpServerElicitationRequestParams__McpElicitationUntitledEnumItems;\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationArrayType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema =\n  Schema.Struct({\n    default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n    description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    items: McpServerElicitationRequestParams__McpElicitationUntitledEnumItems,\n    maxItems: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint64\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n    minItems: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint64\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        Schema.Null,\n      ]),\n    ),\n    title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    type: McpServerElicitationRequestParams__McpElicitationArrayType,\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema =\n  | McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema;\nexport const McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema = Schema.Union(\n  [\n    McpServerElicitationRequestParams__McpElicitationUntitledSingleSelectEnumSchema,\n    McpServerElicitationRequestParams__McpElicitationTitledSingleSelectEnumSchema,\n  ],\n);\n\nexport type PermissionsRequestApprovalParams__FileSystemPath =\n  | { readonly path: PermissionsRequestApprovalParams__LegacyAppPathString; readonly type: \"path\" }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: PermissionsRequestApprovalParams__FileSystemSpecialPath;\n    };\nexport const PermissionsRequestApprovalParams__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: PermissionsRequestApprovalParams__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: PermissionsRequestApprovalParams__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type PermissionsRequestApprovalResponse__FileSystemPath =\n  | {\n      readonly path: PermissionsRequestApprovalResponse__LegacyAppPathString;\n      readonly type: \"path\";\n    }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: PermissionsRequestApprovalResponse__FileSystemSpecialPath;\n    };\nexport const PermissionsRequestApprovalResponse__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: PermissionsRequestApprovalResponse__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: PermissionsRequestApprovalResponse__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__AppInfo = {\n  readonly appMetadata?: ServerNotification__AppMetadata | null;\n  readonly branding?: ServerNotification__AppBranding | null;\n  readonly description?: string | null;\n  readonly distributionChannel?: string | null;\n  readonly iconAssets?: { readonly [x: string]: string } | null;\n  readonly iconDarkAssets?: { readonly [x: string]: string } | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly isAccessible?: boolean;\n  readonly isEnabled?: boolean;\n  readonly labels?: { readonly [x: string]: string } | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly name: string;\n  readonly pluginDisplayNames?: ReadonlyArray<string>;\n};\nexport const ServerNotification__AppInfo = Schema.Struct({\n  appMetadata: Schema.optionalKey(Schema.Union([ServerNotification__AppMetadata, Schema.Null])),\n  branding: Schema.optionalKey(Schema.Union([ServerNotification__AppBranding, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  iconDarkAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isEnabled: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```\",\n      default: true,\n    }),\n  ),\n  labels: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type ServerNotification__ExternalAgentConfigImportTypeResult = {\n  readonly failures: ReadonlyArray<ServerNotification__ExternalAgentConfigImportItemTypeFailure>;\n  readonly itemType: ServerNotification__ExternalAgentConfigMigrationItemType;\n  readonly successes: ReadonlyArray<ServerNotification__ExternalAgentConfigImportItemTypeSuccess>;\n};\nexport const ServerNotification__ExternalAgentConfigImportTypeResult = Schema.Struct({\n  failures: Schema.Array(ServerNotification__ExternalAgentConfigImportItemTypeFailure),\n  itemType: ServerNotification__ExternalAgentConfigMigrationItemType,\n  successes: Schema.Array(ServerNotification__ExternalAgentConfigImportItemTypeSuccess),\n});\n\nexport type ServerNotification__FuzzyFileSearchSessionUpdatedNotification = {\n  readonly files: ReadonlyArray<ServerNotification__FuzzyFileSearchResult>;\n  readonly query: string;\n  readonly sessionId: string;\n};\nexport const ServerNotification__FuzzyFileSearchSessionUpdatedNotification = Schema.Struct({\n  files: Schema.Array(ServerNotification__FuzzyFileSearchResult),\n  query: Schema.String,\n  sessionId: Schema.String,\n});\n\nexport type ServerNotification__HookRunSummary = {\n  readonly completedAt?: number | null;\n  readonly displayOrder: number;\n  readonly durationMs?: number | null;\n  readonly entries: ReadonlyArray<ServerNotification__HookOutputEntry>;\n  readonly eventName: ServerNotification__HookEventName;\n  readonly executionMode: ServerNotification__HookExecutionMode;\n  readonly handlerType: ServerNotification__HookHandlerType;\n  readonly id: string;\n  readonly scope: ServerNotification__HookScope;\n  readonly source?:\n    | \"system\"\n    | \"user\"\n    | \"project\"\n    | \"mdm\"\n    | \"sessionFlags\"\n    | \"plugin\"\n    | \"cloudRequirements\"\n    | \"cloudManagedConfig\"\n    | \"legacyManagedConfigFile\"\n    | \"legacyManagedConfigMdm\"\n    | \"unknown\";\n  readonly sourcePath: ServerNotification__AbsolutePathBuf;\n  readonly startedAt: number;\n  readonly status: ServerNotification__HookRunStatus;\n  readonly statusMessage?: string | null;\n};\nexport const ServerNotification__HookRunSummary = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  displayOrder: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  durationMs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  entries: Schema.Array(ServerNotification__HookOutputEntry),\n  eventName: ServerNotification__HookEventName,\n  executionMode: ServerNotification__HookExecutionMode,\n  handlerType: ServerNotification__HookHandlerType,\n  id: Schema.String,\n  scope: ServerNotification__HookScope,\n  source: Schema.optionalKey(\n    Schema.Literals([\n      \"system\",\n      \"user\",\n      \"project\",\n      \"mdm\",\n      \"sessionFlags\",\n      \"plugin\",\n      \"cloudRequirements\",\n      \"cloudManagedConfig\",\n      \"legacyManagedConfigFile\",\n      \"legacyManagedConfigMdm\",\n      \"unknown\",\n    ]).annotate({ default: \"unknown\" }),\n  ),\n  sourcePath: ServerNotification__AbsolutePathBuf,\n  startedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  status: ServerNotification__HookRunStatus,\n  statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__FileSystemPath =\n  | { readonly path: ServerNotification__LegacyAppPathString; readonly type: \"path\" }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | { readonly type: \"special\"; readonly value: ServerNotification__FileSystemSpecialPath };\nexport const ServerNotification__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: ServerNotification__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: ServerNotification__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: ServerNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const ServerNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([ServerNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type ServerNotification__FileChangePatchUpdatedNotification = {\n  readonly changes: ReadonlyArray<ServerNotification__FileUpdateChange>;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__FileChangePatchUpdatedNotification = Schema.Struct({\n  changes: Schema.Array(ServerNotification__FileUpdateChange),\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__CollaborationMode = {\n  readonly mode: ServerNotification__ModeKind;\n  readonly settings: ServerNotification__Settings;\n};\nexport const ServerNotification__CollaborationMode = Schema.Struct({\n  mode: ServerNotification__ModeKind,\n  settings: ServerNotification__Settings,\n}).annotate({ description: \"Collaboration mode for a Codex session.\" });\n\nexport type ServerNotification__AccountRateLimitsUpdatedNotification = {\n  readonly rateLimits: ServerNotification__RateLimitSnapshot;\n};\nexport const ServerNotification__AccountRateLimitsUpdatedNotification = Schema.Struct({\n  rateLimits: ServerNotification__RateLimitSnapshot,\n}).annotate({\n  description:\n    \"Sparse rolling rate-limit update.\\n\\nClients should merge available values into the most recent `account/rateLimits/read` response or refetch that snapshot. Nullable account metadata may be unavailable in a rolling update and does not clear a previously observed value.\",\n});\n\nexport type ServerNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<ServerNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<ServerNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: ServerNotification__MemoryCitation | null;\n      readonly phase?: ServerNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<ServerNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: ServerNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<ServerNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: ServerNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: ServerNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: ServerNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: ServerNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: ServerNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<ServerNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: ServerNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: ServerNotification__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: ServerNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: ServerNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: ServerNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: ServerNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: ServerNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const ServerNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(ServerNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(ServerNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([ServerNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([ServerNotification__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(ServerNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: ServerNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(ServerNotification__FileUpdateChange),\n      id: Schema.String,\n      status: ServerNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([ServerNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(Schema.Union([ServerNotification__McpToolCallError, Schema.Null])),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([ServerNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: ServerNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(ServerNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: ServerNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, ServerNotification__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([ServerNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: ServerNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(Schema.Union([ServerNotification__WebSearchAction, Schema.Null])),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: ServerNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([ServerNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ConfigWarningNotification = {\n  readonly details?: string | null;\n  readonly path?: string | null;\n  readonly range?: ServerNotification__TextRange | null;\n  readonly summary: string;\n};\nexport const ServerNotification__ConfigWarningNotification = Schema.Struct({\n  details: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional extra guidance or error details.\" }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional path to the config file that triggered the warning.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  range: Schema.optionalKey(\n    Schema.Union([ServerNotification__TextRange, Schema.Null]).annotate({\n      description: \"Optional range for the error location inside the config file.\",\n    }),\n  ),\n  summary: Schema.String.annotate({ description: \"Concise summary of the warning.\" }),\n});\n\nexport type ServerNotification__ThreadStatusChangedNotification = {\n  readonly status: ServerNotification__ThreadStatus;\n  readonly threadId: string;\n};\nexport const ServerNotification__ThreadStatusChangedNotification = Schema.Struct({\n  status: ServerNotification__ThreadStatus,\n  threadId: Schema.String,\n});\n\nexport type ServerNotification__ThreadGoalUpdatedNotification = {\n  readonly goal: ServerNotification__ThreadGoal;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const ServerNotification__ThreadGoalUpdatedNotification = Schema.Struct({\n  goal: ServerNotification__ThreadGoal,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__ThreadTokenUsageUpdatedNotification = {\n  readonly threadId: string;\n  readonly tokenUsage: ServerNotification__ThreadTokenUsage;\n  readonly turnId: string;\n};\nexport const ServerNotification__ThreadTokenUsageUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  tokenUsage: ServerNotification__ThreadTokenUsage,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__TurnPlanUpdatedNotification = {\n  readonly explanation?: string | null;\n  readonly plan: ReadonlyArray<ServerNotification__TurnPlanStep>;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__TurnPlanUpdatedNotification = Schema.Struct({\n  explanation: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  plan: Schema.Array(ServerNotification__TurnPlanStep),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__FileSystemPath =\n  | { readonly path: ServerRequest__LegacyAppPathString; readonly type: \"path\" }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | { readonly type: \"special\"; readonly value: ServerRequest__FileSystemSpecialPath };\nexport const ServerRequest__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: ServerRequest__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: ServerRequest__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__McpElicitationTitledMultiSelectEnumSchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items: ServerRequest__McpElicitationTitledEnumItems;\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationArrayType;\n};\nexport const ServerRequest__McpElicitationTitledMultiSelectEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  items: ServerRequest__McpElicitationTitledEnumItems,\n  maxItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationArrayType,\n});\n\nexport type ServerRequest__McpElicitationUntitledMultiSelectEnumSchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items: ServerRequest__McpElicitationUntitledEnumItems;\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n  readonly type: ServerRequest__McpElicitationArrayType;\n};\nexport const ServerRequest__McpElicitationUntitledMultiSelectEnumSchema = Schema.Struct({\n  default: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  items: ServerRequest__McpElicitationUntitledEnumItems,\n  maxItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  type: ServerRequest__McpElicitationArrayType,\n});\n\nexport type ServerRequest__McpElicitationSingleSelectEnumSchema =\n  | ServerRequest__McpElicitationUntitledSingleSelectEnumSchema\n  | ServerRequest__McpElicitationTitledSingleSelectEnumSchema;\nexport const ServerRequest__McpElicitationSingleSelectEnumSchema = Schema.Union([\n  ServerRequest__McpElicitationUntitledSingleSelectEnumSchema,\n  ServerRequest__McpElicitationTitledSingleSelectEnumSchema,\n]);\n\nexport type ServerRequest__CommandExecutionRequestApprovalParams = {\n  readonly approvalId?: string | null;\n  readonly command?: string | null;\n  readonly commandActions?: ReadonlyArray<ServerRequest__CommandAction> | null;\n  readonly cwd?: ServerRequest__LegacyAppPathString | null;\n  readonly environmentId?: string | null;\n  readonly itemId: string;\n  readonly networkApprovalContext?: ServerRequest__NetworkApprovalContext | null;\n  readonly proposedExecpolicyAmendment?: ReadonlyArray<string> | null;\n  readonly proposedNetworkPolicyAmendments?: ReadonlyArray<ServerRequest__NetworkPolicyAmendment> | null;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__CommandExecutionRequestApprovalParams = Schema.Struct({\n  approvalId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Unique identifier for this specific approval callback.\\n\\nFor regular shell/unified_exec approvals, this is null.\\n\\nFor zsh-exec-bridge subcommand approvals, multiple callbacks can belong to one parent `itemId`, so `approvalId` is a distinct opaque callback id (a UUID) used to disambiguate routing.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  command: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"The command to be executed.\" }),\n      Schema.Null,\n    ]),\n  ),\n  commandActions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerRequest__CommandAction).annotate({\n        description: \"Best-effort parsed command actions for friendly display.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([ServerRequest__LegacyAppPathString, Schema.Null]).annotate({\n      description: \"The command's working directory.\",\n    }),\n  ),\n  environmentId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Environment in which the command will run.\" }),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  networkApprovalContext: Schema.optionalKey(\n    Schema.Union([ServerRequest__NetworkApprovalContext, Schema.Null]).annotate({\n      description: \"Optional context for a managed-network approval prompt.\",\n    }),\n  ),\n  proposedExecpolicyAmendment: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Optional proposed execpolicy amendment to allow similar commands without prompting.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  proposedNetworkPolicyAmendments: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerRequest__NetworkPolicyAmendment).annotate({\n        description:\n          \"Optional proposed network policy amendments (allow/deny host) for future requests.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for network access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__ToolRequestUserInputParams = {\n  readonly autoResolutionMs?: number | null;\n  readonly itemId: string;\n  readonly questions: ReadonlyArray<ServerRequest__ToolRequestUserInputQuestion>;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__ToolRequestUserInputParams = Schema.Struct({\n  autoResolutionMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  questions: Schema.Array(ServerRequest__ToolRequestUserInputQuestion),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ description: \"EXPERIMENTAL. Params sent with a request_user_input event.\" });\n\nexport type V2AppListUpdatedNotification__AppInfo = {\n  readonly appMetadata?: V2AppListUpdatedNotification__AppMetadata | null;\n  readonly branding?: V2AppListUpdatedNotification__AppBranding | null;\n  readonly description?: string | null;\n  readonly distributionChannel?: string | null;\n  readonly iconAssets?: { readonly [x: string]: string } | null;\n  readonly iconDarkAssets?: { readonly [x: string]: string } | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly isAccessible?: boolean;\n  readonly isEnabled?: boolean;\n  readonly labels?: { readonly [x: string]: string } | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly name: string;\n  readonly pluginDisplayNames?: ReadonlyArray<string>;\n};\nexport const V2AppListUpdatedNotification__AppInfo = Schema.Struct({\n  appMetadata: Schema.optionalKey(\n    Schema.Union([V2AppListUpdatedNotification__AppMetadata, Schema.Null]),\n  ),\n  branding: Schema.optionalKey(\n    Schema.Union([V2AppListUpdatedNotification__AppBranding, Schema.Null]),\n  ),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  iconDarkAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isEnabled: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```\",\n      default: true,\n    }),\n  ),\n  labels: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type V2AppsListResponse__AppInfo = {\n  readonly appMetadata?: V2AppsListResponse__AppMetadata | null;\n  readonly branding?: V2AppsListResponse__AppBranding | null;\n  readonly description?: string | null;\n  readonly distributionChannel?: string | null;\n  readonly iconAssets?: { readonly [x: string]: string } | null;\n  readonly iconDarkAssets?: { readonly [x: string]: string } | null;\n  readonly id: string;\n  readonly installUrl?: string | null;\n  readonly isAccessible?: boolean;\n  readonly isEnabled?: boolean;\n  readonly labels?: { readonly [x: string]: string } | null;\n  readonly logoUrl?: string | null;\n  readonly logoUrlDark?: string | null;\n  readonly name: string;\n  readonly pluginDisplayNames?: ReadonlyArray<string>;\n};\nexport const V2AppsListResponse__AppInfo = Schema.Struct({\n  appMetadata: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppMetadata, Schema.Null])),\n  branding: Schema.optionalKey(Schema.Union([V2AppsListResponse__AppBranding, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  distributionChannel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  iconAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  iconDarkAssets: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  id: Schema.String,\n  installUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  isAccessible: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  isEnabled: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```\",\n      default: true,\n    }),\n  ),\n  labels: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  logoUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  logoUrlDark: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  pluginDisplayNames: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n}).annotate({ description: \"EXPERIMENTAL - app metadata returned by app-list APIs.\" });\n\nexport type V2ConfigReadResponse__ConfigLayer = {\n  readonly config: unknown;\n  readonly disabledReason?: string | null;\n  readonly name: V2ConfigReadResponse__ConfigLayerSource;\n  readonly version: string;\n};\nexport const V2ConfigReadResponse__ConfigLayer = Schema.Struct({\n  config: Schema.Unknown,\n  disabledReason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: V2ConfigReadResponse__ConfigLayerSource,\n  version: Schema.String,\n});\n\nexport type V2ConfigReadResponse__ConfigLayerMetadata = {\n  readonly name: V2ConfigReadResponse__ConfigLayerSource;\n  readonly version: string;\n};\nexport const V2ConfigReadResponse__ConfigLayerMetadata = Schema.Struct({\n  name: V2ConfigReadResponse__ConfigLayerSource,\n  version: Schema.String,\n});\n\nexport type V2ConfigReadResponse__ToolsV2 = {\n  readonly web_search?: V2ConfigReadResponse__WebSearchToolConfig | null;\n};\nexport const V2ConfigReadResponse__ToolsV2 = Schema.Struct({\n  web_search: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__WebSearchToolConfig, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigRequirementsReadResponse__ModelsRequirements = {\n  readonly newThread?: V2ConfigRequirementsReadResponse__NewThreadModelDefaults | null;\n};\nexport const V2ConfigRequirementsReadResponse__ModelsRequirements = Schema.Struct({\n  newThread: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__NewThreadModelDefaults, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigWriteResponse__ConfigLayerMetadata = {\n  readonly name: V2ConfigWriteResponse__ConfigLayerSource;\n  readonly version: string;\n};\nexport const V2ConfigWriteResponse__ConfigLayerMetadata = Schema.Struct({\n  name: V2ConfigWriteResponse__ConfigLayerSource,\n  version: Schema.String,\n});\n\nexport type V2ErrorNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ErrorNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ErrorNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ErrorNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = {\n  readonly cwd?: string | null;\n  readonly description: string;\n  readonly details?: V2ExternalAgentConfigDetectResponse__MigrationDetails | null;\n  readonly itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType;\n};\nexport const V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Null or empty means home-scoped migration; non-empty means repo-scoped migration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String,\n  details: Schema.optionalKey(\n    Schema.Union([V2ExternalAgentConfigDetectResponse__MigrationDetails, Schema.Null]),\n  ),\n  itemType: V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItemType,\n});\n\nexport type V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportTypeResult =\n  {\n    readonly failures: ReadonlyArray<V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeFailure>;\n    readonly itemType: V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType;\n    readonly successes: ReadonlyArray<V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeSuccess>;\n  };\nexport const V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportTypeResult =\n  Schema.Struct({\n    failures: Schema.Array(\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeFailure,\n    ),\n    itemType:\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigMigrationItemType,\n    successes: Schema.Array(\n      V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportItemTypeSuccess,\n    ),\n  });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportHistory = {\n  readonly completedAtMs: number;\n  readonly failures: ReadonlyArray<V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeFailure>;\n  readonly importId: string;\n  readonly successes: ReadonlyArray<V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeSuccess>;\n};\nexport const V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportHistory =\n  Schema.Struct({\n    completedAtMs: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n    failures: Schema.Array(\n      V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeFailure,\n    ),\n    importId: Schema.String,\n    successes: Schema.Array(\n      V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportItemTypeSuccess,\n    ),\n  });\n\nexport type V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = {\n  readonly cwd?: string | null;\n  readonly description: string;\n  readonly details?: V2ExternalAgentConfigImportParams__MigrationDetails | null;\n  readonly itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType;\n};\nexport const V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Null or empty means home-scoped migration; non-empty means repo-scoped migration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String,\n  details: Schema.optionalKey(\n    Schema.Union([V2ExternalAgentConfigImportParams__MigrationDetails, Schema.Null]),\n  ),\n  itemType: V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItemType,\n});\n\nexport type V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportTypeResult = {\n  readonly failures: ReadonlyArray<V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeFailure>;\n  readonly itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType;\n  readonly successes: ReadonlyArray<V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeSuccess>;\n};\nexport const V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportTypeResult =\n  Schema.Struct({\n    failures: Schema.Array(\n      V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeFailure,\n    ),\n    itemType: V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigMigrationItemType,\n    successes: Schema.Array(\n      V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportItemTypeSuccess,\n    ),\n  });\n\nexport type V2GetAccountRateLimitsResponse__RateLimitResetCreditsSummary = {\n  readonly availableCount: number;\n  readonly credits?: ReadonlyArray<V2GetAccountRateLimitsResponse__RateLimitResetCredit> | null;\n};\nexport const V2GetAccountRateLimitsResponse__RateLimitResetCreditsSummary = Schema.Struct({\n  availableCount: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  credits: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2GetAccountRateLimitsResponse__RateLimitResetCredit).annotate({\n        description:\n          \"Detail rows for available reset credits, when the backend provides them.\\n\\n`null` means only `availableCount` is known, while an empty array means details were fetched and no available credits were returned. The backend may cap this list, so its length can be less than `availableCount`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2HookCompletedNotification__HookRunSummary = {\n  readonly completedAt?: number | null;\n  readonly displayOrder: number;\n  readonly durationMs?: number | null;\n  readonly entries: ReadonlyArray<V2HookCompletedNotification__HookOutputEntry>;\n  readonly eventName: V2HookCompletedNotification__HookEventName;\n  readonly executionMode: V2HookCompletedNotification__HookExecutionMode;\n  readonly handlerType: V2HookCompletedNotification__HookHandlerType;\n  readonly id: string;\n  readonly scope: V2HookCompletedNotification__HookScope;\n  readonly source?:\n    | \"system\"\n    | \"user\"\n    | \"project\"\n    | \"mdm\"\n    | \"sessionFlags\"\n    | \"plugin\"\n    | \"cloudRequirements\"\n    | \"cloudManagedConfig\"\n    | \"legacyManagedConfigFile\"\n    | \"legacyManagedConfigMdm\"\n    | \"unknown\";\n  readonly sourcePath: V2HookCompletedNotification__AbsolutePathBuf;\n  readonly startedAt: number;\n  readonly status: V2HookCompletedNotification__HookRunStatus;\n  readonly statusMessage?: string | null;\n};\nexport const V2HookCompletedNotification__HookRunSummary = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  displayOrder: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  durationMs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  entries: Schema.Array(V2HookCompletedNotification__HookOutputEntry),\n  eventName: V2HookCompletedNotification__HookEventName,\n  executionMode: V2HookCompletedNotification__HookExecutionMode,\n  handlerType: V2HookCompletedNotification__HookHandlerType,\n  id: Schema.String,\n  scope: V2HookCompletedNotification__HookScope,\n  source: Schema.optionalKey(\n    Schema.Literals([\n      \"system\",\n      \"user\",\n      \"project\",\n      \"mdm\",\n      \"sessionFlags\",\n      \"plugin\",\n      \"cloudRequirements\",\n      \"cloudManagedConfig\",\n      \"legacyManagedConfigFile\",\n      \"legacyManagedConfigMdm\",\n      \"unknown\",\n    ]).annotate({ default: \"unknown\" }),\n  ),\n  sourcePath: V2HookCompletedNotification__AbsolutePathBuf,\n  startedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  status: V2HookCompletedNotification__HookRunStatus,\n  statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2HooksListResponse__HooksListEntry = {\n  readonly cwd: string;\n  readonly errors: ReadonlyArray<V2HooksListResponse__HookErrorInfo>;\n  readonly hooks: ReadonlyArray<V2HooksListResponse__HookMetadata>;\n  readonly warnings: ReadonlyArray<string>;\n};\nexport const V2HooksListResponse__HooksListEntry = Schema.Struct({\n  cwd: Schema.String,\n  errors: Schema.Array(V2HooksListResponse__HookErrorInfo),\n  hooks: Schema.Array(V2HooksListResponse__HookMetadata),\n  warnings: Schema.Array(Schema.String),\n});\n\nexport type V2HookStartedNotification__HookRunSummary = {\n  readonly completedAt?: number | null;\n  readonly displayOrder: number;\n  readonly durationMs?: number | null;\n  readonly entries: ReadonlyArray<V2HookStartedNotification__HookOutputEntry>;\n  readonly eventName: V2HookStartedNotification__HookEventName;\n  readonly executionMode: V2HookStartedNotification__HookExecutionMode;\n  readonly handlerType: V2HookStartedNotification__HookHandlerType;\n  readonly id: string;\n  readonly scope: V2HookStartedNotification__HookScope;\n  readonly source?:\n    | \"system\"\n    | \"user\"\n    | \"project\"\n    | \"mdm\"\n    | \"sessionFlags\"\n    | \"plugin\"\n    | \"cloudRequirements\"\n    | \"cloudManagedConfig\"\n    | \"legacyManagedConfigFile\"\n    | \"legacyManagedConfigMdm\"\n    | \"unknown\";\n  readonly sourcePath: V2HookStartedNotification__AbsolutePathBuf;\n  readonly startedAt: number;\n  readonly status: V2HookStartedNotification__HookRunStatus;\n  readonly statusMessage?: string | null;\n};\nexport const V2HookStartedNotification__HookRunSummary = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  displayOrder: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  durationMs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  entries: Schema.Array(V2HookStartedNotification__HookOutputEntry),\n  eventName: V2HookStartedNotification__HookEventName,\n  executionMode: V2HookStartedNotification__HookExecutionMode,\n  handlerType: V2HookStartedNotification__HookHandlerType,\n  id: Schema.String,\n  scope: V2HookStartedNotification__HookScope,\n  source: Schema.optionalKey(\n    Schema.Literals([\n      \"system\",\n      \"user\",\n      \"project\",\n      \"mdm\",\n      \"sessionFlags\",\n      \"plugin\",\n      \"cloudRequirements\",\n      \"cloudManagedConfig\",\n      \"legacyManagedConfigFile\",\n      \"legacyManagedConfigMdm\",\n      \"unknown\",\n    ]).annotate({ default: \"unknown\" }),\n  ),\n  sourcePath: V2HookStartedNotification__AbsolutePathBuf,\n  startedAt: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  status: V2HookStartedNotification__HookRunStatus,\n  statusMessage: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ItemCompletedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ItemCompletedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ItemCompletedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ItemCompletedNotification__MemoryCitation | null;\n      readonly phase?: V2ItemCompletedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ItemCompletedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ItemCompletedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ItemCompletedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ItemCompletedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ItemCompletedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ItemCompletedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ItemCompletedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ItemCompletedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ItemCompletedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ItemCompletedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: {\n        readonly [x: string]: V2ItemCompletedNotification__CollabAgentState;\n      };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ItemCompletedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ItemCompletedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ItemCompletedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ItemCompletedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ItemCompletedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ItemCompletedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ItemCompletedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ItemCompletedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ItemCompletedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ItemCompletedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ItemCompletedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2ItemCompletedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ItemCompletedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ItemCompletedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ItemCompletedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ItemCompletedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ItemCompletedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ItemCompletedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ItemCompletedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath =\n  | {\n      readonly path: V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString;\n      readonly type: \"path\";\n    }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath;\n    };\nexport const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath =\n  | {\n      readonly path: V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString;\n      readonly type: \"path\";\n    }\n  | { readonly pattern: string; readonly type: \"glob_pattern\" }\n  | {\n      readonly type: \"special\";\n      readonly value: V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath;\n    };\nexport const V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath = Schema.Union(\n  [\n    Schema.Struct({\n      path: V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"path\").annotate({ title: \"PathFileSystemPathType\" }),\n    }).annotate({ title: \"PathFileSystemPath\" }),\n    Schema.Struct({\n      pattern: Schema.String,\n      type: Schema.Literal(\"glob_pattern\").annotate({ title: \"GlobPatternFileSystemPathType\" }),\n    }).annotate({ title: \"GlobPatternFileSystemPath\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"special\").annotate({ title: \"SpecialFileSystemPathType\" }),\n      value: V2ItemGuardianApprovalReviewStartedNotification__FileSystemSpecialPath,\n    }).annotate({ title: \"SpecialFileSystemPath\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ItemStartedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ItemStartedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ItemStartedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ItemStartedNotification__MemoryCitation | null;\n      readonly phase?: V2ItemStartedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ItemStartedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ItemStartedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ItemStartedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ItemStartedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ItemStartedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ItemStartedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ItemStartedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ItemStartedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ItemStartedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ItemStartedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ItemStartedNotification__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ItemStartedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ItemStartedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ItemStartedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ItemStartedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ItemStartedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ItemStartedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ItemStartedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ItemStartedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ItemStartedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ItemStartedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ItemStartedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2ItemStartedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ItemStartedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ItemStartedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ItemStartedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ItemStartedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ItemStartedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ItemStartedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ItemStartedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ModelListResponse__Model = {\n  readonly additionalSpeedTiers?: ReadonlyArray<string>;\n  readonly availabilityNux?: V2ModelListResponse__ModelAvailabilityNux | null;\n  readonly defaultReasoningEffort: V2ModelListResponse__ReasoningEffort;\n  readonly defaultServiceTier?: string | null;\n  readonly description: string;\n  readonly displayName: string;\n  readonly hidden: boolean;\n  readonly id: string;\n  readonly inputModalities?: ReadonlyArray<V2ModelListResponse__InputModality>;\n  readonly isDefault: boolean;\n  readonly model: string;\n  readonly serviceTiers?: ReadonlyArray<V2ModelListResponse__ModelServiceTier>;\n  readonly supportedReasoningEfforts: ReadonlyArray<V2ModelListResponse__ReasoningEffortOption>;\n  readonly supportsPersonality?: boolean;\n  readonly upgrade?: string | null;\n  readonly upgradeInfo?: V2ModelListResponse__ModelUpgradeInfo | null;\n};\nexport const V2ModelListResponse__Model = Schema.Struct({\n  additionalSpeedTiers: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"Deprecated: use `serviceTiers` instead.\",\n      default: [],\n    }),\n  ),\n  availabilityNux: Schema.optionalKey(\n    Schema.Union([V2ModelListResponse__ModelAvailabilityNux, Schema.Null]),\n  ),\n  defaultReasoningEffort: V2ModelListResponse__ReasoningEffort,\n  defaultServiceTier: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Catalog default service tier id for this model, when one is configured.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String,\n  displayName: Schema.String,\n  hidden: Schema.Boolean,\n  id: Schema.String,\n  inputModalities: Schema.optionalKey(\n    Schema.Array(V2ModelListResponse__InputModality).annotate({ default: [\"text\", \"image\"] }),\n  ),\n  isDefault: Schema.Boolean,\n  model: Schema.String,\n  serviceTiers: Schema.optionalKey(\n    Schema.Array(V2ModelListResponse__ModelServiceTier).annotate({ default: [] }),\n  ),\n  supportedReasoningEfforts: Schema.Array(V2ModelListResponse__ReasoningEffortOption),\n  supportsPersonality: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n  upgrade: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  upgradeInfo: Schema.optionalKey(\n    Schema.Union([V2ModelListResponse__ModelUpgradeInfo, Schema.Null]),\n  ),\n});\n\nexport type V2PluginInstalledResponse__PluginShareContext = {\n  readonly creatorAccountUserId?: string | null;\n  readonly creatorName?: string | null;\n  readonly discoverability?: V2PluginInstalledResponse__PluginShareDiscoverability | null;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n  readonly sharePrincipals?: ReadonlyArray<V2PluginInstalledResponse__PluginSharePrincipal> | null;\n  readonly shareUrl?: string | null;\n};\nexport const V2PluginInstalledResponse__PluginShareContext = Schema.Struct({\n  creatorAccountUserId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  creatorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__PluginShareDiscoverability, Schema.Null]),\n  ),\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the remote shared plugin release when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sharePrincipals: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginInstalledResponse__PluginSharePrincipal), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginListResponse__PluginShareContext = {\n  readonly creatorAccountUserId?: string | null;\n  readonly creatorName?: string | null;\n  readonly discoverability?: V2PluginListResponse__PluginShareDiscoverability | null;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n  readonly sharePrincipals?: ReadonlyArray<V2PluginListResponse__PluginSharePrincipal> | null;\n  readonly shareUrl?: string | null;\n};\nexport const V2PluginListResponse__PluginShareContext = Schema.Struct({\n  creatorAccountUserId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  creatorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__PluginShareDiscoverability, Schema.Null]),\n  ),\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the remote shared plugin release when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sharePrincipals: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginListResponse__PluginSharePrincipal), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__SkillSummary = {\n  readonly description: string;\n  readonly enabled: boolean;\n  readonly interface?: V2PluginReadResponse__SkillInterface | null;\n  readonly name: string;\n  readonly path?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly shortDescription?: string | null;\n};\nexport const V2PluginReadResponse__SkillSummary = Schema.Struct({\n  description: Schema.String,\n  enabled: Schema.Boolean,\n  interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__SkillInterface, Schema.Null])),\n  name: Schema.String,\n  path: Schema.optionalKey(Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null])),\n  shortDescription: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__PluginShareContext = {\n  readonly creatorAccountUserId?: string | null;\n  readonly creatorName?: string | null;\n  readonly discoverability?: V2PluginReadResponse__PluginShareDiscoverability | null;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n  readonly sharePrincipals?: ReadonlyArray<V2PluginReadResponse__PluginSharePrincipal> | null;\n  readonly shareUrl?: string | null;\n};\nexport const V2PluginReadResponse__PluginShareContext = Schema.Struct({\n  creatorAccountUserId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  creatorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__PluginShareDiscoverability, Schema.Null]),\n  ),\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the remote shared plugin release when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sharePrincipals: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginReadResponse__PluginSharePrincipal), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2PluginReadResponse__ScheduledTaskSummary = {\n  readonly key: string;\n  readonly name: string;\n  readonly prompt: string;\n  readonly schedule: V2PluginReadResponse__ScheduledTaskSchedule;\n};\nexport const V2PluginReadResponse__ScheduledTaskSummary = Schema.Struct({\n  key: Schema.String,\n  name: Schema.String,\n  prompt: Schema.String,\n  schedule: V2PluginReadResponse__ScheduledTaskSchedule,\n});\n\nexport type V2PluginShareListResponse__PluginShareContext = {\n  readonly creatorAccountUserId?: string | null;\n  readonly creatorName?: string | null;\n  readonly discoverability?: V2PluginShareListResponse__PluginShareDiscoverability | null;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n  readonly sharePrincipals?: ReadonlyArray<V2PluginShareListResponse__PluginSharePrincipal> | null;\n  readonly shareUrl?: string | null;\n};\nexport const V2PluginShareListResponse__PluginShareContext = Schema.Struct({\n  creatorAccountUserId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  creatorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__PluginShareDiscoverability, Schema.Null]),\n  ),\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the remote shared plugin release when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sharePrincipals: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginShareListResponse__PluginSharePrincipal), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2RawResponseItemCompletedNotification__FunctionCallOutputBody =\n  | string\n  | ReadonlyArray<V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem>;\nexport const V2RawResponseItemCompletedNotification__FunctionCallOutputBody = Schema.Union([\n  Schema.String,\n  Schema.Array(V2RawResponseItemCompletedNotification__FunctionCallOutputContentItem),\n]);\n\nexport type V2ReviewStartResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ReviewStartResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ReviewStartResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ReviewStartResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ReviewStartResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ReviewStartResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ReviewStartResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ReviewStartResponse__MemoryCitation | null;\n      readonly phase?: V2ReviewStartResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ReviewStartResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ReviewStartResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ReviewStartResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ReviewStartResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ReviewStartResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ReviewStartResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ReviewStartResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ReviewStartResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ReviewStartResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ReviewStartResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ReviewStartResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ReviewStartResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ReviewStartResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ReviewStartResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ReviewStartResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ReviewStartResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ReviewStartResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ReviewStartResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ReviewStartResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ReviewStartResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ReviewStartResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ReviewStartResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ReviewStartResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ReviewStartResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ReviewStartResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ReviewStartResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ReviewStartResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ReviewStartResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ReviewStartResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ReviewStartResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ReviewStartResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2SkillsListResponse__SkillMetadata = {\n  readonly dependencies?: V2SkillsListResponse__SkillDependencies | null;\n  readonly description: string;\n  readonly enabled: boolean;\n  readonly interface?: V2SkillsListResponse__SkillInterface | null;\n  readonly name: string;\n  readonly path: V2SkillsListResponse__AbsolutePathBuf;\n  readonly scope: V2SkillsListResponse__SkillScope;\n  readonly shortDescription?: string | null;\n};\nexport const V2SkillsListResponse__SkillMetadata = Schema.Struct({\n  dependencies: Schema.optionalKey(\n    Schema.Union([V2SkillsListResponse__SkillDependencies, Schema.Null]),\n  ),\n  description: Schema.String,\n  enabled: Schema.Boolean,\n  interface: Schema.optionalKey(Schema.Union([V2SkillsListResponse__SkillInterface, Schema.Null])),\n  name: Schema.String,\n  path: V2SkillsListResponse__AbsolutePathBuf,\n  scope: V2SkillsListResponse__SkillScope,\n  shortDescription: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Legacy short_description from SKILL.md. Prefer SKILL.json interface.short_description.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadForkResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadForkResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadForkResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadForkResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadForkResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadForkResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadForkResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadForkResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadForkResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadForkResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadForkResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadForkResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadForkResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadForkResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadForkResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadForkResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadForkResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadForkResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadForkResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadForkResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadForkResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadForkResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadForkResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadForkResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadForkResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadForkResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadForkResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadForkResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadForkResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadForkResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadForkResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadForkResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadForkResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadForkResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadForkResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadForkResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadForkResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadForkResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadForkResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadListResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadListResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadListResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadListResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadListResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadListResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadListResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadListResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadListResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadListResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadListResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadListResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadListResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadListResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadListResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadListResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadListResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadListResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadListResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadListResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadListResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadListResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadListResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadListResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadListResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadListResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadListResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadListResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadListResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadListResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadListResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadListResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadListResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadListResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadListResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadListResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadListResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadListResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadListResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadMetadataUpdateResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadMetadataUpdateResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadMetadataUpdateResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadMetadataUpdateResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadMetadataUpdateResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadMetadataUpdateResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadMetadataUpdateResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadMetadataUpdateResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadMetadataUpdateResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadMetadataUpdateResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadMetadataUpdateResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadMetadataUpdateResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadMetadataUpdateResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadMetadataUpdateResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadMetadataUpdateResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadMetadataUpdateResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: {\n        readonly [x: string]: V2ThreadMetadataUpdateResponse__CollabAgentState;\n      };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadMetadataUpdateResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadMetadataUpdateResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadMetadataUpdateResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadMetadataUpdateResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadMetadataUpdateResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadMetadataUpdateResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadMetadataUpdateResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadMetadataUpdateResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadMetadataUpdateResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadMetadataUpdateResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadMetadataUpdateResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadMetadataUpdateResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadMetadataUpdateResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadMetadataUpdateResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadMetadataUpdateResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ThreadMetadataUpdateResponse__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadMetadataUpdateResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadMetadataUpdateResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadMetadataUpdateResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadReadResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadReadResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadReadResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadReadResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadReadResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadReadResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadReadResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadReadResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadReadResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadReadResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadReadResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadReadResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadReadResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadReadResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadReadResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadReadResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadReadResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadReadResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadReadResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadReadResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadReadResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadReadResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadReadResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadReadResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadReadResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadReadResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadReadResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadReadResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadReadResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadReadResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadReadResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadReadResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadReadResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadReadResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadReadResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadReadResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadReadResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadReadResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadReadResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__FunctionCallOutputBody =\n  | string\n  | ReadonlyArray<V2ThreadResumeParams__FunctionCallOutputContentItem>;\nexport const V2ThreadResumeParams__FunctionCallOutputBody = Schema.Union([\n  Schema.String,\n  Schema.Array(V2ThreadResumeParams__FunctionCallOutputContentItem),\n]);\n\nexport type V2ThreadResumeResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadResumeResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadResumeResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadResumeResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadResumeResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadResumeResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadResumeResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadResumeResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadResumeResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadResumeResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadResumeResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadResumeResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadResumeResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadResumeResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadResumeResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadResumeResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadResumeResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadResumeResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadResumeResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadResumeResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadResumeResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadResumeResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadResumeResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadResumeResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadResumeResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadResumeResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadResumeResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadResumeResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadResumeResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadResumeResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadResumeResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadResumeResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadResumeResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadResumeResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadResumeResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadResumeResponse__CollabAgentState).annotate(\n        { description: \"Last known status of the target agents, when available.\" },\n      ),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadResumeResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadResumeResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadRollbackResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadRollbackResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadRollbackResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadRollbackResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadRollbackResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadRollbackResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadRollbackResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadRollbackResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadRollbackResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadRollbackResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadRollbackResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadRollbackResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadRollbackResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadRollbackResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadRollbackResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadRollbackResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadRollbackResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadRollbackResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadRollbackResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadRollbackResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadRollbackResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadRollbackResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadRollbackResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadRollbackResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadRollbackResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadRollbackResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadRollbackResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadRollbackResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadRollbackResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadRollbackResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadRollbackResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadRollbackResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadRollbackResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadRollbackResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ThreadRollbackResponse__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadRollbackResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadRollbackResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadRollbackResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadSettingsUpdatedNotification__CollaborationMode = {\n  readonly mode: V2ThreadSettingsUpdatedNotification__ModeKind;\n  readonly settings: V2ThreadSettingsUpdatedNotification__Settings;\n};\nexport const V2ThreadSettingsUpdatedNotification__CollaborationMode = Schema.Struct({\n  mode: V2ThreadSettingsUpdatedNotification__ModeKind,\n  settings: V2ThreadSettingsUpdatedNotification__Settings,\n}).annotate({ description: \"Collaboration mode for a Codex session.\" });\n\nexport type V2ThreadStartedNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadStartedNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadStartedNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadStartedNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadStartedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadStartedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadStartedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadStartedNotification__MemoryCitation | null;\n      readonly phase?: V2ThreadStartedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadStartedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadStartedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadStartedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadStartedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadStartedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadStartedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadStartedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadStartedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadStartedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadStartedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: {\n        readonly [x: string]: V2ThreadStartedNotification__CollabAgentState;\n      };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadStartedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadStartedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadStartedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadStartedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadStartedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadStartedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadStartedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadStartedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadStartedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadStartedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadStartedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadStartedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadStartedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadStartedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadStartedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ThreadStartedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadStartedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadStartedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadStartedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadStartResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadStartResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadStartResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadStartResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadStartResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadStartResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadStartResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadStartResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadStartResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadStartResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadStartResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadStartResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadStartResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadStartResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadStartResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadStartResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadStartResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadStartResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadStartResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadStartResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadStartResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadStartResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadStartResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadStartResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadStartResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadStartResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadStartResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadStartResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadStartResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadStartResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadStartResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadStartResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadStartResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadStartResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2ThreadStartResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadStartResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadStartResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadStartResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2ThreadUnarchiveResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2ThreadUnarchiveResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadUnarchiveResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2ThreadUnarchiveResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2ThreadUnarchiveResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2ThreadUnarchiveResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2ThreadUnarchiveResponse__MemoryCitation | null;\n      readonly phase?: V2ThreadUnarchiveResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2ThreadUnarchiveResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2ThreadUnarchiveResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2ThreadUnarchiveResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2ThreadUnarchiveResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2ThreadUnarchiveResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2ThreadUnarchiveResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2ThreadUnarchiveResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2ThreadUnarchiveResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2ThreadUnarchiveResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2ThreadUnarchiveResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2ThreadUnarchiveResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2ThreadUnarchiveResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2ThreadUnarchiveResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2ThreadUnarchiveResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2ThreadUnarchiveResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2ThreadUnarchiveResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2ThreadUnarchiveResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2ThreadUnarchiveResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2ThreadUnarchiveResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2ThreadUnarchiveResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2ThreadUnarchiveResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2ThreadUnarchiveResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2ThreadUnarchiveResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2ThreadUnarchiveResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2ThreadUnarchiveResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2ThreadUnarchiveResponse__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2ThreadUnarchiveResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2ThreadUnarchiveResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2ThreadUnarchiveResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnCompletedNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2TurnCompletedNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2TurnCompletedNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2TurnCompletedNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2TurnCompletedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2TurnCompletedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2TurnCompletedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2TurnCompletedNotification__MemoryCitation | null;\n      readonly phase?: V2TurnCompletedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2TurnCompletedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2TurnCompletedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2TurnCompletedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2TurnCompletedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2TurnCompletedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2TurnCompletedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2TurnCompletedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2TurnCompletedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2TurnCompletedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2TurnCompletedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: {\n        readonly [x: string]: V2TurnCompletedNotification__CollabAgentState;\n      };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2TurnCompletedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2TurnCompletedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2TurnCompletedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2TurnCompletedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2TurnCompletedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2TurnCompletedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2TurnCompletedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2TurnCompletedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2TurnCompletedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2TurnCompletedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2TurnCompletedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2TurnCompletedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2TurnCompletedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2TurnCompletedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2TurnCompletedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2TurnCompletedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2TurnCompletedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2TurnCompletedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2TurnCompletedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartedNotification__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2TurnStartedNotification__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2TurnStartedNotification__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2TurnStartedNotification__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2TurnStartedNotification__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2TurnStartedNotification__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2TurnStartedNotification__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2TurnStartedNotification__MemoryCitation | null;\n      readonly phase?: V2TurnStartedNotification__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2TurnStartedNotification__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2TurnStartedNotification__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2TurnStartedNotification__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2TurnStartedNotification__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2TurnStartedNotification__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2TurnStartedNotification__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2TurnStartedNotification__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2TurnStartedNotification__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2TurnStartedNotification__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2TurnStartedNotification__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2TurnStartedNotification__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2TurnStartedNotification__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2TurnStartedNotification__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2TurnStartedNotification__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2TurnStartedNotification__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2TurnStartedNotification__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2TurnStartedNotification__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2TurnStartedNotification__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2TurnStartedNotification__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__MessagePhase, Schema.Null]),\n      ),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2TurnStartedNotification__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2TurnStartedNotification__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2TurnStartedNotification__FileUpdateChange),\n      id: Schema.String,\n      status: V2TurnStartedNotification__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__McpToolCallError, Schema.Null]),\n      ),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2TurnStartedNotification__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2TurnStartedNotification__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2TurnStartedNotification__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(\n        Schema.String,\n        V2TurnStartedNotification__CollabAgentState,\n      ).annotate({ description: \"Last known status of the target agents, when available.\" }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2TurnStartedNotification__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__WebSearchAction, Schema.Null]),\n      ),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2TurnStartedNotification__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2TurnStartedNotification__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2TurnStartResponse__TurnError = {\n  readonly additionalDetails?: string | null;\n  readonly codexErrorInfo?: V2TurnStartResponse__CodexErrorInfo | null;\n  readonly message: string;\n};\nexport const V2TurnStartResponse__TurnError = Schema.Struct({\n  additionalDetails: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  codexErrorInfo: Schema.optionalKey(\n    Schema.Union([V2TurnStartResponse__CodexErrorInfo, Schema.Null]),\n  ),\n  message: Schema.String,\n});\n\nexport type V2TurnStartResponse__ThreadItem =\n  | {\n      readonly clientId?: string | null;\n      readonly content: ReadonlyArray<V2TurnStartResponse__UserInput>;\n      readonly id: string;\n      readonly type: \"userMessage\";\n    }\n  | {\n      readonly fragments: ReadonlyArray<V2TurnStartResponse__HookPromptFragment>;\n      readonly id: string;\n      readonly type: \"hookPrompt\";\n    }\n  | {\n      readonly id: string;\n      readonly memoryCitation?: V2TurnStartResponse__MemoryCitation | null;\n      readonly phase?: V2TurnStartResponse__MessagePhase | null;\n      readonly text: string;\n      readonly type: \"agentMessage\";\n    }\n  | { readonly id: string; readonly text: string; readonly type: \"plan\" }\n  | {\n      readonly content?: ReadonlyArray<string>;\n      readonly id: string;\n      readonly summary?: ReadonlyArray<string>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly aggregatedOutput?: string | null;\n      readonly command: string;\n      readonly commandActions: ReadonlyArray<V2TurnStartResponse__CommandAction>;\n      readonly cwd: string;\n      readonly durationMs?: number | null;\n      readonly exitCode?: number | null;\n      readonly id: string;\n      readonly processId?: string | null;\n      readonly source?: \"agent\" | \"userShell\" | \"unifiedExecStartup\" | \"unifiedExecInteraction\";\n      readonly status: V2TurnStartResponse__CommandExecutionStatus;\n      readonly type: \"commandExecution\";\n    }\n  | {\n      readonly changes: ReadonlyArray<V2TurnStartResponse__FileUpdateChange>;\n      readonly id: string;\n      readonly status: V2TurnStartResponse__PatchApplyStatus;\n      readonly type: \"fileChange\";\n    }\n  | {\n      readonly appContext?: V2TurnStartResponse__McpToolCallAppContext | null;\n      readonly arguments: unknown;\n      readonly durationMs?: number | null;\n      readonly error?: V2TurnStartResponse__McpToolCallError | null;\n      readonly id: string;\n      readonly mcpAppResourceUri?: string | null;\n      readonly pluginId?: string | null;\n      readonly result?: V2TurnStartResponse__McpToolCallResult | null;\n      readonly server: string;\n      readonly status: V2TurnStartResponse__McpToolCallStatus;\n      readonly tool: string;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly contentItems?: ReadonlyArray<V2TurnStartResponse__DynamicToolCallOutputContentItem> | null;\n      readonly durationMs?: number | null;\n      readonly id: string;\n      readonly namespace?: string | null;\n      readonly status: V2TurnStartResponse__DynamicToolCallStatus;\n      readonly success?: boolean | null;\n      readonly tool: string;\n      readonly type: \"dynamicToolCall\";\n    }\n  | {\n      readonly agentsStates: { readonly [x: string]: V2TurnStartResponse__CollabAgentState };\n      readonly id: string;\n      readonly model?: string | null;\n      readonly prompt?: string | null;\n      readonly reasoningEffort?: V2TurnStartResponse__ReasoningEffort | null;\n      readonly receiverThreadIds: ReadonlyArray<string>;\n      readonly senderThreadId: string;\n      readonly status: \"inProgress\" | \"completed\" | \"failed\";\n      readonly tool: \"spawnAgent\" | \"sendInput\" | \"resumeAgent\" | \"wait\" | \"closeAgent\";\n      readonly type: \"collabAgentToolCall\";\n    }\n  | {\n      readonly agentPath: string;\n      readonly agentThreadId: string;\n      readonly id: string;\n      readonly kind: V2TurnStartResponse__SubAgentActivityKind;\n      readonly type: \"subAgentActivity\";\n    }\n  | {\n      readonly action?: V2TurnStartResponse__WebSearchAction | null;\n      readonly id: string;\n      readonly query: string;\n      readonly results?: ReadonlyArray<unknown> | null;\n      readonly type: \"webSearch\";\n    }\n  | {\n      readonly id: string;\n      readonly path: V2TurnStartResponse__LegacyAppPathString;\n      readonly type: \"imageView\";\n    }\n  | { readonly durationMs: number; readonly id: string; readonly type: \"sleep\" }\n  | {\n      readonly id: string;\n      readonly result: string;\n      readonly revisedPrompt?: string | null;\n      readonly savedPath?: V2TurnStartResponse__AbsolutePathBuf | null;\n      readonly status: string;\n      readonly type: \"imageGeneration\";\n    }\n  | { readonly id: string; readonly review: string; readonly type: \"enteredReviewMode\" }\n  | { readonly id: string; readonly review: string; readonly type: \"exitedReviewMode\" }\n  | { readonly id: string; readonly type: \"contextCompaction\" };\nexport const V2TurnStartResponse__ThreadItem = Schema.Union(\n  [\n    Schema.Struct({\n      clientId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      content: Schema.Array(V2TurnStartResponse__UserInput),\n      id: Schema.String,\n      type: Schema.Literal(\"userMessage\").annotate({ title: \"UserMessageThreadItemType\" }),\n    }).annotate({ title: \"UserMessageThreadItem\" }),\n    Schema.Struct({\n      fragments: Schema.Array(V2TurnStartResponse__HookPromptFragment),\n      id: Schema.String,\n      type: Schema.Literal(\"hookPrompt\").annotate({ title: \"HookPromptThreadItemType\" }),\n    }).annotate({ title: \"HookPromptThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      memoryCitation: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__MemoryCitation, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2TurnStartResponse__MessagePhase, Schema.Null])),\n      text: Schema.String,\n      type: Schema.Literal(\"agentMessage\").annotate({ title: \"AgentMessageThreadItemType\" }),\n    }).annotate({ title: \"AgentMessageThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      text: Schema.String,\n      type: Schema.Literal(\"plan\").annotate({ title: \"PlanThreadItemType\" }),\n    }).annotate({\n      title: \"PlanThreadItem\",\n      description:\n        \"EXPERIMENTAL - proposed plan item content. The completed plan item is authoritative and may not match the concatenation of `PlanDelta` text.\",\n    }),\n    Schema.Struct({\n      content: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      id: Schema.String,\n      summary: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningThreadItemType\" }),\n    }).annotate({ title: \"ReasoningThreadItem\" }),\n    Schema.Struct({\n      aggregatedOutput: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"The command's output, aggregated from stdout and stderr.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      command: Schema.String.annotate({ description: \"The command to be executed.\" }),\n      commandActions: Schema.Array(V2TurnStartResponse__CommandAction).annotate({\n        description:\n          \"A best-effort parsing of the command to understand the action(s) it will perform. This returns a list of CommandAction objects because a single shell command may be composed of many commands piped together.\",\n      }),\n      cwd: Schema.String.annotate({ description: \"The command's working directory.\" }),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the command execution in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      exitCode: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The command's exit code.\",\n            format: \"int32\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      processId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Identifier for the underlying PTY process (when available).\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      source: Schema.optionalKey(\n        Schema.Literals([\n          \"agent\",\n          \"userShell\",\n          \"unifiedExecStartup\",\n          \"unifiedExecInteraction\",\n        ]).annotate({ default: \"agent\" }),\n      ),\n      status: V2TurnStartResponse__CommandExecutionStatus,\n      type: Schema.Literal(\"commandExecution\").annotate({\n        title: \"CommandExecutionThreadItemType\",\n      }),\n    }).annotate({ title: \"CommandExecutionThreadItem\" }),\n    Schema.Struct({\n      changes: Schema.Array(V2TurnStartResponse__FileUpdateChange),\n      id: Schema.String,\n      status: V2TurnStartResponse__PatchApplyStatus,\n      type: Schema.Literal(\"fileChange\").annotate({ title: \"FileChangeThreadItemType\" }),\n    }).annotate({ title: \"FileChangeThreadItem\" }),\n    Schema.Struct({\n      appContext: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__McpToolCallAppContext, Schema.Null]),\n      ),\n      arguments: Schema.Unknown,\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the MCP tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      error: Schema.optionalKey(Schema.Union([V2TurnStartResponse__McpToolCallError, Schema.Null])),\n      id: Schema.String,\n      mcpAppResourceUri: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Deprecated: use `appContext.resourceUri` instead.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      result: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__McpToolCallResult, Schema.Null]),\n      ),\n      server: Schema.String,\n      status: V2TurnStartResponse__McpToolCallStatus,\n      tool: Schema.String,\n      type: Schema.Literal(\"mcpToolCall\").annotate({ title: \"McpToolCallThreadItemType\" }),\n    }).annotate({ title: \"McpToolCallThreadItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      contentItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2TurnStartResponse__DynamicToolCallOutputContentItem),\n          Schema.Null,\n        ]),\n      ),\n      durationMs: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"The duration of the dynamic tool call in milliseconds.\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: V2TurnStartResponse__DynamicToolCallStatus,\n      success: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n      tool: Schema.String,\n      type: Schema.Literal(\"dynamicToolCall\").annotate({ title: \"DynamicToolCallThreadItemType\" }),\n    }).annotate({ title: \"DynamicToolCallThreadItem\" }),\n    Schema.Struct({\n      agentsStates: Schema.Record(Schema.String, V2TurnStartResponse__CollabAgentState).annotate({\n        description: \"Last known status of the target agents, when available.\",\n      }),\n      id: Schema.String.annotate({ description: \"Unique identifier for this collab tool call.\" }),\n      model: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Model requested for the spawned agent, when applicable.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      prompt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Prompt text sent as part of the collab tool call, when available.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      reasoningEffort: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__ReasoningEffort, Schema.Null]).annotate({\n          description: \"Reasoning effort requested for the spawned agent, when applicable.\",\n        }),\n      ),\n      receiverThreadIds: Schema.Array(Schema.String).annotate({\n        description:\n          \"Thread ID of the receiving agent, when applicable. In case of spawn operation, this corresponds to the newly spawned agent.\",\n      }),\n      senderThreadId: Schema.String.annotate({\n        description: \"Thread ID of the agent issuing the collab request.\",\n      }),\n      status: Schema.Literals([\"inProgress\", \"completed\", \"failed\"]).annotate({\n        description: \"Current status of the collab tool call.\",\n      }),\n      tool: Schema.Literals([\n        \"spawnAgent\",\n        \"sendInput\",\n        \"resumeAgent\",\n        \"wait\",\n        \"closeAgent\",\n      ]).annotate({ description: \"Name of the collab tool that was invoked.\" }),\n      type: Schema.Literal(\"collabAgentToolCall\").annotate({\n        title: \"CollabAgentToolCallThreadItemType\",\n      }),\n    }).annotate({ title: \"CollabAgentToolCallThreadItem\" }),\n    Schema.Struct({\n      agentPath: Schema.String,\n      agentThreadId: Schema.String,\n      id: Schema.String,\n      kind: V2TurnStartResponse__SubAgentActivityKind,\n      type: Schema.Literal(\"subAgentActivity\").annotate({\n        title: \"SubAgentActivityThreadItemType\",\n      }),\n    }).annotate({ title: \"SubAgentActivityThreadItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(Schema.Union([V2TurnStartResponse__WebSearchAction, Schema.Null])),\n      id: Schema.String,\n      query: Schema.String,\n      results: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.Unknown).annotate({\n            description:\n              \"Structured search results returned out-of-band by standalone web search.\\n\\nThese stay as opaque JSON at the extension/app-server boundary so new result fields and result types can pass through without a Codex release.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"webSearch\").annotate({ title: \"WebSearchThreadItemType\" }),\n    }).annotate({ title: \"WebSearchThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      path: V2TurnStartResponse__LegacyAppPathString,\n      type: Schema.Literal(\"imageView\").annotate({ title: \"ImageViewThreadItemType\" }),\n    }).annotate({ title: \"ImageViewThreadItem\" }),\n    Schema.Struct({\n      durationMs: Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      id: Schema.String,\n      type: Schema.Literal(\"sleep\").annotate({ title: \"SleepThreadItemType\" }),\n    }).annotate({\n      title: \"SleepThreadItem\",\n      description: \"Display item emitted by the interruptible `clock.sleep` tool.\",\n    }),\n    Schema.Struct({\n      id: Schema.String,\n      result: Schema.String,\n      revisedPrompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      savedPath: Schema.optionalKey(\n        Schema.Union([V2TurnStartResponse__AbsolutePathBuf, Schema.Null]),\n      ),\n      status: Schema.String,\n      type: Schema.Literal(\"imageGeneration\").annotate({ title: \"ImageGenerationThreadItemType\" }),\n    }).annotate({ title: \"ImageGenerationThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"enteredReviewMode\").annotate({\n        title: \"EnteredReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"EnteredReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      review: Schema.String,\n      type: Schema.Literal(\"exitedReviewMode\").annotate({\n        title: \"ExitedReviewModeThreadItemType\",\n      }),\n    }).annotate({ title: \"ExitedReviewModeThreadItem\" }),\n    Schema.Struct({\n      id: Schema.String,\n      type: Schema.Literal(\"contextCompaction\").annotate({\n        title: \"ContextCompactionThreadItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionThreadItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__ExternalAgentConfigImportParams = {\n  readonly migrationItems: ReadonlyArray<ClientRequest__ExternalAgentConfigMigrationItem>;\n  readonly migrationSource?: string | null;\n  readonly source?: string | null;\n};\nexport const ClientRequest__ExternalAgentConfigImportParams = Schema.Struct({\n  migrationItems: Schema.Array(ClientRequest__ExternalAgentConfigMigrationItem),\n  migrationSource: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Migration-source selector used to produce the migration items. Pass the same value to detection and import; missing or unrecognized values use the default source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  source: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional identifier for the product that initiated the import.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type CommandExecutionRequestApprovalParams__FileSystemSandboxEntry = {\n  readonly access: CommandExecutionRequestApprovalParams__FileSystemAccessMode;\n  readonly path: CommandExecutionRequestApprovalParams__FileSystemPath;\n};\nexport const CommandExecutionRequestApprovalParams__FileSystemSandboxEntry = Schema.Struct({\n  access: CommandExecutionRequestApprovalParams__FileSystemAccessMode,\n  path: CommandExecutionRequestApprovalParams__FileSystemPath,\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema =\n  | McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema;\nexport const McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema = Schema.Union([\n  McpServerElicitationRequestParams__McpElicitationUntitledMultiSelectEnumSchema,\n  McpServerElicitationRequestParams__McpElicitationTitledMultiSelectEnumSchema,\n]);\n\nexport type PermissionsRequestApprovalParams__FileSystemSandboxEntry = {\n  readonly access: PermissionsRequestApprovalParams__FileSystemAccessMode;\n  readonly path: PermissionsRequestApprovalParams__FileSystemPath;\n};\nexport const PermissionsRequestApprovalParams__FileSystemSandboxEntry = Schema.Struct({\n  access: PermissionsRequestApprovalParams__FileSystemAccessMode,\n  path: PermissionsRequestApprovalParams__FileSystemPath,\n});\n\nexport type PermissionsRequestApprovalResponse__FileSystemSandboxEntry = {\n  readonly access: PermissionsRequestApprovalResponse__FileSystemAccessMode;\n  readonly path: PermissionsRequestApprovalResponse__FileSystemPath;\n};\nexport const PermissionsRequestApprovalResponse__FileSystemSandboxEntry = Schema.Struct({\n  access: PermissionsRequestApprovalResponse__FileSystemAccessMode,\n  path: PermissionsRequestApprovalResponse__FileSystemPath,\n});\n\nexport type ServerNotification__AppListUpdatedNotification = {\n  readonly data: ReadonlyArray<ServerNotification__AppInfo>;\n};\nexport const ServerNotification__AppListUpdatedNotification = Schema.Struct({\n  data: Schema.Array(ServerNotification__AppInfo),\n}).annotate({ description: \"EXPERIMENTAL - notification emitted when the app list changes.\" });\n\nexport type ServerNotification__ExternalAgentConfigImportCompletedNotification = {\n  readonly importId: string;\n  readonly itemTypeResults: ReadonlyArray<ServerNotification__ExternalAgentConfigImportTypeResult>;\n};\nexport const ServerNotification__ExternalAgentConfigImportCompletedNotification = Schema.Struct({\n  importId: Schema.String,\n  itemTypeResults: Schema.Array(ServerNotification__ExternalAgentConfigImportTypeResult),\n});\n\nexport type ServerNotification__ExternalAgentConfigImportProgressNotification = {\n  readonly importId: string;\n  readonly itemTypeResults: ReadonlyArray<ServerNotification__ExternalAgentConfigImportTypeResult>;\n};\nexport const ServerNotification__ExternalAgentConfigImportProgressNotification = Schema.Struct({\n  importId: Schema.String,\n  itemTypeResults: Schema.Array(ServerNotification__ExternalAgentConfigImportTypeResult),\n});\n\nexport type ServerNotification__HookCompletedNotification = {\n  readonly run: ServerNotification__HookRunSummary;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const ServerNotification__HookCompletedNotification = Schema.Struct({\n  run: ServerNotification__HookRunSummary,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__HookStartedNotification = {\n  readonly run: ServerNotification__HookRunSummary;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const ServerNotification__HookStartedNotification = Schema.Struct({\n  run: ServerNotification__HookRunSummary,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type ServerNotification__FileSystemSandboxEntry = {\n  readonly access: ServerNotification__FileSystemAccessMode;\n  readonly path: ServerNotification__FileSystemPath;\n};\nexport const ServerNotification__FileSystemSandboxEntry = Schema.Struct({\n  access: ServerNotification__FileSystemAccessMode,\n  path: ServerNotification__FileSystemPath,\n});\n\nexport type ServerNotification__ErrorNotification = {\n  readonly error: ServerNotification__TurnError;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly willRetry: boolean;\n};\nexport const ServerNotification__ErrorNotification = Schema.Struct({\n  error: ServerNotification__TurnError,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  willRetry: Schema.Boolean,\n});\n\nexport type ServerNotification__ThreadSettings = {\n  readonly activePermissionProfile?: ServerNotification__ActivePermissionProfile | null;\n  readonly approvalPolicy: ServerNotification__AskForApproval;\n  readonly approvalsReviewer: ServerNotification__ApprovalsReviewer;\n  readonly collaborationMode: ServerNotification__CollaborationMode;\n  readonly cwd: ServerNotification__AbsolutePathBuf;\n  readonly effort?: ServerNotification__ReasoningEffort | null;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly personality?: ServerNotification__Personality | null;\n  readonly sandboxPolicy: ServerNotification__SandboxPolicy;\n  readonly serviceTier?: string | null;\n  readonly summary?: ServerNotification__ReasoningSummary | null;\n};\nexport const ServerNotification__ThreadSettings = Schema.Struct({\n  activePermissionProfile: Schema.optionalKey(\n    Schema.Union([ServerNotification__ActivePermissionProfile, Schema.Null]),\n  ),\n  approvalPolicy: ServerNotification__AskForApproval,\n  approvalsReviewer: ServerNotification__ApprovalsReviewer,\n  collaborationMode: ServerNotification__CollaborationMode,\n  cwd: ServerNotification__AbsolutePathBuf,\n  effort: Schema.optionalKey(Schema.Union([ServerNotification__ReasoningEffort, Schema.Null])),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  personality: Schema.optionalKey(Schema.Union([ServerNotification__Personality, Schema.Null])),\n  sandboxPolicy: ServerNotification__SandboxPolicy,\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  summary: Schema.optionalKey(Schema.Union([ServerNotification__ReasoningSummary, Schema.Null])),\n});\n\nexport type ServerNotification__ItemCompletedNotification = {\n  readonly completedAtMs: number;\n  readonly item: ServerNotification__ThreadItem;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ItemCompletedNotification = Schema.Struct({\n  completedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this item lifecycle completed.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  item: ServerNotification__ThreadItem,\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__ItemStartedNotification = {\n  readonly item: ServerNotification__ThreadItem;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ItemStartedNotification = Schema.Struct({\n  item: ServerNotification__ThreadItem,\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this item lifecycle started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerNotification__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: ServerNotification__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<ServerNotification__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: ServerNotification__TurnStatus;\n};\nexport const ServerNotification__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([ServerNotification__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(ServerNotification__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: ServerNotification__TurnStatus,\n});\n\nexport type ServerRequest__FileSystemSandboxEntry = {\n  readonly access: ServerRequest__FileSystemAccessMode;\n  readonly path: ServerRequest__FileSystemPath;\n};\nexport const ServerRequest__FileSystemSandboxEntry = Schema.Struct({\n  access: ServerRequest__FileSystemAccessMode,\n  path: ServerRequest__FileSystemPath,\n});\n\nexport type ServerRequest__McpElicitationMultiSelectEnumSchema =\n  | ServerRequest__McpElicitationUntitledMultiSelectEnumSchema\n  | ServerRequest__McpElicitationTitledMultiSelectEnumSchema;\nexport const ServerRequest__McpElicitationMultiSelectEnumSchema = Schema.Union([\n  ServerRequest__McpElicitationUntitledMultiSelectEnumSchema,\n  ServerRequest__McpElicitationTitledMultiSelectEnumSchema,\n]);\n\nexport type V2ConfigReadResponse__Config = {\n  readonly analytics?: V2ConfigReadResponse__AnalyticsConfig | null;\n  readonly approval_policy?: V2ConfigReadResponse__AskForApproval | null;\n  readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null;\n  readonly compact_prompt?: string | null;\n  readonly desktop?: { readonly [x: string]: unknown } | null;\n  readonly developer_instructions?: string | null;\n  readonly forced_chatgpt_workspace_id?: V2ConfigReadResponse__ForcedChatgptWorkspaceIds | null;\n  readonly forced_login_method?: V2ConfigReadResponse__ForcedLoginMethod | null;\n  readonly instructions?: string | null;\n  readonly model?: string | null;\n  readonly model_auto_compact_token_limit?: number | null;\n  readonly model_auto_compact_token_limit_scope?: V2ConfigReadResponse__AutoCompactTokenLimitScope | null;\n  readonly model_context_window?: number | null;\n  readonly model_provider?: string | null;\n  readonly model_reasoning_effort?: V2ConfigReadResponse__ReasoningEffort | null;\n  readonly model_reasoning_summary?: V2ConfigReadResponse__ReasoningSummary | null;\n  readonly model_verbosity?: V2ConfigReadResponse__Verbosity | null;\n  readonly review_model?: string | null;\n  readonly sandbox_mode?: V2ConfigReadResponse__SandboxMode | null;\n  readonly sandbox_workspace_write?: V2ConfigReadResponse__SandboxWorkspaceWrite | null;\n  readonly service_tier?: string | null;\n  readonly tools?: V2ConfigReadResponse__ToolsV2 | null;\n  readonly web_search?: V2ConfigReadResponse__WebSearchMode | null;\n  readonly [x: string]: unknown;\n};\nexport const V2ConfigReadResponse__Config = Schema.StructWithRest(\n  Schema.Struct({\n    analytics: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__AnalyticsConfig, Schema.Null]),\n    ),\n    approval_policy: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__AskForApproval, Schema.Null]),\n    ),\n    approvals_reviewer: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]).annotate({\n        description:\n          \"[UNSTABLE] Optional default for where approval requests are routed for review.\",\n      }),\n    ),\n    compact_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    desktop: Schema.optionalKey(\n      Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n    ),\n    developer_instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    forced_chatgpt_workspace_id: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ForcedChatgptWorkspaceIds, Schema.Null]),\n    ),\n    forced_login_method: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ForcedLoginMethod, Schema.Null]),\n    ),\n    instructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    model_auto_compact_token_limit: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n        Schema.Null,\n      ]),\n    ),\n    model_auto_compact_token_limit_scope: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__AutoCompactTokenLimitScope, Schema.Null]),\n    ),\n    model_context_window: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n        Schema.Null,\n      ]),\n    ),\n    model_provider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    model_reasoning_effort: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ReasoningEffort, Schema.Null]),\n    ),\n    model_reasoning_summary: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__ReasoningSummary, Schema.Null]),\n    ),\n    model_verbosity: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__Verbosity, Schema.Null]),\n    ),\n    review_model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    sandbox_mode: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__SandboxMode, Schema.Null]),\n    ),\n    sandbox_workspace_write: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__SandboxWorkspaceWrite, Schema.Null]),\n    ),\n    service_tier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__ToolsV2, Schema.Null])),\n    web_search: Schema.optionalKey(\n      Schema.Union([V2ConfigReadResponse__WebSearchMode, Schema.Null]),\n    ),\n  }),\n  [Schema.Record(Schema.String, Schema.Unknown)],\n);\n\nexport type V2ConfigRequirementsReadResponse__ConfigRequirements = {\n  readonly allowAppshots?: boolean | null;\n  readonly allowManagedHooksOnly?: boolean | null;\n  readonly allowRemoteControl?: boolean | null;\n  readonly allowedApprovalPolicies?: ReadonlyArray<V2ConfigRequirementsReadResponse__AskForApproval> | null;\n  readonly allowedPermissionProfiles?: { readonly [x: string]: boolean } | null;\n  readonly allowedSandboxModes?: ReadonlyArray<V2ConfigRequirementsReadResponse__SandboxMode> | null;\n  readonly allowedWebSearchModes?: ReadonlyArray<V2ConfigRequirementsReadResponse__WebSearchMode> | null;\n  readonly allowedWindowsSandboxImplementations?: ReadonlyArray<V2ConfigRequirementsReadResponse__WindowsSandboxSetupMode> | null;\n  readonly computerUse?: V2ConfigRequirementsReadResponse__ComputerUseRequirements | null;\n  readonly defaultPermissions?: string | null;\n  readonly enforceResidency?: V2ConfigRequirementsReadResponse__ResidencyRequirement | null;\n  readonly featureRequirements?: { readonly [x: string]: boolean } | null;\n  readonly models?: V2ConfigRequirementsReadResponse__ModelsRequirements | null;\n};\nexport const V2ConfigRequirementsReadResponse__ConfigRequirements = Schema.Struct({\n  allowAppshots: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowManagedHooksOnly: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowRemoteControl: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowedApprovalPolicies: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__AskForApproval), Schema.Null]),\n  ),\n  allowedPermissionProfiles: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Boolean), Schema.Null]),\n  ),\n  allowedSandboxModes: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__SandboxMode), Schema.Null]),\n  ),\n  allowedWebSearchModes: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2ConfigRequirementsReadResponse__WebSearchMode), Schema.Null]),\n  ),\n  allowedWindowsSandboxImplementations: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2ConfigRequirementsReadResponse__WindowsSandboxSetupMode),\n      Schema.Null,\n    ]),\n  ),\n  computerUse: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ComputerUseRequirements, Schema.Null]),\n  ),\n  defaultPermissions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  enforceResidency: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ResidencyRequirement, Schema.Null]),\n  ),\n  featureRequirements: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Boolean), Schema.Null]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ModelsRequirements, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigWriteResponse__OverriddenMetadata = {\n  readonly effectiveValue: unknown;\n  readonly message: string;\n  readonly overridingLayer: V2ConfigWriteResponse__ConfigLayerMetadata;\n};\nexport const V2ConfigWriteResponse__OverriddenMetadata = Schema.Struct({\n  effectiveValue: Schema.Unknown,\n  message: Schema.String,\n  overridingLayer: V2ConfigWriteResponse__ConfigLayerMetadata,\n});\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry = {\n  readonly access: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode;\n  readonly path: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry =\n  Schema.Struct({\n    access: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemAccessMode,\n    path: V2ItemGuardianApprovalReviewCompletedNotification__FileSystemPath,\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry = {\n  readonly access: V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode;\n  readonly path: V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry =\n  Schema.Struct({\n    access: V2ItemGuardianApprovalReviewStartedNotification__FileSystemAccessMode,\n    path: V2ItemGuardianApprovalReviewStartedNotification__FileSystemPath,\n  });\n\nexport type V2PluginInstalledResponse__PluginSummary = {\n  readonly authPolicy: V2PluginInstalledResponse__PluginAuthPolicy;\n  readonly availability?: \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly installPolicy: V2PluginInstalledResponse__PluginInstallPolicy;\n  readonly installPolicySource?: V2PluginInstalledResponse__PluginInstallPolicySource | null;\n  readonly installed: boolean;\n  readonly interface?: V2PluginInstalledResponse__PluginInterface | null;\n  readonly keywords?: ReadonlyArray<string>;\n  readonly localVersion?: string | null;\n  readonly mustShowInstallationInterstitial?: boolean | null;\n  readonly name: string;\n  readonly remotePluginId?: string | null;\n  readonly shareContext?: V2PluginInstalledResponse__PluginShareContext | null;\n  readonly source: V2PluginInstalledResponse__PluginSource;\n  readonly version?: string | null;\n};\nexport const V2PluginInstalledResponse__PluginSummary = Schema.Struct({\n  authPolicy: V2PluginInstalledResponse__PluginAuthPolicy,\n  availability: Schema.optionalKey(\n    Schema.Literals([\"DISABLED_BY_ADMIN\", \"AVAILABLE\"]).annotate({\n      description: \"Availability state for installing and using the plugin.\",\n      default: \"AVAILABLE\",\n    }),\n  ),\n  enabled: Schema.Boolean,\n  id: Schema.String,\n  installPolicy: V2PluginInstalledResponse__PluginInstallPolicy,\n  installPolicySource: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__PluginInstallPolicySource, Schema.Null]),\n  ),\n  installed: Schema.Boolean,\n  interface: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__PluginInterface, Schema.Null]),\n  ),\n  keywords: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  localVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the locally materialized plugin package when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mustShowInstallationInterstitial: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  name: Schema.String,\n  remotePluginId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Backend remote plugin identifier when available.\" }),\n      Schema.Null,\n    ]),\n  ),\n  shareContext: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__PluginShareContext, Schema.Null]).annotate({\n      description: \"Remote sharing context associated with this plugin when available.\",\n    }),\n  ),\n  source: V2PluginInstalledResponse__PluginSource,\n  version: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version advertised by the remote marketplace backend when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2PluginListResponse__PluginSummary = {\n  readonly authPolicy: V2PluginListResponse__PluginAuthPolicy;\n  readonly availability?: \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly installPolicy: V2PluginListResponse__PluginInstallPolicy;\n  readonly installPolicySource?: V2PluginListResponse__PluginInstallPolicySource | null;\n  readonly installed: boolean;\n  readonly interface?: V2PluginListResponse__PluginInterface | null;\n  readonly keywords?: ReadonlyArray<string>;\n  readonly localVersion?: string | null;\n  readonly mustShowInstallationInterstitial?: boolean | null;\n  readonly name: string;\n  readonly remotePluginId?: string | null;\n  readonly shareContext?: V2PluginListResponse__PluginShareContext | null;\n  readonly source: V2PluginListResponse__PluginSource;\n  readonly version?: string | null;\n};\nexport const V2PluginListResponse__PluginSummary = Schema.Struct({\n  authPolicy: V2PluginListResponse__PluginAuthPolicy,\n  availability: Schema.optionalKey(\n    Schema.Literals([\"DISABLED_BY_ADMIN\", \"AVAILABLE\"]).annotate({\n      description: \"Availability state for installing and using the plugin.\",\n      default: \"AVAILABLE\",\n    }),\n  ),\n  enabled: Schema.Boolean,\n  id: Schema.String,\n  installPolicy: V2PluginListResponse__PluginInstallPolicy,\n  installPolicySource: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__PluginInstallPolicySource, Schema.Null]),\n  ),\n  installed: Schema.Boolean,\n  interface: Schema.optionalKey(Schema.Union([V2PluginListResponse__PluginInterface, Schema.Null])),\n  keywords: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  localVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the locally materialized plugin package when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mustShowInstallationInterstitial: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  name: Schema.String,\n  remotePluginId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Backend remote plugin identifier when available.\" }),\n      Schema.Null,\n    ]),\n  ),\n  shareContext: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__PluginShareContext, Schema.Null]).annotate({\n      description: \"Remote sharing context associated with this plugin when available.\",\n    }),\n  ),\n  source: V2PluginListResponse__PluginSource,\n  version: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version advertised by the remote marketplace backend when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2PluginReadResponse__PluginSummary = {\n  readonly authPolicy: V2PluginReadResponse__PluginAuthPolicy;\n  readonly availability?: \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly installPolicy: V2PluginReadResponse__PluginInstallPolicy;\n  readonly installPolicySource?: V2PluginReadResponse__PluginInstallPolicySource | null;\n  readonly installed: boolean;\n  readonly interface?: V2PluginReadResponse__PluginInterface | null;\n  readonly keywords?: ReadonlyArray<string>;\n  readonly localVersion?: string | null;\n  readonly mustShowInstallationInterstitial?: boolean | null;\n  readonly name: string;\n  readonly remotePluginId?: string | null;\n  readonly shareContext?: V2PluginReadResponse__PluginShareContext | null;\n  readonly source: V2PluginReadResponse__PluginSource;\n  readonly version?: string | null;\n};\nexport const V2PluginReadResponse__PluginSummary = Schema.Struct({\n  authPolicy: V2PluginReadResponse__PluginAuthPolicy,\n  availability: Schema.optionalKey(\n    Schema.Literals([\"DISABLED_BY_ADMIN\", \"AVAILABLE\"]).annotate({\n      description: \"Availability state for installing and using the plugin.\",\n      default: \"AVAILABLE\",\n    }),\n  ),\n  enabled: Schema.Boolean,\n  id: Schema.String,\n  installPolicy: V2PluginReadResponse__PluginInstallPolicy,\n  installPolicySource: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__PluginInstallPolicySource, Schema.Null]),\n  ),\n  installed: Schema.Boolean,\n  interface: Schema.optionalKey(Schema.Union([V2PluginReadResponse__PluginInterface, Schema.Null])),\n  keywords: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  localVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the locally materialized plugin package when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mustShowInstallationInterstitial: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  name: Schema.String,\n  remotePluginId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Backend remote plugin identifier when available.\" }),\n      Schema.Null,\n    ]),\n  ),\n  shareContext: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__PluginShareContext, Schema.Null]).annotate({\n      description: \"Remote sharing context associated with this plugin when available.\",\n    }),\n  ),\n  source: V2PluginReadResponse__PluginSource,\n  version: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version advertised by the remote marketplace backend when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2PluginShareListResponse__PluginSummary = {\n  readonly authPolicy: V2PluginShareListResponse__PluginAuthPolicy;\n  readonly availability?: \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\n  readonly enabled: boolean;\n  readonly id: string;\n  readonly installPolicy: V2PluginShareListResponse__PluginInstallPolicy;\n  readonly installPolicySource?: V2PluginShareListResponse__PluginInstallPolicySource | null;\n  readonly installed: boolean;\n  readonly interface?: V2PluginShareListResponse__PluginInterface | null;\n  readonly keywords?: ReadonlyArray<string>;\n  readonly localVersion?: string | null;\n  readonly mustShowInstallationInterstitial?: boolean | null;\n  readonly name: string;\n  readonly remotePluginId?: string | null;\n  readonly shareContext?: V2PluginShareListResponse__PluginShareContext | null;\n  readonly source: V2PluginShareListResponse__PluginSource;\n  readonly version?: string | null;\n};\nexport const V2PluginShareListResponse__PluginSummary = Schema.Struct({\n  authPolicy: V2PluginShareListResponse__PluginAuthPolicy,\n  availability: Schema.optionalKey(\n    Schema.Literals([\"DISABLED_BY_ADMIN\", \"AVAILABLE\"]).annotate({\n      description: \"Availability state for installing and using the plugin.\",\n      default: \"AVAILABLE\",\n    }),\n  ),\n  enabled: Schema.Boolean,\n  id: Schema.String,\n  installPolicy: V2PluginShareListResponse__PluginInstallPolicy,\n  installPolicySource: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__PluginInstallPolicySource, Schema.Null]),\n  ),\n  installed: Schema.Boolean,\n  interface: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__PluginInterface, Schema.Null]),\n  ),\n  keywords: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  localVersion: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version of the locally materialized plugin package when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mustShowInstallationInterstitial: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  name: Schema.String,\n  remotePluginId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Backend remote plugin identifier when available.\" }),\n      Schema.Null,\n    ]),\n  ),\n  shareContext: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__PluginShareContext, Schema.Null]).annotate({\n      description: \"Remote sharing context associated with this plugin when available.\",\n    }),\n  ),\n  source: V2PluginShareListResponse__PluginSource,\n  version: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Version advertised by the remote marketplace backend when available.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2RawResponseItemCompletedNotification__ResponseItem =\n  | {\n      readonly content: ReadonlyArray<V2RawResponseItemCompletedNotification__ContentItem>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly phase?: V2RawResponseItemCompletedNotification__MessagePhase | null;\n      readonly role: string;\n      readonly type: \"message\";\n    }\n  | {\n      readonly author: string;\n      readonly content: ReadonlyArray<V2RawResponseItemCompletedNotification__AgentMessageInputContent>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly recipient: string;\n      readonly type: \"agent_message\";\n    }\n  | {\n      readonly content?: ReadonlyArray<V2RawResponseItemCompletedNotification__ReasoningItemContent> | null;\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly summary: ReadonlyArray<V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly action: V2RawResponseItemCompletedNotification__LocalShellAction;\n      readonly call_id?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly status: V2RawResponseItemCompletedNotification__LocalShellStatus;\n      readonly type: \"local_shell_call\";\n    }\n  | {\n      readonly arguments: string;\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly type: \"function_call\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"tool_search_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody;\n      readonly type: \"function_call_output\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly input: string;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly status?: string | null;\n      readonly type: \"custom_tool_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly name?: string | null;\n      readonly output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody;\n      readonly type: \"custom_tool_call_output\";\n    }\n  | {\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly status: string;\n      readonly tools: ReadonlyArray<unknown>;\n      readonly type: \"tool_search_output\";\n    }\n  | {\n      readonly action?: V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"web_search_call\";\n    }\n  | {\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly result: string;\n      readonly revised_prompt?: string | null;\n      readonly status: string;\n      readonly type: \"image_generation_call\";\n    }\n  | {\n      readonly encrypted_content: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"compaction\";\n    }\n  | { readonly type: \"compaction_trigger\" }\n  | {\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"context_compaction\";\n    }\n  | { readonly type: \"other\" };\nexport const V2RawResponseItemCompletedNotification__ResponseItem = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.Array(V2RawResponseItemCompletedNotification__ContentItem),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      phase: Schema.optionalKey(\n        Schema.Union([V2RawResponseItemCompletedNotification__MessagePhase, Schema.Null]),\n      ),\n      role: Schema.String,\n      type: Schema.Literal(\"message\").annotate({ title: \"MessageResponseItemType\" }),\n    }).annotate({ title: \"MessageResponseItem\" }),\n    Schema.Struct({\n      author: Schema.String,\n      content: Schema.Array(V2RawResponseItemCompletedNotification__AgentMessageInputContent),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      recipient: Schema.String,\n      type: Schema.Literal(\"agent_message\").annotate({ title: \"AgentMessageResponseItemType\" }),\n    }).annotate({ title: \"AgentMessageResponseItem\" }),\n    Schema.Struct({\n      content: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(V2RawResponseItemCompletedNotification__ReasoningItemContent),\n          Schema.Null,\n        ]),\n      ),\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      summary: Schema.Array(V2RawResponseItemCompletedNotification__ReasoningItemReasoningSummary),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningResponseItemType\" }),\n    }).annotate({ title: \"ReasoningResponseItem\" }),\n    Schema.Struct({\n      action: V2RawResponseItemCompletedNotification__LocalShellAction,\n      call_id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Set when using the Responses API.\" }),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Legacy id field retained for compatibility with older payloads.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      status: V2RawResponseItemCompletedNotification__LocalShellStatus,\n      type: Schema.Literal(\"local_shell_call\").annotate({\n        title: \"LocalShellCallResponseItemType\",\n      }),\n    }).annotate({ title: \"LocalShellCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.String,\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"function_call\").annotate({ title: \"FunctionCallResponseItemType\" }),\n    }).annotate({ title: \"FunctionCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"tool_search_call\").annotate({\n        title: \"ToolSearchCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody,\n      type: Schema.Literal(\"function_call_output\").annotate({\n        title: \"FunctionCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"FunctionCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      input: Schema.String,\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"custom_tool_call\").annotate({\n        title: \"CustomToolCallResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      output: V2RawResponseItemCompletedNotification__FunctionCallOutputBody,\n      type: Schema.Literal(\"custom_tool_call_output\").annotate({\n        title: \"CustomToolCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      status: Schema.String,\n      tools: Schema.Array(Schema.Unknown),\n      type: Schema.Literal(\"tool_search_output\").annotate({\n        title: \"ToolSearchOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchOutputResponseItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__ResponsesApiWebSearchAction,\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"web_search_call\").annotate({ title: \"WebSearchCallResponseItemType\" }),\n    }).annotate({ title: \"WebSearchCallResponseItem\" }),\n    Schema.Struct({\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      result: Schema.String,\n      revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.String,\n      type: Schema.Literal(\"image_generation_call\").annotate({\n        title: \"ImageGenerationCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ImageGenerationCallResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"compaction\").annotate({ title: \"CompactionResponseItemType\" }),\n    }).annotate({ title: \"CompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"compaction_trigger\").annotate({\n        title: \"CompactionTriggerResponseItemType\",\n      }),\n    }).annotate({ title: \"CompactionTriggerResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([\n          V2RawResponseItemCompletedNotification__InternalChatMessageMetadataPassthrough,\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"context_compaction\").annotate({\n        title: \"ContextCompactionResponseItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponseItemType\" }),\n    }).annotate({ title: \"OtherResponseItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ReviewStartResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ReviewStartResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ReviewStartResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ReviewStartResponse__TurnStatus;\n};\nexport const V2ReviewStartResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ReviewStartResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ReviewStartResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ReviewStartResponse__TurnStatus,\n});\n\nexport type V2SkillsListResponse__SkillsListEntry = {\n  readonly cwd: string;\n  readonly errors: ReadonlyArray<V2SkillsListResponse__SkillErrorInfo>;\n  readonly skills: ReadonlyArray<V2SkillsListResponse__SkillMetadata>;\n};\nexport const V2SkillsListResponse__SkillsListEntry = Schema.Struct({\n  cwd: Schema.String,\n  errors: Schema.Array(V2SkillsListResponse__SkillErrorInfo),\n  skills: Schema.Array(V2SkillsListResponse__SkillMetadata),\n});\n\nexport type V2ThreadForkResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadForkResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadForkResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadForkResponse__TurnStatus;\n};\nexport const V2ThreadForkResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadForkResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadForkResponse__TurnStatus,\n});\n\nexport type V2ThreadListResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadListResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadListResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadListResponse__TurnStatus;\n};\nexport const V2ThreadListResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadListResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadListResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadListResponse__TurnStatus,\n});\n\nexport type V2ThreadMetadataUpdateResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadMetadataUpdateResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadMetadataUpdateResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadMetadataUpdateResponse__TurnStatus;\n};\nexport const V2ThreadMetadataUpdateResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadMetadataUpdateResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadMetadataUpdateResponse__TurnStatus,\n});\n\nexport type V2ThreadReadResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadReadResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadReadResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadReadResponse__TurnStatus;\n};\nexport const V2ThreadReadResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadReadResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadReadResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadReadResponse__TurnStatus,\n});\n\nexport type V2ThreadResumeResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadResumeResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadResumeResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadResumeResponse__TurnStatus;\n};\nexport const V2ThreadResumeResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadResumeResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadResumeResponse__TurnStatus,\n});\n\nexport type V2ThreadRollbackResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadRollbackResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadRollbackResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadRollbackResponse__TurnStatus;\n};\nexport const V2ThreadRollbackResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadRollbackResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadRollbackResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadRollbackResponse__TurnStatus,\n});\n\nexport type V2ThreadSettingsUpdatedNotification__ThreadSettings = {\n  readonly activePermissionProfile?: V2ThreadSettingsUpdatedNotification__ActivePermissionProfile | null;\n  readonly approvalPolicy: V2ThreadSettingsUpdatedNotification__AskForApproval;\n  readonly approvalsReviewer: V2ThreadSettingsUpdatedNotification__ApprovalsReviewer;\n  readonly collaborationMode: V2ThreadSettingsUpdatedNotification__CollaborationMode;\n  readonly cwd: V2ThreadSettingsUpdatedNotification__AbsolutePathBuf;\n  readonly effort?: V2ThreadSettingsUpdatedNotification__ReasoningEffort | null;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly personality?: V2ThreadSettingsUpdatedNotification__Personality | null;\n  readonly sandboxPolicy: V2ThreadSettingsUpdatedNotification__SandboxPolicy;\n  readonly serviceTier?: string | null;\n  readonly summary?: V2ThreadSettingsUpdatedNotification__ReasoningSummary | null;\n};\nexport const V2ThreadSettingsUpdatedNotification__ThreadSettings = Schema.Struct({\n  activePermissionProfile: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__ActivePermissionProfile, Schema.Null]),\n  ),\n  approvalPolicy: V2ThreadSettingsUpdatedNotification__AskForApproval,\n  approvalsReviewer: V2ThreadSettingsUpdatedNotification__ApprovalsReviewer,\n  collaborationMode: V2ThreadSettingsUpdatedNotification__CollaborationMode,\n  cwd: V2ThreadSettingsUpdatedNotification__AbsolutePathBuf,\n  effort: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__ReasoningEffort, Schema.Null]),\n  ),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  personality: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__Personality, Schema.Null]),\n  ),\n  sandboxPolicy: V2ThreadSettingsUpdatedNotification__SandboxPolicy,\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  summary: Schema.optionalKey(\n    Schema.Union([V2ThreadSettingsUpdatedNotification__ReasoningSummary, Schema.Null]),\n  ),\n});\n\nexport type V2ThreadStartedNotification__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadStartedNotification__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadStartedNotification__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadStartedNotification__TurnStatus;\n};\nexport const V2ThreadStartedNotification__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadStartedNotification__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadStartedNotification__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadStartedNotification__TurnStatus,\n});\n\nexport type V2ThreadStartResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadStartResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadStartResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadStartResponse__TurnStatus;\n};\nexport const V2ThreadStartResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadStartResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadStartResponse__TurnStatus,\n});\n\nexport type V2ThreadUnarchiveResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2ThreadUnarchiveResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2ThreadUnarchiveResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2ThreadUnarchiveResponse__TurnStatus;\n};\nexport const V2ThreadUnarchiveResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2ThreadUnarchiveResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2ThreadUnarchiveResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2ThreadUnarchiveResponse__TurnStatus,\n});\n\nexport type V2TurnCompletedNotification__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2TurnCompletedNotification__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2TurnCompletedNotification__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2TurnCompletedNotification__TurnStatus;\n};\nexport const V2TurnCompletedNotification__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2TurnCompletedNotification__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2TurnCompletedNotification__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2TurnCompletedNotification__TurnStatus,\n});\n\nexport type V2TurnStartedNotification__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2TurnStartedNotification__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2TurnStartedNotification__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2TurnStartedNotification__TurnStatus;\n};\nexport const V2TurnStartedNotification__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2TurnStartedNotification__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2TurnStartedNotification__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2TurnStartedNotification__TurnStatus,\n});\n\nexport type V2TurnStartResponse__Turn = {\n  readonly completedAt?: number | null;\n  readonly durationMs?: number | null;\n  readonly error?: V2TurnStartResponse__TurnError | null;\n  readonly id: string;\n  readonly items: ReadonlyArray<V2TurnStartResponse__ThreadItem>;\n  readonly itemsView?: \"notLoaded\" | \"summary\" | \"full\";\n  readonly startedAt?: number | null;\n  readonly status: V2TurnStartResponse__TurnStatus;\n};\nexport const V2TurnStartResponse__Turn = Schema.Struct({\n  completedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn completed.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  durationMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Duration between turn start and completion in milliseconds, if known.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  error: Schema.optionalKey(\n    Schema.Union([V2TurnStartResponse__TurnError, Schema.Null]).annotate({\n      description: \"Only populated when the Turn's status is failed.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this turn. Codex-generated turn IDs are UUIDv7.\",\n  }),\n  items: Schema.Array(V2TurnStartResponse__ThreadItem).annotate({\n    description: \"Thread items currently included in this turn payload.\",\n  }),\n  itemsView: Schema.optionalKey(\n    Schema.Literals([\"notLoaded\", \"summary\", \"full\"]).annotate({\n      description: \"Describes how much of `items` has been loaded for this turn.\",\n      default: \"full\",\n    }),\n  ),\n  startedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) when the turn started.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  status: V2TurnStartResponse__TurnStatus,\n});\n\nexport type CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<CommandExecutionRequestApprovalParams__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<CommandExecutionRequestApprovalParams__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<CommandExecutionRequestApprovalParams__LegacyAppPathString> | null;\n};\nexport const CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct(\n  {\n    entries: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(CommandExecutionRequestApprovalParams__FileSystemSandboxEntry),\n        Schema.Null,\n      ]),\n    ),\n    globScanMaxDepth: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(1)),\n        Schema.Null,\n      ]),\n    ),\n    read: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(CommandExecutionRequestApprovalParams__LegacyAppPathString).annotate({\n          description: \"This will be removed in favor of `entries`.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    write: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(CommandExecutionRequestApprovalParams__LegacyAppPathString).annotate({\n          description: \"This will be removed in favor of `entries`.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n  },\n);\n\nexport type McpServerElicitationRequestParams__McpElicitationEnumSchema =\n  | McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema;\nexport const McpServerElicitationRequestParams__McpElicitationEnumSchema = Schema.Union([\n  McpServerElicitationRequestParams__McpElicitationSingleSelectEnumSchema,\n  McpServerElicitationRequestParams__McpElicitationMultiSelectEnumSchema,\n  McpServerElicitationRequestParams__McpElicitationLegacyTitledEnumSchema,\n]);\n\nexport type PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<PermissionsRequestApprovalParams__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<PermissionsRequestApprovalParams__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<PermissionsRequestApprovalParams__LegacyAppPathString> | null;\n};\nexport const PermissionsRequestApprovalParams__AdditionalFileSystemPermissions = Schema.Struct({\n  entries: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalParams__FileSystemSandboxEntry),\n      Schema.Null,\n    ]),\n  ),\n  globScanMaxDepth: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(1)),\n      Schema.Null,\n    ]),\n  ),\n  read: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalParams__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  write: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalParams__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<PermissionsRequestApprovalResponse__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<PermissionsRequestApprovalResponse__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<PermissionsRequestApprovalResponse__LegacyAppPathString> | null;\n};\nexport const PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions = Schema.Struct({\n  entries: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalResponse__FileSystemSandboxEntry),\n      Schema.Null,\n    ]),\n  ),\n  globScanMaxDepth: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(1)),\n      Schema.Null,\n    ]),\n  ),\n  read: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalResponse__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  write: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(PermissionsRequestApprovalResponse__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<ServerNotification__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<ServerNotification__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<ServerNotification__LegacyAppPathString> | null;\n};\nexport const ServerNotification__AdditionalFileSystemPermissions = Schema.Struct({\n  entries: Schema.optionalKey(\n    Schema.Union([Schema.Array(ServerNotification__FileSystemSandboxEntry), Schema.Null]),\n  ),\n  globScanMaxDepth: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(1)),\n      Schema.Null,\n    ]),\n  ),\n  read: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerNotification__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  write: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerNotification__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerNotification__ThreadSettingsUpdatedNotification = {\n  readonly threadId: string;\n  readonly threadSettings: ServerNotification__ThreadSettings;\n};\nexport const ServerNotification__ThreadSettingsUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  threadSettings: ServerNotification__ThreadSettings,\n});\n\nexport type ServerNotification__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: ServerNotification__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: ServerNotification__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<ServerNotification__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: ServerNotification__ThreadSource | null;\n  readonly turns: ReadonlyArray<ServerNotification__Turn>;\n  readonly updatedAt: number;\n};\nexport const ServerNotification__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([ServerNotification__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: ServerNotification__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(ServerNotification__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([ServerNotification__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(ServerNotification__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type ServerNotification__TurnCompletedNotification = {\n  readonly threadId: string;\n  readonly turn: ServerNotification__Turn;\n};\nexport const ServerNotification__TurnCompletedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turn: ServerNotification__Turn,\n});\n\nexport type ServerNotification__TurnStartedNotification = {\n  readonly threadId: string;\n  readonly turn: ServerNotification__Turn;\n};\nexport const ServerNotification__TurnStartedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turn: ServerNotification__Turn,\n});\n\nexport type ServerRequest__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<ServerRequest__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<ServerRequest__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<ServerRequest__LegacyAppPathString> | null;\n};\nexport const ServerRequest__AdditionalFileSystemPermissions = Schema.Struct({\n  entries: Schema.optionalKey(\n    Schema.Union([Schema.Array(ServerRequest__FileSystemSandboxEntry), Schema.Null]),\n  ),\n  globScanMaxDepth: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(1)),\n      Schema.Null,\n    ]),\n  ),\n  read: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerRequest__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  write: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ServerRequest__LegacyAppPathString).annotate({\n        description: \"This will be removed in favor of `entries`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ServerRequest__McpElicitationEnumSchema =\n  | ServerRequest__McpElicitationSingleSelectEnumSchema\n  | ServerRequest__McpElicitationMultiSelectEnumSchema\n  | ServerRequest__McpElicitationLegacyTitledEnumSchema;\nexport const ServerRequest__McpElicitationEnumSchema = Schema.Union([\n  ServerRequest__McpElicitationSingleSelectEnumSchema,\n  ServerRequest__McpElicitationMultiSelectEnumSchema,\n  ServerRequest__McpElicitationLegacyTitledEnumSchema,\n]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString> | null;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions =\n  Schema.Struct({\n    entries: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(V2ItemGuardianApprovalReviewCompletedNotification__FileSystemSandboxEntry),\n        Schema.Null,\n      ]),\n    ),\n    globScanMaxDepth: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(1)),\n        Schema.Null,\n      ]),\n    ),\n    read: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(\n          V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n        ).annotate({ description: \"This will be removed in favor of `entries`.\" }),\n        Schema.Null,\n      ]),\n    ),\n    write: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(\n          V2ItemGuardianApprovalReviewCompletedNotification__LegacyAppPathString,\n        ).annotate({ description: \"This will be removed in favor of `entries`.\" }),\n        Schema.Null,\n      ]),\n    ),\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions = {\n  readonly entries?: ReadonlyArray<V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry> | null;\n  readonly globScanMaxDepth?: number | null;\n  readonly read?: ReadonlyArray<V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString> | null;\n  readonly write?: ReadonlyArray<V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString> | null;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions =\n  Schema.Struct({\n    entries: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__FileSystemSandboxEntry),\n        Schema.Null,\n      ]),\n    ),\n    globScanMaxDepth: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({ format: \"uint\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(1)),\n        Schema.Null,\n      ]),\n    ),\n    read: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString).annotate(\n          { description: \"This will be removed in favor of `entries`.\" },\n        ),\n        Schema.Null,\n      ]),\n    ),\n    write: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__LegacyAppPathString).annotate(\n          { description: \"This will be removed in favor of `entries`.\" },\n        ),\n        Schema.Null,\n      ]),\n    ),\n  });\n\nexport type V2PluginInstalledResponse__PluginMarketplaceEntry = {\n  readonly interface?: V2PluginInstalledResponse__MarketplaceInterface | null;\n  readonly name: string;\n  readonly path?: V2PluginInstalledResponse__AbsolutePathBuf | null;\n  readonly plugins: ReadonlyArray<V2PluginInstalledResponse__PluginSummary>;\n};\nexport const V2PluginInstalledResponse__PluginMarketplaceEntry = Schema.Struct({\n  interface: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__MarketplaceInterface, Schema.Null]),\n  ),\n  name: Schema.String,\n  path: Schema.optionalKey(\n    Schema.Union([V2PluginInstalledResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description:\n        \"Local marketplace file path when the marketplace is backed by a local file. Remote-only catalog marketplaces do not have a local path.\",\n    }),\n  ),\n  plugins: Schema.Array(V2PluginInstalledResponse__PluginSummary),\n});\n\nexport type V2PluginListResponse__PluginMarketplaceEntry = {\n  readonly interface?: V2PluginListResponse__MarketplaceInterface | null;\n  readonly name: string;\n  readonly path?: V2PluginListResponse__AbsolutePathBuf | null;\n  readonly plugins: ReadonlyArray<V2PluginListResponse__PluginSummary>;\n};\nexport const V2PluginListResponse__PluginMarketplaceEntry = Schema.Struct({\n  interface: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__MarketplaceInterface, Schema.Null]),\n  ),\n  name: Schema.String,\n  path: Schema.optionalKey(\n    Schema.Union([V2PluginListResponse__AbsolutePathBuf, Schema.Null]).annotate({\n      description:\n        \"Local marketplace file path when the marketplace is backed by a local file. Remote-only catalog marketplaces do not have a local path.\",\n    }),\n  ),\n  plugins: Schema.Array(V2PluginListResponse__PluginSummary),\n});\n\nexport type V2PluginReadResponse__PluginDetail = {\n  readonly appTemplates: ReadonlyArray<V2PluginReadResponse__AppTemplateSummary>;\n  readonly apps: ReadonlyArray<V2PluginReadResponse__AppSummary>;\n  readonly description?: string | null;\n  readonly hooks: ReadonlyArray<V2PluginReadResponse__PluginHookSummary>;\n  readonly marketplaceName: string;\n  readonly marketplacePath?: V2PluginReadResponse__AbsolutePathBuf | null;\n  readonly mcpServers: ReadonlyArray<string>;\n  readonly scheduledTasks?: ReadonlyArray<V2PluginReadResponse__ScheduledTaskSummary> | null;\n  readonly shareUrl?: string | null;\n  readonly skills: ReadonlyArray<V2PluginReadResponse__SkillSummary>;\n  readonly summary: V2PluginReadResponse__PluginSummary;\n};\nexport const V2PluginReadResponse__PluginDetail = Schema.Struct({\n  appTemplates: Schema.Array(V2PluginReadResponse__AppTemplateSummary),\n  apps: Schema.Array(V2PluginReadResponse__AppSummary),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  hooks: Schema.Array(V2PluginReadResponse__PluginHookSummary),\n  marketplaceName: Schema.String,\n  marketplacePath: Schema.optionalKey(\n    Schema.Union([V2PluginReadResponse__AbsolutePathBuf, Schema.Null]),\n  ),\n  mcpServers: Schema.Array(Schema.String),\n  scheduledTasks: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginReadResponse__ScheduledTaskSummary), Schema.Null]),\n  ),\n  shareUrl: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  skills: Schema.Array(V2PluginReadResponse__SkillSummary),\n  summary: V2PluginReadResponse__PluginSummary,\n});\n\nexport type V2PluginShareListResponse__PluginShareListItem = {\n  readonly localPluginPath?: V2PluginShareListResponse__AbsolutePathBuf | null;\n  readonly plugin: V2PluginShareListResponse__PluginSummary;\n};\nexport const V2PluginShareListResponse__PluginShareListItem = Schema.Struct({\n  localPluginPath: Schema.optionalKey(\n    Schema.Union([V2PluginShareListResponse__AbsolutePathBuf, Schema.Null]),\n  ),\n  plugin: V2PluginShareListResponse__PluginSummary,\n});\n\nexport type V2ThreadForkResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadForkResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadForkResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadForkResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadForkResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadForkResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadForkResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadForkResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadForkResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadForkResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadListResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadListResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadListResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadListResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadListResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadListResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadListResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadListResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadListResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadListResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadListResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadListResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadMetadataUpdateResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadMetadataUpdateResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadMetadataUpdateResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadMetadataUpdateResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadMetadataUpdateResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadMetadataUpdateResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadMetadataUpdateResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadMetadataUpdateResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadMetadataUpdateResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadReadResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadReadResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadReadResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadReadResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadReadResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadReadResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadReadResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadReadResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadReadResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadReadResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadReadResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadReadResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadResumeResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadResumeResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadResumeResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadResumeResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadResumeResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadResumeResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadResumeResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadResumeResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadResumeResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadResumeResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadStartedNotification__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadStartedNotification__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadStartedNotification__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadStartedNotification__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadStartedNotification__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadStartedNotification__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadStartedNotification__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadStartedNotification__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadStartedNotification__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadStartedNotification__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadStartedNotification__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadStartedNotification__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadStartResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadStartResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadStartResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadStartResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadStartResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadStartResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadStartResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadStartResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadStartResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadStartResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadUnarchiveResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadUnarchiveResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadUnarchiveResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadUnarchiveResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadUnarchiveResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadUnarchiveResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadUnarchiveResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadUnarchiveResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadUnarchiveResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadUnarchiveResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadUnarchiveResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadUnarchiveResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type McpServerElicitationRequestParams__McpElicitationPrimitiveSchema =\n  | McpServerElicitationRequestParams__McpElicitationEnumSchema\n  | McpServerElicitationRequestParams__McpElicitationStringSchema\n  | McpServerElicitationRequestParams__McpElicitationNumberSchema\n  | McpServerElicitationRequestParams__McpElicitationBooleanSchema;\nexport const McpServerElicitationRequestParams__McpElicitationPrimitiveSchema = Schema.Union([\n  McpServerElicitationRequestParams__McpElicitationEnumSchema,\n  McpServerElicitationRequestParams__McpElicitationStringSchema,\n  McpServerElicitationRequestParams__McpElicitationNumberSchema,\n  McpServerElicitationRequestParams__McpElicitationBooleanSchema,\n]);\n\nexport type PermissionsRequestApprovalParams__RequestPermissionProfile = {\n  readonly fileSystem?: PermissionsRequestApprovalParams__AdditionalFileSystemPermissions | null;\n  readonly network?: PermissionsRequestApprovalParams__AdditionalNetworkPermissions | null;\n};\nexport const PermissionsRequestApprovalParams__RequestPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([PermissionsRequestApprovalParams__AdditionalFileSystemPermissions, Schema.Null]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([PermissionsRequestApprovalParams__AdditionalNetworkPermissions, Schema.Null]),\n  ),\n});\n\nexport type PermissionsRequestApprovalResponse__GrantedPermissionProfile = {\n  readonly fileSystem?: PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions | null;\n  readonly network?: PermissionsRequestApprovalResponse__AdditionalNetworkPermissions | null;\n};\nexport const PermissionsRequestApprovalResponse__GrantedPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([\n      PermissionsRequestApprovalResponse__AdditionalFileSystemPermissions,\n      Schema.Null,\n    ]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([PermissionsRequestApprovalResponse__AdditionalNetworkPermissions, Schema.Null]),\n  ),\n});\n\nexport type ServerNotification__RequestPermissionProfile = {\n  readonly fileSystem?: ServerNotification__AdditionalFileSystemPermissions | null;\n  readonly network?: ServerNotification__AdditionalNetworkPermissions | null;\n};\nexport const ServerNotification__RequestPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([ServerNotification__AdditionalFileSystemPermissions, Schema.Null]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([ServerNotification__AdditionalNetworkPermissions, Schema.Null]),\n  ),\n});\n\nexport type ServerNotification__ThreadStartedNotification = {\n  readonly thread: ServerNotification__Thread;\n};\nexport const ServerNotification__ThreadStartedNotification = Schema.Struct({\n  thread: ServerNotification__Thread,\n});\n\nexport type ServerRequest__RequestPermissionProfile = {\n  readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null;\n  readonly network?: ServerRequest__AdditionalNetworkPermissions | null;\n};\nexport const ServerRequest__RequestPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]),\n  ),\n});\n\nexport type ServerRequest__McpElicitationPrimitiveSchema =\n  | ServerRequest__McpElicitationEnumSchema\n  | ServerRequest__McpElicitationStringSchema\n  | ServerRequest__McpElicitationNumberSchema\n  | ServerRequest__McpElicitationBooleanSchema;\nexport const ServerRequest__McpElicitationPrimitiveSchema = Schema.Union([\n  ServerRequest__McpElicitationEnumSchema,\n  ServerRequest__McpElicitationStringSchema,\n  ServerRequest__McpElicitationNumberSchema,\n  ServerRequest__McpElicitationBooleanSchema,\n]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile = {\n  readonly fileSystem?: V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions | null;\n  readonly network?: V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions | null;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile =\n  Schema.Struct({\n    fileSystem: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewCompletedNotification__AdditionalFileSystemPermissions,\n        Schema.Null,\n      ]),\n    ),\n    network: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewCompletedNotification__AdditionalNetworkPermissions,\n        Schema.Null,\n      ]),\n    ),\n  });\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile = {\n  readonly fileSystem?: V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions | null;\n  readonly network?: V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions | null;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile =\n  Schema.Struct({\n    fileSystem: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewStartedNotification__AdditionalFileSystemPermissions,\n        Schema.Null,\n      ]),\n    ),\n    network: Schema.optionalKey(\n      Schema.Union([\n        V2ItemGuardianApprovalReviewStartedNotification__AdditionalNetworkPermissions,\n        Schema.Null,\n      ]),\n    ),\n  });\n\nexport type McpServerElicitationRequestParams__McpElicitationSchema = {\n  readonly $schema?: string | null;\n  readonly properties: {\n    readonly [x: string]: McpServerElicitationRequestParams__McpElicitationPrimitiveSchema;\n  };\n  readonly required?: ReadonlyArray<string> | null;\n  readonly type: McpServerElicitationRequestParams__McpElicitationObjectType;\n};\nexport const McpServerElicitationRequestParams__McpElicitationSchema = Schema.Struct({\n  $schema: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  properties: Schema.Record(\n    Schema.String,\n    McpServerElicitationRequestParams__McpElicitationPrimitiveSchema,\n  ),\n  required: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  type: McpServerElicitationRequestParams__McpElicitationObjectType,\n}).annotate({\n  description:\n    \"Typed form schema for MCP `elicitation/create` requests.\\n\\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.\",\n});\n\nexport type ServerNotification__GuardianApprovalReviewAction =\n  | {\n      readonly command: string;\n      readonly cwd: ServerNotification__AbsolutePathBuf;\n      readonly source: ServerNotification__GuardianCommandSource;\n      readonly type: \"command\";\n    }\n  | {\n      readonly argv: ReadonlyArray<string>;\n      readonly cwd: ServerNotification__AbsolutePathBuf;\n      readonly program: string;\n      readonly source: ServerNotification__GuardianCommandSource;\n      readonly type: \"execve\";\n    }\n  | {\n      readonly cwd: ServerNotification__AbsolutePathBuf;\n      readonly files: ReadonlyArray<ServerNotification__AbsolutePathBuf>;\n      readonly type: \"applyPatch\";\n    }\n  | {\n      readonly host: string;\n      readonly port: number;\n      readonly protocol: ServerNotification__NetworkApprovalProtocol;\n      readonly target: string;\n      readonly type: \"networkAccess\";\n    }\n  | {\n      readonly connectorId?: string | null;\n      readonly connectorName?: string | null;\n      readonly server: string;\n      readonly toolName: string;\n      readonly toolTitle?: string | null;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly permissions: ServerNotification__RequestPermissionProfile;\n      readonly reason?: string | null;\n      readonly type: \"requestPermissions\";\n    };\nexport const ServerNotification__GuardianApprovalReviewAction = Schema.Union(\n  [\n    Schema.Struct({\n      command: Schema.String,\n      cwd: ServerNotification__AbsolutePathBuf,\n      source: ServerNotification__GuardianCommandSource,\n      type: Schema.Literal(\"command\").annotate({\n        title: \"CommandGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"CommandGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      argv: Schema.Array(Schema.String),\n      cwd: ServerNotification__AbsolutePathBuf,\n      program: Schema.String,\n      source: ServerNotification__GuardianCommandSource,\n      type: Schema.Literal(\"execve\").annotate({ title: \"ExecveGuardianApprovalReviewActionType\" }),\n    }).annotate({ title: \"ExecveGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      cwd: ServerNotification__AbsolutePathBuf,\n      files: Schema.Array(ServerNotification__AbsolutePathBuf),\n      type: Schema.Literal(\"applyPatch\").annotate({\n        title: \"ApplyPatchGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"ApplyPatchGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      host: Schema.String,\n      port: Schema.Number.annotate({ format: \"uint16\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      protocol: ServerNotification__NetworkApprovalProtocol,\n      target: Schema.String,\n      type: Schema.Literal(\"networkAccess\").annotate({\n        title: \"NetworkAccessGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"NetworkAccessGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      server: Schema.String,\n      toolName: Schema.String,\n      toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"mcpToolCall\").annotate({\n        title: \"McpToolCallGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"McpToolCallGuardianApprovalReviewAction\" }),\n    Schema.Struct({\n      permissions: ServerNotification__RequestPermissionProfile,\n      reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"requestPermissions\").annotate({\n        title: \"RequestPermissionsGuardianApprovalReviewActionType\",\n      }),\n    }).annotate({ title: \"RequestPermissionsGuardianApprovalReviewAction\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerRequest__PermissionsRequestApprovalParams = {\n  readonly cwd: ServerRequest__AbsolutePathBuf;\n  readonly environmentId?: string | null;\n  readonly itemId: string;\n  readonly permissions: ServerRequest__RequestPermissionProfile;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerRequest__PermissionsRequestApprovalParams = Schema.Struct({\n  cwd: ServerRequest__AbsolutePathBuf,\n  environmentId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  itemId: Schema.String,\n  permissions: ServerRequest__RequestPermissionProfile,\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n});\n\nexport type ServerRequest__McpElicitationSchema = {\n  readonly $schema?: string | null;\n  readonly properties: { readonly [x: string]: ServerRequest__McpElicitationPrimitiveSchema };\n  readonly required?: ReadonlyArray<string> | null;\n  readonly type: ServerRequest__McpElicitationObjectType;\n};\nexport const ServerRequest__McpElicitationSchema = Schema.Struct({\n  $schema: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  properties: Schema.Record(Schema.String, ServerRequest__McpElicitationPrimitiveSchema),\n  required: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  type: ServerRequest__McpElicitationObjectType,\n}).annotate({\n  description:\n    \"Typed form schema for MCP `elicitation/create` requests.\\n\\nThis matches the `requestedSchema` shape from the MCP 2025-11-25 `ElicitRequestFormParams` schema.\",\n});\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction =\n  | {\n      readonly command: string;\n      readonly cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf;\n      readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource;\n      readonly type: \"command\";\n    }\n  | {\n      readonly argv: ReadonlyArray<string>;\n      readonly cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf;\n      readonly program: string;\n      readonly source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource;\n      readonly type: \"execve\";\n    }\n  | {\n      readonly cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf;\n      readonly files: ReadonlyArray<V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf>;\n      readonly type: \"applyPatch\";\n    }\n  | {\n      readonly host: string;\n      readonly port: number;\n      readonly protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol;\n      readonly target: string;\n      readonly type: \"networkAccess\";\n    }\n  | {\n      readonly connectorId?: string | null;\n      readonly connectorName?: string | null;\n      readonly server: string;\n      readonly toolName: string;\n      readonly toolTitle?: string | null;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly permissions: V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile;\n      readonly reason?: string | null;\n      readonly type: \"requestPermissions\";\n    };\nexport const V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction =\n  Schema.Union(\n    [\n      Schema.Struct({\n        command: Schema.String,\n        cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf,\n        source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource,\n        type: Schema.Literal(\"command\").annotate({\n          title: \"CommandGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"CommandGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        argv: Schema.Array(Schema.String),\n        cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf,\n        program: Schema.String,\n        source: V2ItemGuardianApprovalReviewCompletedNotification__GuardianCommandSource,\n        type: Schema.Literal(\"execve\").annotate({\n          title: \"ExecveGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"ExecveGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        cwd: V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf,\n        files: Schema.Array(V2ItemGuardianApprovalReviewCompletedNotification__AbsolutePathBuf),\n        type: Schema.Literal(\"applyPatch\").annotate({\n          title: \"ApplyPatchGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"ApplyPatchGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        host: Schema.String,\n        port: Schema.Number.annotate({ format: \"uint16\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        protocol: V2ItemGuardianApprovalReviewCompletedNotification__NetworkApprovalProtocol,\n        target: Schema.String,\n        type: Schema.Literal(\"networkAccess\").annotate({\n          title: \"NetworkAccessGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"NetworkAccessGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        server: Schema.String,\n        toolName: Schema.String,\n        toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        type: Schema.Literal(\"mcpToolCall\").annotate({\n          title: \"McpToolCallGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"McpToolCallGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        permissions: V2ItemGuardianApprovalReviewCompletedNotification__RequestPermissionProfile,\n        reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        type: Schema.Literal(\"requestPermissions\").annotate({\n          title: \"RequestPermissionsGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"RequestPermissionsGuardianApprovalReviewAction\" }),\n    ],\n    { mode: \"oneOf\" },\n  );\n\nexport type V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction =\n  | {\n      readonly command: string;\n      readonly cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf;\n      readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource;\n      readonly type: \"command\";\n    }\n  | {\n      readonly argv: ReadonlyArray<string>;\n      readonly cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf;\n      readonly program: string;\n      readonly source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource;\n      readonly type: \"execve\";\n    }\n  | {\n      readonly cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf;\n      readonly files: ReadonlyArray<V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf>;\n      readonly type: \"applyPatch\";\n    }\n  | {\n      readonly host: string;\n      readonly port: number;\n      readonly protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol;\n      readonly target: string;\n      readonly type: \"networkAccess\";\n    }\n  | {\n      readonly connectorId?: string | null;\n      readonly connectorName?: string | null;\n      readonly server: string;\n      readonly toolName: string;\n      readonly toolTitle?: string | null;\n      readonly type: \"mcpToolCall\";\n    }\n  | {\n      readonly permissions: V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile;\n      readonly reason?: string | null;\n      readonly type: \"requestPermissions\";\n    };\nexport const V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction =\n  Schema.Union(\n    [\n      Schema.Struct({\n        command: Schema.String,\n        cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf,\n        source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource,\n        type: Schema.Literal(\"command\").annotate({\n          title: \"CommandGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"CommandGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        argv: Schema.Array(Schema.String),\n        cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf,\n        program: Schema.String,\n        source: V2ItemGuardianApprovalReviewStartedNotification__GuardianCommandSource,\n        type: Schema.Literal(\"execve\").annotate({\n          title: \"ExecveGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"ExecveGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        cwd: V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf,\n        files: Schema.Array(V2ItemGuardianApprovalReviewStartedNotification__AbsolutePathBuf),\n        type: Schema.Literal(\"applyPatch\").annotate({\n          title: \"ApplyPatchGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"ApplyPatchGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        host: Schema.String,\n        port: Schema.Number.annotate({ format: \"uint16\" })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        protocol: V2ItemGuardianApprovalReviewStartedNotification__NetworkApprovalProtocol,\n        target: Schema.String,\n        type: Schema.Literal(\"networkAccess\").annotate({\n          title: \"NetworkAccessGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"NetworkAccessGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        connectorId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        connectorName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        server: Schema.String,\n        toolName: Schema.String,\n        toolTitle: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        type: Schema.Literal(\"mcpToolCall\").annotate({\n          title: \"McpToolCallGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"McpToolCallGuardianApprovalReviewAction\" }),\n      Schema.Struct({\n        permissions: V2ItemGuardianApprovalReviewStartedNotification__RequestPermissionProfile,\n        reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        type: Schema.Literal(\"requestPermissions\").annotate({\n          title: \"RequestPermissionsGuardianApprovalReviewActionType\",\n        }),\n      }).annotate({ title: \"RequestPermissionsGuardianApprovalReviewAction\" }),\n    ],\n    { mode: \"oneOf\" },\n  );\n\nexport type ServerNotification__ItemGuardianApprovalReviewCompletedNotification = {\n  readonly action: ServerNotification__GuardianApprovalReviewAction;\n  readonly completedAtMs: number;\n  readonly decisionSource: ServerNotification__AutoReviewDecisionSource;\n  readonly review: ServerNotification__GuardianApprovalReview;\n  readonly reviewId: string;\n  readonly startedAtMs: number;\n  readonly targetItemId?: string | null;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({\n  action: ServerNotification__GuardianApprovalReviewAction,\n  completedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review completed.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  decisionSource: ServerNotification__AutoReviewDecisionSource,\n  review: ServerNotification__GuardianApprovalReview,\n  reviewId: Schema.String.annotate({ description: \"Stable identifier for this review.\" }),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  targetItemId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Identifier for the reviewed item or tool call when one exists.\\n\\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\\n\\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.\",\n});\n\nexport type ServerNotification__ItemGuardianApprovalReviewStartedNotification = {\n  readonly action: ServerNotification__GuardianApprovalReviewAction;\n  readonly review: ServerNotification__GuardianApprovalReview;\n  readonly reviewId: string;\n  readonly startedAtMs: number;\n  readonly targetItemId?: string | null;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ServerNotification__ItemGuardianApprovalReviewStartedNotification = Schema.Struct({\n  action: ServerNotification__GuardianApprovalReviewAction,\n  review: ServerNotification__GuardianApprovalReview,\n  reviewId: Schema.String.annotate({ description: \"Stable identifier for this review.\" }),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  targetItemId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Identifier for the reviewed item or tool call when one exists.\\n\\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\\n\\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  description:\n    \"[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.\",\n});\n\nexport type ServerRequest__McpServerElicitationRequestParams =\n  | {\n      readonly _meta?: unknown;\n      readonly message: string;\n      readonly mode: \"form\";\n      readonly requestedSchema: ServerRequest__McpElicitationSchema;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly message: string;\n      readonly mode: \"openai/form\";\n      readonly requestedSchema: unknown;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly elicitationId: string;\n      readonly message: string;\n      readonly mode: \"url\";\n      readonly url: string;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    };\nexport const ServerRequest__McpServerElicitationRequestParams = Schema.Union(\n  [\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      message: Schema.String,\n      mode: Schema.Literal(\"form\"),\n      requestedSchema: ServerRequest__McpElicitationSchema,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }),\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      message: Schema.String,\n      mode: Schema.Literal(\"openai/form\"),\n      requestedSchema: Schema.Unknown,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }),\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      elicitationId: Schema.String,\n      message: Schema.String,\n      mode: Schema.Literal(\"url\"),\n      url: Schema.String,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ApplyPatchApprovalParams = {\n  readonly callId: string;\n  readonly conversationId: ApplyPatchApprovalParams__ThreadId;\n  readonly fileChanges: { readonly [x: string]: ApplyPatchApprovalParams__FileChange };\n  readonly grantRoot?: string | null;\n  readonly reason?: string | null;\n};\nexport const ApplyPatchApprovalParams = Schema.Struct({\n  callId: Schema.String.annotate({\n    description:\n      \"Use to correlate this with [codex_protocol::protocol::PatchApplyBeginEvent] and [codex_protocol::protocol::PatchApplyEndEvent].\",\n  }),\n  conversationId: ApplyPatchApprovalParams__ThreadId,\n  fileChanges: Schema.Record(Schema.String, ApplyPatchApprovalParams__FileChange),\n  grantRoot: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for extra write access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ApplyPatchApprovalParams\" });\n\nexport type ApplyPatchApprovalResponse = {\n  readonly decision: ApplyPatchApprovalResponse__ReviewDecision;\n};\nexport const ApplyPatchApprovalResponse = Schema.Struct({\n  decision: ApplyPatchApprovalResponse__ReviewDecision,\n}).annotate({ title: \"ApplyPatchApprovalResponse\" });\n\nexport type AttestationGenerateParams = {};\nexport const AttestationGenerateParams = Schema.Struct({}).annotate({\n  title: \"AttestationGenerateParams\",\n});\n\nexport type AttestationGenerateResponse = { readonly token: string };\nexport const AttestationGenerateResponse = Schema.Struct({\n  token: Schema.String.annotate({ description: \"Opaque client attestation token.\" }),\n}).annotate({ title: \"AttestationGenerateResponse\" });\n\nexport type ChatgptAuthTokensRefreshParams = {\n  readonly previousAccountId?: string | null;\n  readonly reason: ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason;\n};\nexport const ChatgptAuthTokensRefreshParams = Schema.Struct({\n  previousAccountId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Workspace/account identifier that Codex was previously using.\\n\\nClients that manage multiple accounts/workspaces can use this as a hint to refresh the token for the correct workspace.\\n\\nThis may be `null` when the prior auth state did not include a workspace identifier (`chatgpt_account_id`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: ChatgptAuthTokensRefreshParams__ChatgptAuthTokensRefreshReason,\n}).annotate({ title: \"ChatgptAuthTokensRefreshParams\" });\n\nexport type ChatgptAuthTokensRefreshResponse = {\n  readonly accessToken: string;\n  readonly chatgptAccountId: string;\n  readonly chatgptPlanType?: string | null;\n};\nexport const ChatgptAuthTokensRefreshResponse = Schema.Struct({\n  accessToken: Schema.String,\n  chatgptAccountId: Schema.String,\n  chatgptPlanType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ChatgptAuthTokensRefreshResponse\" });\n\nexport type ClientNotification = { readonly method: \"initialized\" };\nexport const ClientNotification = Schema.Union(\n  [\n    Schema.Struct({\n      method: Schema.Literal(\"initialized\").annotate({ title: \"InitializedNotificationMethod\" }),\n    }).annotate({ title: \"InitializedNotification\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ title: \"ClientNotification\" });\n\nexport type ClientRequest =\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"initialize\";\n      readonly params: ClientRequest__InitializeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/start\";\n      readonly params: ClientRequest__ThreadStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/resume\";\n      readonly params: ClientRequest__ThreadResumeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/fork\";\n      readonly params: ClientRequest__ThreadForkParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/archive\";\n      readonly params: ClientRequest__ThreadArchiveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/delete\";\n      readonly params: ClientRequest__ThreadDeleteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/unsubscribe\";\n      readonly params: ClientRequest__ThreadUnsubscribeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/name/set\";\n      readonly params: ClientRequest__ThreadSetNameParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/goal/set\";\n      readonly params: ClientRequest__ThreadGoalSetParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/goal/get\";\n      readonly params: ClientRequest__ThreadGoalGetParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/goal/clear\";\n      readonly params: ClientRequest__ThreadGoalClearParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/metadata/update\";\n      readonly params: ClientRequest__ThreadMetadataUpdateParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/unarchive\";\n      readonly params: ClientRequest__ThreadUnarchiveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/compact/start\";\n      readonly params: ClientRequest__ThreadCompactStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/shellCommand\";\n      readonly params: ClientRequest__ThreadShellCommandParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/approveGuardianDeniedAction\";\n      readonly params: ClientRequest__ThreadApproveGuardianDeniedActionParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/rollback\";\n      readonly params: ClientRequest__ThreadRollbackParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/list\";\n      readonly params: ClientRequest__ThreadListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/loaded/list\";\n      readonly params: ClientRequest__ThreadLoadedListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/read\";\n      readonly params: ClientRequest__ThreadReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"thread/inject_items\";\n      readonly params: ClientRequest__ThreadInjectItemsParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"skills/list\";\n      readonly params: ClientRequest__SkillsListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"skills/extraRoots/set\";\n      readonly params: ClientRequest__SkillsExtraRootsSetParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"hooks/list\";\n      readonly params: ClientRequest__HooksListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"marketplace/add\";\n      readonly params: ClientRequest__MarketplaceAddParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"marketplace/remove\";\n      readonly params: ClientRequest__MarketplaceRemoveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"marketplace/upgrade\";\n      readonly params: ClientRequest__MarketplaceUpgradeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/list\";\n      readonly params: ClientRequest__PluginListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/installed\";\n      readonly params: ClientRequest__PluginInstalledParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/read\";\n      readonly params: ClientRequest__PluginReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/skill/read\";\n      readonly params: ClientRequest__PluginSkillReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/save\";\n      readonly params: ClientRequest__PluginShareSaveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/updateTargets\";\n      readonly params: ClientRequest__PluginShareUpdateTargetsParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/list\";\n      readonly params: ClientRequest__PluginShareListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/checkout\";\n      readonly params: ClientRequest__PluginShareCheckoutParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/share/delete\";\n      readonly params: ClientRequest__PluginShareDeleteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"app/read\";\n      readonly params: ClientRequest__AppsReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"app/list\";\n      readonly params: ClientRequest__AppsListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"app/installed\";\n      readonly params: ClientRequest__AppsInstalledParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/readFile\";\n      readonly params: ClientRequest__FsReadFileParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/writeFile\";\n      readonly params: ClientRequest__FsWriteFileParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/createDirectory\";\n      readonly params: ClientRequest__FsCreateDirectoryParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/getMetadata\";\n      readonly params: ClientRequest__FsGetMetadataParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/readDirectory\";\n      readonly params: ClientRequest__FsReadDirectoryParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/remove\";\n      readonly params: ClientRequest__FsRemoveParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/copy\";\n      readonly params: ClientRequest__FsCopyParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/watch\";\n      readonly params: ClientRequest__FsWatchParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fs/unwatch\";\n      readonly params: ClientRequest__FsUnwatchParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"skills/config/write\";\n      readonly params: ClientRequest__SkillsConfigWriteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/install\";\n      readonly params: ClientRequest__PluginInstallParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"plugin/uninstall\";\n      readonly params: ClientRequest__PluginUninstallParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"turn/start\";\n      readonly params: ClientRequest__TurnStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"turn/steer\";\n      readonly params: ClientRequest__TurnSteerParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"turn/interrupt\";\n      readonly params: ClientRequest__TurnInterruptParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"review/start\";\n      readonly params: ClientRequest__ReviewStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"model/list\";\n      readonly params: ClientRequest__ModelListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"modelProvider/capabilities/read\";\n      readonly params: ClientRequest__ModelProviderCapabilitiesReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"experimentalFeature/list\";\n      readonly params: ClientRequest__ExperimentalFeatureListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"permissionProfile/list\";\n      readonly params: ClientRequest__PermissionProfileListParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"experimentalFeature/enablement/set\";\n      readonly params: ClientRequest__ExperimentalFeatureEnablementSetParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"mcpServer/oauth/login\";\n      readonly params: ClientRequest__McpServerOauthLoginParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"config/mcpServer/reload\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"mcpServerStatus/list\";\n      readonly params: ClientRequest__ListMcpServerStatusParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"mcpServer/resource/read\";\n      readonly params: ClientRequest__McpResourceReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"mcpServer/tool/call\";\n      readonly params: ClientRequest__McpServerToolCallParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"windowsSandbox/setupStart\";\n      readonly params: ClientRequest__WindowsSandboxSetupStartParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"windowsSandbox/readiness\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/login/start\";\n      readonly params: ClientRequest__LoginAccountParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/login/cancel\";\n      readonly params: ClientRequest__CancelLoginAccountParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/logout\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/rateLimits/read\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/rateLimitResetCredit/consume\";\n      readonly params: ClientRequest__ConsumeAccountRateLimitResetCreditParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/usage/read\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/workspaceMessages/read\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/sendAddCreditsNudgeEmail\";\n      readonly params: ClientRequest__SendAddCreditsNudgeEmailParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"feedback/upload\";\n      readonly params: ClientRequest__FeedbackUploadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"command/exec\";\n      readonly params: ClientRequest__CommandExecParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"command/exec/write\";\n      readonly params: ClientRequest__CommandExecWriteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"command/exec/terminate\";\n      readonly params: ClientRequest__CommandExecTerminateParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"command/exec/resize\";\n      readonly params: ClientRequest__CommandExecResizeParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"config/read\";\n      readonly params: ClientRequest__ConfigReadParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"externalAgentConfig/detect\";\n      readonly params: ClientRequest__ExternalAgentConfigDetectParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"externalAgentConfig/import\";\n      readonly params: ClientRequest__ExternalAgentConfigImportParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"externalAgentConfig/import/readHistories\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"config/value/write\";\n      readonly params: ClientRequest__ConfigValueWriteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"config/batchWrite\";\n      readonly params: ClientRequest__ConfigBatchWriteParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"configRequirements/read\";\n      readonly params?: null;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"account/read\";\n      readonly params: ClientRequest__GetAccountParams;\n    }\n  | {\n      readonly id: ClientRequest__RequestId;\n      readonly method: \"fuzzyFileSearch\";\n      readonly params: ClientRequest__FuzzyFileSearchParams;\n    };\nexport const ClientRequest = Schema.Union(\n  [\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"initialize\").annotate({ title: \"InitializeRequestMethod\" }),\n      params: ClientRequest__InitializeParams,\n    }).annotate({ title: \"InitializeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/start\").annotate({ title: \"Thread/startRequestMethod\" }),\n      params: ClientRequest__ThreadStartParams,\n    }).annotate({ title: \"Thread/startRequest\", description: \"NEW APIs\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/resume\").annotate({ title: \"Thread/resumeRequestMethod\" }),\n      params: ClientRequest__ThreadResumeParams,\n    }).annotate({ title: \"Thread/resumeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/fork\").annotate({ title: \"Thread/forkRequestMethod\" }),\n      params: ClientRequest__ThreadForkParams,\n    }).annotate({ title: \"Thread/forkRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/archive\").annotate({ title: \"Thread/archiveRequestMethod\" }),\n      params: ClientRequest__ThreadArchiveParams,\n    }).annotate({ title: \"Thread/archiveRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/delete\").annotate({ title: \"Thread/deleteRequestMethod\" }),\n      params: ClientRequest__ThreadDeleteParams,\n    }).annotate({ title: \"Thread/deleteRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/unsubscribe\").annotate({\n        title: \"Thread/unsubscribeRequestMethod\",\n      }),\n      params: ClientRequest__ThreadUnsubscribeParams,\n    }).annotate({ title: \"Thread/unsubscribeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/name/set\").annotate({ title: \"Thread/name/setRequestMethod\" }),\n      params: ClientRequest__ThreadSetNameParams,\n    }).annotate({ title: \"Thread/name/setRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/goal/set\").annotate({ title: \"Thread/goal/setRequestMethod\" }),\n      params: ClientRequest__ThreadGoalSetParams,\n    }).annotate({ title: \"Thread/goal/setRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/goal/get\").annotate({ title: \"Thread/goal/getRequestMethod\" }),\n      params: ClientRequest__ThreadGoalGetParams,\n    }).annotate({ title: \"Thread/goal/getRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/goal/clear\").annotate({\n        title: \"Thread/goal/clearRequestMethod\",\n      }),\n      params: ClientRequest__ThreadGoalClearParams,\n    }).annotate({ title: \"Thread/goal/clearRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/metadata/update\").annotate({\n        title: \"Thread/metadata/updateRequestMethod\",\n      }),\n      params: ClientRequest__ThreadMetadataUpdateParams,\n    }).annotate({ title: \"Thread/metadata/updateRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/unarchive\").annotate({\n        title: \"Thread/unarchiveRequestMethod\",\n      }),\n      params: ClientRequest__ThreadUnarchiveParams,\n    }).annotate({ title: \"Thread/unarchiveRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/compact/start\").annotate({\n        title: \"Thread/compact/startRequestMethod\",\n      }),\n      params: ClientRequest__ThreadCompactStartParams,\n    }).annotate({ title: \"Thread/compact/startRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/shellCommand\").annotate({\n        title: \"Thread/shellCommandRequestMethod\",\n      }),\n      params: ClientRequest__ThreadShellCommandParams,\n    }).annotate({ title: \"Thread/shellCommandRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/approveGuardianDeniedAction\").annotate({\n        title: \"Thread/approveGuardianDeniedActionRequestMethod\",\n      }),\n      params: ClientRequest__ThreadApproveGuardianDeniedActionParams,\n    }).annotate({ title: \"Thread/approveGuardianDeniedActionRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/rollback\").annotate({ title: \"Thread/rollbackRequestMethod\" }),\n      params: ClientRequest__ThreadRollbackParams,\n    }).annotate({ title: \"Thread/rollbackRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/list\").annotate({ title: \"Thread/listRequestMethod\" }),\n      params: ClientRequest__ThreadListParams,\n    }).annotate({ title: \"Thread/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/loaded/list\").annotate({\n        title: \"Thread/loaded/listRequestMethod\",\n      }),\n      params: ClientRequest__ThreadLoadedListParams,\n    }).annotate({ title: \"Thread/loaded/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/read\").annotate({ title: \"Thread/readRequestMethod\" }),\n      params: ClientRequest__ThreadReadParams,\n    }).annotate({ title: \"Thread/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"thread/inject_items\").annotate({\n        title: \"Thread/injectItemsRequestMethod\",\n      }),\n      params: ClientRequest__ThreadInjectItemsParams,\n    }).annotate({\n      title: \"Thread/injectItemsRequest\",\n      description:\n        \"Append raw Responses API items to the thread history without starting a user turn.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"skills/list\").annotate({ title: \"Skills/listRequestMethod\" }),\n      params: ClientRequest__SkillsListParams,\n    }).annotate({ title: \"Skills/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"skills/extraRoots/set\").annotate({\n        title: \"Skills/extraRoots/setRequestMethod\",\n      }),\n      params: ClientRequest__SkillsExtraRootsSetParams,\n    }).annotate({ title: \"Skills/extraRoots/setRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"hooks/list\").annotate({ title: \"Hooks/listRequestMethod\" }),\n      params: ClientRequest__HooksListParams,\n    }).annotate({ title: \"Hooks/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"marketplace/add\").annotate({ title: \"Marketplace/addRequestMethod\" }),\n      params: ClientRequest__MarketplaceAddParams,\n    }).annotate({ title: \"Marketplace/addRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"marketplace/remove\").annotate({\n        title: \"Marketplace/removeRequestMethod\",\n      }),\n      params: ClientRequest__MarketplaceRemoveParams,\n    }).annotate({ title: \"Marketplace/removeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"marketplace/upgrade\").annotate({\n        title: \"Marketplace/upgradeRequestMethod\",\n      }),\n      params: ClientRequest__MarketplaceUpgradeParams,\n    }).annotate({ title: \"Marketplace/upgradeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/list\").annotate({ title: \"Plugin/listRequestMethod\" }),\n      params: ClientRequest__PluginListParams,\n    }).annotate({ title: \"Plugin/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/installed\").annotate({\n        title: \"Plugin/installedRequestMethod\",\n      }),\n      params: ClientRequest__PluginInstalledParams,\n    }).annotate({ title: \"Plugin/installedRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/read\").annotate({ title: \"Plugin/readRequestMethod\" }),\n      params: ClientRequest__PluginReadParams,\n    }).annotate({ title: \"Plugin/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/skill/read\").annotate({\n        title: \"Plugin/skill/readRequestMethod\",\n      }),\n      params: ClientRequest__PluginSkillReadParams,\n    }).annotate({ title: \"Plugin/skill/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/save\").annotate({\n        title: \"Plugin/share/saveRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareSaveParams,\n    }).annotate({ title: \"Plugin/share/saveRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/updateTargets\").annotate({\n        title: \"Plugin/share/updateTargetsRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareUpdateTargetsParams,\n    }).annotate({ title: \"Plugin/share/updateTargetsRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/list\").annotate({\n        title: \"Plugin/share/listRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareListParams,\n    }).annotate({ title: \"Plugin/share/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/checkout\").annotate({\n        title: \"Plugin/share/checkoutRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareCheckoutParams,\n    }).annotate({ title: \"Plugin/share/checkoutRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/share/delete\").annotate({\n        title: \"Plugin/share/deleteRequestMethod\",\n      }),\n      params: ClientRequest__PluginShareDeleteParams,\n    }).annotate({ title: \"Plugin/share/deleteRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"app/read\").annotate({ title: \"App/readRequestMethod\" }),\n      params: ClientRequest__AppsReadParams,\n    }).annotate({ title: \"App/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"app/list\").annotate({ title: \"App/listRequestMethod\" }),\n      params: ClientRequest__AppsListParams,\n    }).annotate({ title: \"App/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"app/installed\").annotate({ title: \"App/installedRequestMethod\" }),\n      params: ClientRequest__AppsInstalledParams,\n    }).annotate({ title: \"App/installedRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/readFile\").annotate({ title: \"Fs/readFileRequestMethod\" }),\n      params: ClientRequest__FsReadFileParams,\n    }).annotate({ title: \"Fs/readFileRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/writeFile\").annotate({ title: \"Fs/writeFileRequestMethod\" }),\n      params: ClientRequest__FsWriteFileParams,\n    }).annotate({ title: \"Fs/writeFileRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/createDirectory\").annotate({\n        title: \"Fs/createDirectoryRequestMethod\",\n      }),\n      params: ClientRequest__FsCreateDirectoryParams,\n    }).annotate({ title: \"Fs/createDirectoryRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/getMetadata\").annotate({ title: \"Fs/getMetadataRequestMethod\" }),\n      params: ClientRequest__FsGetMetadataParams,\n    }).annotate({ title: \"Fs/getMetadataRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/readDirectory\").annotate({\n        title: \"Fs/readDirectoryRequestMethod\",\n      }),\n      params: ClientRequest__FsReadDirectoryParams,\n    }).annotate({ title: \"Fs/readDirectoryRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/remove\").annotate({ title: \"Fs/removeRequestMethod\" }),\n      params: ClientRequest__FsRemoveParams,\n    }).annotate({ title: \"Fs/removeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/copy\").annotate({ title: \"Fs/copyRequestMethod\" }),\n      params: ClientRequest__FsCopyParams,\n    }).annotate({ title: \"Fs/copyRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/watch\").annotate({ title: \"Fs/watchRequestMethod\" }),\n      params: ClientRequest__FsWatchParams,\n    }).annotate({ title: \"Fs/watchRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fs/unwatch\").annotate({ title: \"Fs/unwatchRequestMethod\" }),\n      params: ClientRequest__FsUnwatchParams,\n    }).annotate({ title: \"Fs/unwatchRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"skills/config/write\").annotate({\n        title: \"Skills/config/writeRequestMethod\",\n      }),\n      params: ClientRequest__SkillsConfigWriteParams,\n    }).annotate({ title: \"Skills/config/writeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/install\").annotate({ title: \"Plugin/installRequestMethod\" }),\n      params: ClientRequest__PluginInstallParams,\n    }).annotate({ title: \"Plugin/installRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"plugin/uninstall\").annotate({\n        title: \"Plugin/uninstallRequestMethod\",\n      }),\n      params: ClientRequest__PluginUninstallParams,\n    }).annotate({ title: \"Plugin/uninstallRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"turn/start\").annotate({ title: \"Turn/startRequestMethod\" }),\n      params: ClientRequest__TurnStartParams,\n    }).annotate({ title: \"Turn/startRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"turn/steer\").annotate({ title: \"Turn/steerRequestMethod\" }),\n      params: ClientRequest__TurnSteerParams,\n    }).annotate({ title: \"Turn/steerRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"turn/interrupt\").annotate({ title: \"Turn/interruptRequestMethod\" }),\n      params: ClientRequest__TurnInterruptParams,\n    }).annotate({ title: \"Turn/interruptRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"review/start\").annotate({ title: \"Review/startRequestMethod\" }),\n      params: ClientRequest__ReviewStartParams,\n    }).annotate({ title: \"Review/startRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"model/list\").annotate({ title: \"Model/listRequestMethod\" }),\n      params: ClientRequest__ModelListParams,\n    }).annotate({ title: \"Model/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"modelProvider/capabilities/read\").annotate({\n        title: \"ModelProvider/capabilities/readRequestMethod\",\n      }),\n      params: ClientRequest__ModelProviderCapabilitiesReadParams,\n    }).annotate({ title: \"ModelProvider/capabilities/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"experimentalFeature/list\").annotate({\n        title: \"ExperimentalFeature/listRequestMethod\",\n      }),\n      params: ClientRequest__ExperimentalFeatureListParams,\n    }).annotate({ title: \"ExperimentalFeature/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"permissionProfile/list\").annotate({\n        title: \"PermissionProfile/listRequestMethod\",\n      }),\n      params: ClientRequest__PermissionProfileListParams,\n    }).annotate({ title: \"PermissionProfile/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"experimentalFeature/enablement/set\").annotate({\n        title: \"ExperimentalFeature/enablement/setRequestMethod\",\n      }),\n      params: ClientRequest__ExperimentalFeatureEnablementSetParams,\n    }).annotate({ title: \"ExperimentalFeature/enablement/setRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"mcpServer/oauth/login\").annotate({\n        title: \"McpServer/oauth/loginRequestMethod\",\n      }),\n      params: ClientRequest__McpServerOauthLoginParams,\n    }).annotate({ title: \"McpServer/oauth/loginRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"config/mcpServer/reload\").annotate({\n        title: \"Config/mcpServer/reloadRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Config/mcpServer/reloadRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"mcpServerStatus/list\").annotate({\n        title: \"McpServerStatus/listRequestMethod\",\n      }),\n      params: ClientRequest__ListMcpServerStatusParams,\n    }).annotate({ title: \"McpServerStatus/listRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"mcpServer/resource/read\").annotate({\n        title: \"McpServer/resource/readRequestMethod\",\n      }),\n      params: ClientRequest__McpResourceReadParams,\n    }).annotate({ title: \"McpServer/resource/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"mcpServer/tool/call\").annotate({\n        title: \"McpServer/tool/callRequestMethod\",\n      }),\n      params: ClientRequest__McpServerToolCallParams,\n    }).annotate({ title: \"McpServer/tool/callRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"windowsSandbox/setupStart\").annotate({\n        title: \"WindowsSandbox/setupStartRequestMethod\",\n      }),\n      params: ClientRequest__WindowsSandboxSetupStartParams,\n    }).annotate({ title: \"WindowsSandbox/setupStartRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"windowsSandbox/readiness\").annotate({\n        title: \"WindowsSandbox/readinessRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"WindowsSandbox/readinessRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/login/start\").annotate({\n        title: \"Account/login/startRequestMethod\",\n      }),\n      params: ClientRequest__LoginAccountParams,\n    }).annotate({ title: \"Account/login/startRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/login/cancel\").annotate({\n        title: \"Account/login/cancelRequestMethod\",\n      }),\n      params: ClientRequest__CancelLoginAccountParams,\n    }).annotate({ title: \"Account/login/cancelRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/logout\").annotate({ title: \"Account/logoutRequestMethod\" }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Account/logoutRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/rateLimits/read\").annotate({\n        title: \"Account/rateLimits/readRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Account/rateLimits/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/rateLimitResetCredit/consume\").annotate({\n        title: \"Account/rateLimitResetCredit/consumeRequestMethod\",\n      }),\n      params: ClientRequest__ConsumeAccountRateLimitResetCreditParams,\n    }).annotate({ title: \"Account/rateLimitResetCredit/consumeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/usage/read\").annotate({\n        title: \"Account/usage/readRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Account/usage/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/workspaceMessages/read\").annotate({\n        title: \"Account/workspaceMessages/readRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"Account/workspaceMessages/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/sendAddCreditsNudgeEmail\").annotate({\n        title: \"Account/sendAddCreditsNudgeEmailRequestMethod\",\n      }),\n      params: ClientRequest__SendAddCreditsNudgeEmailParams,\n    }).annotate({ title: \"Account/sendAddCreditsNudgeEmailRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"feedback/upload\").annotate({ title: \"Feedback/uploadRequestMethod\" }),\n      params: ClientRequest__FeedbackUploadParams,\n    }).annotate({ title: \"Feedback/uploadRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"command/exec\").annotate({ title: \"Command/execRequestMethod\" }),\n      params: ClientRequest__CommandExecParams,\n    }).annotate({\n      title: \"Command/execRequest\",\n      description: \"Execute a standalone command (argv vector) under the server's sandbox.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"command/exec/write\").annotate({\n        title: \"Command/exec/writeRequestMethod\",\n      }),\n      params: ClientRequest__CommandExecWriteParams,\n    }).annotate({\n      title: \"Command/exec/writeRequest\",\n      description: \"Write stdin bytes to a running `command/exec` session or close stdin.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"command/exec/terminate\").annotate({\n        title: \"Command/exec/terminateRequestMethod\",\n      }),\n      params: ClientRequest__CommandExecTerminateParams,\n    }).annotate({\n      title: \"Command/exec/terminateRequest\",\n      description: \"Terminate a running `command/exec` session by client-supplied `processId`.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"command/exec/resize\").annotate({\n        title: \"Command/exec/resizeRequestMethod\",\n      }),\n      params: ClientRequest__CommandExecResizeParams,\n    }).annotate({\n      title: \"Command/exec/resizeRequest\",\n      description:\n        \"Resize a running PTY-backed `command/exec` session by client-supplied `processId`.\",\n    }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"config/read\").annotate({ title: \"Config/readRequestMethod\" }),\n      params: ClientRequest__ConfigReadParams,\n    }).annotate({ title: \"Config/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"externalAgentConfig/detect\").annotate({\n        title: \"ExternalAgentConfig/detectRequestMethod\",\n      }),\n      params: ClientRequest__ExternalAgentConfigDetectParams,\n    }).annotate({ title: \"ExternalAgentConfig/detectRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"externalAgentConfig/import\").annotate({\n        title: \"ExternalAgentConfig/importRequestMethod\",\n      }),\n      params: ClientRequest__ExternalAgentConfigImportParams,\n    }).annotate({ title: \"ExternalAgentConfig/importRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"externalAgentConfig/import/readHistories\").annotate({\n        title: \"ExternalAgentConfig/import/readHistoriesRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"ExternalAgentConfig/import/readHistoriesRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"config/value/write\").annotate({\n        title: \"Config/value/writeRequestMethod\",\n      }),\n      params: ClientRequest__ConfigValueWriteParams,\n    }).annotate({ title: \"Config/value/writeRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"config/batchWrite\").annotate({\n        title: \"Config/batchWriteRequestMethod\",\n      }),\n      params: ClientRequest__ConfigBatchWriteParams,\n    }).annotate({ title: \"Config/batchWriteRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"configRequirements/read\").annotate({\n        title: \"ConfigRequirements/readRequestMethod\",\n      }),\n      params: Schema.optionalKey(Schema.Null),\n    }).annotate({ title: \"ConfigRequirements/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"account/read\").annotate({ title: \"Account/readRequestMethod\" }),\n      params: ClientRequest__GetAccountParams,\n    }).annotate({ title: \"Account/readRequest\" }),\n    Schema.Struct({\n      id: ClientRequest__RequestId,\n      method: Schema.Literal(\"fuzzyFileSearch\").annotate({ title: \"FuzzyFileSearchRequestMethod\" }),\n      params: ClientRequest__FuzzyFileSearchParams,\n    }).annotate({ title: \"FuzzyFileSearchRequest\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ title: \"ClientRequest\", description: \"Request from the client to the server.\" });\n\nexport type ClientRequest__AdditionalContextEntry = {\n  readonly kind: ClientRequest__AdditionalContextKind;\n  readonly value: string;\n};\nexport const ClientRequest__AdditionalContextEntry = Schema.Struct({\n  kind: ClientRequest__AdditionalContextKind,\n  value: Schema.String,\n});\n\nexport type ClientRequest__ByteRange = { readonly end: number; readonly start: number };\nexport const ClientRequest__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type ClientRequest__CapabilityRootLocation = {\n  readonly environmentId: string;\n  readonly path: string;\n  readonly type: \"environment\";\n};\nexport const ClientRequest__CapabilityRootLocation = Schema.Union(\n  [\n    Schema.Struct({\n      environmentId: Schema.String,\n      path: Schema.String.annotate({\n        description: \"Absolute path for the root in the selected environment.\",\n      }),\n      type: Schema.Literal(\"environment\").annotate({\n        title: \"EnvironmentCapabilityRootLocationType\",\n      }),\n    }).annotate({\n      title: \"EnvironmentCapabilityRootLocation\",\n      description: \"A path owned by an execution environment.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"Location used to resolve a selected capability root.\" });\n\nexport type ClientRequest__CodexResponseHandoffMode = \"thinking\" | \"commentary\" | \"bemTags\";\nexport const ClientRequest__CodexResponseHandoffMode = Schema.Literals([\n  \"thinking\",\n  \"commentary\",\n  \"bemTags\",\n]);\n\nexport type ClientRequest__CollaborationMode = {\n  readonly mode: ClientRequest__ModeKind;\n  readonly settings: ClientRequest__Settings;\n};\nexport const ClientRequest__CollaborationMode = Schema.Struct({\n  mode: ClientRequest__ModeKind,\n  settings: ClientRequest__Settings,\n}).annotate({ description: \"Collaboration mode for a Codex session.\" });\n\nexport type ClientRequest__DynamicToolSpec =\n  | {\n      readonly deferLoading?: boolean;\n      readonly description: string;\n      readonly inputSchema: unknown;\n      readonly name: string;\n      readonly type: \"function\";\n    }\n  | {\n      readonly description: string;\n      readonly name: string;\n      readonly tools: ReadonlyArray<ClientRequest__DynamicToolNamespaceTool>;\n      readonly type: \"namespace\";\n    };\nexport const ClientRequest__DynamicToolSpec = Schema.Union(\n  [\n    Schema.Struct({\n      deferLoading: Schema.optionalKey(Schema.Boolean),\n      description: Schema.String,\n      inputSchema: Schema.Unknown,\n      name: Schema.String,\n      type: Schema.Literal(\"function\").annotate({ title: \"FunctionDynamicToolSpecType\" }),\n    }).annotate({ title: \"FunctionDynamicToolSpec\" }),\n    Schema.Struct({\n      description: Schema.String,\n      name: Schema.String,\n      tools: Schema.Array(ClientRequest__DynamicToolNamespaceTool),\n      type: Schema.Literal(\"namespace\").annotate({ title: \"NamespaceDynamicToolSpecType\" }),\n    }).annotate({ title: \"NamespaceDynamicToolSpec\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const ClientRequest__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type ClientRequest__NetworkAccess = \"restricted\" | \"enabled\";\nexport const ClientRequest__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type ClientRequest__ProcessTerminalSize = { readonly cols: number; readonly rows: number };\nexport const ClientRequest__ProcessTerminalSize = Schema.Struct({\n  cols: Schema.Number.annotate({\n    description: \"Terminal width in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  rows: Schema.Number.annotate({\n    description: \"Terminal height in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"PTY size in character cells for `process/spawn` PTY sessions.\" });\n\nexport type ClientRequest__RealtimeConversationVersion = \"v1\" | \"v2\" | \"v3\";\nexport const ClientRequest__RealtimeConversationVersion = Schema.Literals([\"v1\", \"v2\", \"v3\"]);\n\nexport type ClientRequest__RealtimeOutputModality = \"text\" | \"audio\";\nexport const ClientRequest__RealtimeOutputModality = Schema.Literals([\"text\", \"audio\"]);\n\nexport type ClientRequest__RealtimeVoice =\n  | \"alloy\"\n  | \"arbor\"\n  | \"ash\"\n  | \"ballad\"\n  | \"breeze\"\n  | \"cedar\"\n  | \"coral\"\n  | \"cove\"\n  | \"echo\"\n  | \"ember\"\n  | \"juniper\"\n  | \"maple\"\n  | \"marin\"\n  | \"sage\"\n  | \"shimmer\"\n  | \"sol\"\n  | \"spruce\"\n  | \"vale\"\n  | \"verse\";\nexport const ClientRequest__RealtimeVoice = Schema.Literals([\n  \"alloy\",\n  \"arbor\",\n  \"ash\",\n  \"ballad\",\n  \"breeze\",\n  \"cedar\",\n  \"coral\",\n  \"cove\",\n  \"echo\",\n  \"ember\",\n  \"juniper\",\n  \"maple\",\n  \"marin\",\n  \"sage\",\n  \"shimmer\",\n  \"sol\",\n  \"spruce\",\n  \"vale\",\n  \"verse\",\n]);\n\nexport type ClientRequest__RemoteControlDisableParams = { readonly ephemeral?: boolean };\nexport const ClientRequest__RemoteControlDisableParams = Schema.Struct({\n  ephemeral: Schema.optionalKey(Schema.Boolean),\n});\n\nexport type ClientRequest__RemoteControlEnableParams = { readonly ephemeral?: boolean };\nexport const ClientRequest__RemoteControlEnableParams = Schema.Struct({\n  ephemeral: Schema.optionalKey(Schema.Boolean),\n});\n\nexport type ClientRequest__ResponseItem =\n  | {\n      readonly content: ReadonlyArray<ClientRequest__ContentItem>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly phase?: ClientRequest__MessagePhase | null;\n      readonly role: string;\n      readonly type: \"message\";\n    }\n  | {\n      readonly author: string;\n      readonly content: ReadonlyArray<ClientRequest__AgentMessageInputContent>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly recipient: string;\n      readonly type: \"agent_message\";\n    }\n  | {\n      readonly content?: ReadonlyArray<ClientRequest__ReasoningItemContent> | null;\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly summary: ReadonlyArray<ClientRequest__ReasoningItemReasoningSummary>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly action: ClientRequest__LocalShellAction;\n      readonly call_id?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly status: ClientRequest__LocalShellStatus;\n      readonly type: \"local_shell_call\";\n    }\n  | {\n      readonly arguments: string;\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly type: \"function_call\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"tool_search_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly output: ClientRequest__FunctionCallOutputBody;\n      readonly type: \"function_call_output\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly input: string;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly status?: string | null;\n      readonly type: \"custom_tool_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly name?: string | null;\n      readonly output: ClientRequest__FunctionCallOutputBody;\n      readonly type: \"custom_tool_call_output\";\n    }\n  | {\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly status: string;\n      readonly tools: ReadonlyArray<unknown>;\n      readonly type: \"tool_search_output\";\n    }\n  | {\n      readonly action?: ClientRequest__ResponsesApiWebSearchAction | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"web_search_call\";\n    }\n  | {\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly result: string;\n      readonly revised_prompt?: string | null;\n      readonly status: string;\n      readonly type: \"image_generation_call\";\n    }\n  | {\n      readonly encrypted_content: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"compaction\";\n    }\n  | { readonly type: \"compaction_trigger\" }\n  | {\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: ClientRequest__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"context_compaction\";\n    }\n  | { readonly type: \"other\" };\nexport const ClientRequest__ResponseItem = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.Array(ClientRequest__ContentItem),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([ClientRequest__MessagePhase, Schema.Null])),\n      role: Schema.String,\n      type: Schema.Literal(\"message\").annotate({ title: \"MessageResponseItemType\" }),\n    }).annotate({ title: \"MessageResponseItem\" }),\n    Schema.Struct({\n      author: Schema.String,\n      content: Schema.Array(ClientRequest__AgentMessageInputContent),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      recipient: Schema.String,\n      type: Schema.Literal(\"agent_message\").annotate({ title: \"AgentMessageResponseItemType\" }),\n    }).annotate({ title: \"AgentMessageResponseItem\" }),\n    Schema.Struct({\n      content: Schema.optionalKey(\n        Schema.Union([Schema.Array(ClientRequest__ReasoningItemContent), Schema.Null]),\n      ),\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      summary: Schema.Array(ClientRequest__ReasoningItemReasoningSummary),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningResponseItemType\" }),\n    }).annotate({ title: \"ReasoningResponseItem\" }),\n    Schema.Struct({\n      action: ClientRequest__LocalShellAction,\n      call_id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Set when using the Responses API.\" }),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Legacy id field retained for compatibility with older payloads.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: ClientRequest__LocalShellStatus,\n      type: Schema.Literal(\"local_shell_call\").annotate({\n        title: \"LocalShellCallResponseItemType\",\n      }),\n    }).annotate({ title: \"LocalShellCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.String,\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"function_call\").annotate({ title: \"FunctionCallResponseItemType\" }),\n    }).annotate({ title: \"FunctionCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"tool_search_call\").annotate({\n        title: \"ToolSearchCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      output: ClientRequest__FunctionCallOutputBody,\n      type: Schema.Literal(\"function_call_output\").annotate({\n        title: \"FunctionCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"FunctionCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      input: Schema.String,\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"custom_tool_call\").annotate({\n        title: \"CustomToolCallResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      output: ClientRequest__FunctionCallOutputBody,\n      type: Schema.Literal(\"custom_tool_call_output\").annotate({\n        title: \"CustomToolCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.String,\n      tools: Schema.Array(Schema.Unknown),\n      type: Schema.Literal(\"tool_search_output\").annotate({\n        title: \"ToolSearchOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchOutputResponseItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([ClientRequest__ResponsesApiWebSearchAction, Schema.Null]),\n      ),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"web_search_call\").annotate({ title: \"WebSearchCallResponseItemType\" }),\n    }).annotate({ title: \"WebSearchCallResponseItem\" }),\n    Schema.Struct({\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      result: Schema.String,\n      revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.String,\n      type: Schema.Literal(\"image_generation_call\").annotate({\n        title: \"ImageGenerationCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ImageGenerationCallResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      type: Schema.Literal(\"compaction\").annotate({ title: \"CompactionResponseItemType\" }),\n    }).annotate({ title: \"CompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"compaction_trigger\").annotate({\n        title: \"CompactionTriggerResponseItemType\",\n      }),\n    }).annotate({ title: \"CompactionTriggerResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([ClientRequest__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      type: Schema.Literal(\"context_compaction\").annotate({\n        title: \"ContextCompactionResponseItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponseItemType\" }),\n    }).annotate({ title: \"OtherResponseItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ClientRequest__SelectedCapabilityRoot = {\n  readonly id: string;\n  readonly location: {\n    readonly environmentId: string;\n    readonly path: string;\n    readonly type: \"environment\";\n  };\n};\nexport const ClientRequest__SelectedCapabilityRoot = Schema.Struct({\n  id: Schema.String.annotate({\n    description: \"Stable identifier supplied by the capability selection platform.\",\n  }),\n  location: Schema.Union(\n    [\n      Schema.Struct({\n        environmentId: Schema.String,\n        path: Schema.String.annotate({\n          description: \"Absolute path for the root in the selected environment.\",\n        }),\n        type: Schema.Literal(\"environment\").annotate({\n          title: \"EnvironmentCapabilityRootLocationType\",\n        }),\n      }).annotate({\n        title: \"EnvironmentCapabilityRootLocation\",\n        description: \"A path owned by an execution environment.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Location used to resolve a selected capability root.\" }),\n}).annotate({\n  description: \"A user-selected root that can expose one or more runtime capabilities.\",\n});\n\nexport type ClientRequest__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const ClientRequest__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type ClientRequest__ThreadMemoryMode = \"enabled\" | \"disabled\";\nexport const ClientRequest__ThreadMemoryMode = Schema.Literals([\"enabled\", \"disabled\"]);\n\nexport type ClientRequest__ThreadRealtimeAudioChunk = {\n  readonly data: string;\n  readonly itemId?: string | null;\n  readonly numChannels: number;\n  readonly sampleRate: number;\n  readonly samplesPerChannel?: number | null;\n};\nexport const ClientRequest__ThreadRealtimeAudioChunk = Schema.Struct({\n  data: Schema.String,\n  itemId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  numChannels: Schema.Number.annotate({ format: \"uint16\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  sampleRate: Schema.Number.annotate({ format: \"uint32\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  samplesPerChannel: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"EXPERIMENTAL - thread realtime audio chunk.\" });\n\nexport type ClientRequest__ThreadRealtimeInitialItem = {\n  readonly role: ClientRequest__ConversationTextRole;\n  readonly text: string;\n};\nexport const ClientRequest__ThreadRealtimeInitialItem = Schema.Struct({\n  role: ClientRequest__ConversationTextRole,\n  text: Schema.String,\n}).annotate({\n  description: \"EXPERIMENTAL - role-bearing text item included when a realtime V3 session starts.\",\n});\n\nexport type ClientRequest__ThreadRealtimeStartTransport =\n  | { readonly type: \"websocket\" }\n  | { readonly sdp: string; readonly type: \"webrtc\" };\nexport const ClientRequest__ThreadRealtimeStartTransport = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"websocket\").annotate({\n        title: \"WebsocketThreadRealtimeStartTransportType\",\n      }),\n    }).annotate({ title: \"WebsocketThreadRealtimeStartTransport\" }),\n    Schema.Struct({\n      sdp: Schema.String.annotate({\n        description:\n          \"SDP offer generated by a WebRTC RTCPeerConnection after configuring audio and the realtime events data channel.\",\n      }),\n      type: Schema.Literal(\"webrtc\").annotate({ title: \"WebrtcThreadRealtimeStartTransportType\" }),\n    }).annotate({ title: \"WebrtcThreadRealtimeStartTransport\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"EXPERIMENTAL - transport used by thread realtime.\" });\n\nexport type ClientRequest__ThreadResumeInitialTurnsPageParams = {\n  readonly itemsView?: ClientRequest__TurnItemsView | null;\n  readonly limit?: number | null;\n  readonly sortDirection?: ClientRequest__SortDirection | null;\n};\nexport const ClientRequest__ThreadResumeInitialTurnsPageParams = Schema.Struct({\n  itemsView: Schema.optionalKey(\n    Schema.Union([ClientRequest__TurnItemsView, Schema.Null]).annotate({\n      description: \"How much item detail to include for each returned turn; defaults to summary.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Optional turn page size.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  sortDirection: Schema.optionalKey(\n    Schema.Union([ClientRequest__SortDirection, Schema.Null]).annotate({\n      description: \"Optional turn pagination direction; defaults to descending.\",\n    }),\n  ),\n});\n\nexport type ClientRequest__TurnEnvironmentParams = {\n  readonly cwd: ClientRequest__LegacyAppPathString;\n  readonly environmentId: string;\n  readonly runtimeWorkspaceRoots?: ReadonlyArray<ClientRequest__LegacyAppPathString> | null;\n};\nexport const ClientRequest__TurnEnvironmentParams = Schema.Struct({\n  cwd: ClientRequest__LegacyAppPathString,\n  environmentId: Schema.String,\n  runtimeWorkspaceRoots: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ClientRequest__LegacyAppPathString).annotate({\n        description: \"Environment-native runtime workspace roots. Omitted defaults to `cwd`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type CommandExecutionRequestApprovalParams = {\n  readonly approvalId?: string | null;\n  readonly command?: string | null;\n  readonly commandActions?: ReadonlyArray<CommandExecutionRequestApprovalParams__CommandAction> | null;\n  readonly cwd?: CommandExecutionRequestApprovalParams__LegacyAppPathString | null;\n  readonly environmentId?: string | null;\n  readonly itemId: string;\n  readonly networkApprovalContext?: CommandExecutionRequestApprovalParams__NetworkApprovalContext | null;\n  readonly proposedExecpolicyAmendment?: ReadonlyArray<string> | null;\n  readonly proposedNetworkPolicyAmendments?: ReadonlyArray<CommandExecutionRequestApprovalParams__NetworkPolicyAmendment> | null;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const CommandExecutionRequestApprovalParams = Schema.Struct({\n  approvalId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Unique identifier for this specific approval callback.\\n\\nFor regular shell/unified_exec approvals, this is null.\\n\\nFor zsh-exec-bridge subcommand approvals, multiple callbacks can belong to one parent `itemId`, so `approvalId` is a distinct opaque callback id (a UUID) used to disambiguate routing.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  command: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"The command to be executed.\" }),\n      Schema.Null,\n    ]),\n  ),\n  commandActions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(CommandExecutionRequestApprovalParams__CommandAction).annotate({\n        description: \"Best-effort parsed command actions for friendly display.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      CommandExecutionRequestApprovalParams__LegacyAppPathString,\n      Schema.Null,\n    ]).annotate({ description: \"The command's working directory.\" }),\n  ),\n  environmentId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Environment in which the command will run.\" }),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  networkApprovalContext: Schema.optionalKey(\n    Schema.Union([\n      CommandExecutionRequestApprovalParams__NetworkApprovalContext,\n      Schema.Null,\n    ]).annotate({ description: \"Optional context for a managed-network approval prompt.\" }),\n  ),\n  proposedExecpolicyAmendment: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Optional proposed execpolicy amendment to allow similar commands without prompting.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  proposedNetworkPolicyAmendments: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(CommandExecutionRequestApprovalParams__NetworkPolicyAmendment).annotate({\n        description:\n          \"Optional proposed network policy amendments (allow/deny host) for future requests.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for network access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"CommandExecutionRequestApprovalParams\" });\n\nexport type CommandExecutionRequestApprovalParams__AdditionalPermissionProfile = {\n  readonly fileSystem?: CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions | null;\n  readonly network?: CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions | null;\n};\nexport const CommandExecutionRequestApprovalParams__AdditionalPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([\n      CommandExecutionRequestApprovalParams__AdditionalFileSystemPermissions,\n      Schema.Null,\n    ]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([\n      CommandExecutionRequestApprovalParams__AdditionalNetworkPermissions,\n      Schema.Null,\n    ]).annotate({ description: \"Partial overlay used for per-command permission requests.\" }),\n  ),\n});\n\nexport type CommandExecutionRequestApprovalParams__CommandExecutionApprovalDecision =\n  | \"accept\"\n  | \"acceptForSession\"\n  | {\n      readonly acceptWithExecpolicyAmendment: {\n        readonly execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | {\n      readonly applyNetworkPolicyAmendment: {\n        readonly network_policy_amendment: CommandExecutionRequestApprovalParams__NetworkPolicyAmendment;\n      };\n    }\n  | \"decline\"\n  | \"cancel\";\nexport const CommandExecutionRequestApprovalParams__CommandExecutionApprovalDecision = Schema.Union(\n  [\n    Schema.Literal(\"accept\").annotate({ description: \"User approved the command.\" }),\n    Schema.Literal(\"acceptForSession\").annotate({\n      description:\n        \"User approved the command and future prompts in the same session-scoped approval cache should run without prompting.\",\n    }),\n    Schema.Struct({\n      acceptWithExecpolicyAmendment: Schema.Struct({\n        execpolicy_amendment: Schema.Array(Schema.String),\n      }),\n    }).annotate({\n      title: \"AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision\",\n      description:\n        \"User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.\",\n    }),\n    Schema.Struct({\n      applyNetworkPolicyAmendment: Schema.Struct({\n        network_policy_amendment: CommandExecutionRequestApprovalParams__NetworkPolicyAmendment,\n      }),\n    }).annotate({\n      title: \"ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision\",\n      description: \"User chose a persistent network policy rule (allow/deny) for this host.\",\n    }),\n    Schema.Literal(\"decline\").annotate({\n      description: \"User denied the command. The agent will continue the turn.\",\n    }),\n    Schema.Literal(\"cancel\").annotate({\n      description: \"User denied the command. The turn will also be immediately interrupted.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type CommandExecutionRequestApprovalResponse = {\n  readonly decision: CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision;\n};\nexport const CommandExecutionRequestApprovalResponse = Schema.Struct({\n  decision: CommandExecutionRequestApprovalResponse__CommandExecutionApprovalDecision,\n}).annotate({ title: \"CommandExecutionRequestApprovalResponse\" });\n\nexport type DynamicToolCallParams = {\n  readonly arguments: unknown;\n  readonly callId: string;\n  readonly namespace?: string | null;\n  readonly threadId: string;\n  readonly tool: string;\n  readonly turnId: string;\n};\nexport const DynamicToolCallParams = Schema.Struct({\n  arguments: Schema.Unknown,\n  callId: Schema.String,\n  namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  tool: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"DynamicToolCallParams\" });\n\nexport type DynamicToolCallResponse = {\n  readonly contentItems: ReadonlyArray<DynamicToolCallResponse__DynamicToolCallOutputContentItem>;\n  readonly success: boolean;\n};\nexport const DynamicToolCallResponse = Schema.Struct({\n  contentItems: Schema.Array(DynamicToolCallResponse__DynamicToolCallOutputContentItem),\n  success: Schema.Boolean,\n}).annotate({ title: \"DynamicToolCallResponse\" });\n\nexport type ExecCommandApprovalParams = {\n  readonly approvalId?: string | null;\n  readonly callId: string;\n  readonly command: ReadonlyArray<string>;\n  readonly conversationId: ExecCommandApprovalParams__ThreadId;\n  readonly cwd: string;\n  readonly parsedCmd: ReadonlyArray<ExecCommandApprovalParams__ParsedCommand>;\n  readonly reason?: string | null;\n};\nexport const ExecCommandApprovalParams = Schema.Struct({\n  approvalId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Identifier for this specific approval callback.\" }),\n      Schema.Null,\n    ]),\n  ),\n  callId: Schema.String.annotate({\n    description:\n      \"Use to correlate this with [codex_protocol::protocol::ExecCommandBeginEvent] and [codex_protocol::protocol::ExecCommandEndEvent].\",\n  }),\n  command: Schema.Array(Schema.String),\n  conversationId: ExecCommandApprovalParams__ThreadId,\n  cwd: Schema.String,\n  parsedCmd: Schema.Array(ExecCommandApprovalParams__ParsedCommand),\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ExecCommandApprovalParams\" });\n\nexport type ExecCommandApprovalResponse = {\n  readonly decision: ExecCommandApprovalResponse__ReviewDecision;\n};\nexport const ExecCommandApprovalResponse = Schema.Struct({\n  decision: ExecCommandApprovalResponse__ReviewDecision,\n}).annotate({ title: \"ExecCommandApprovalResponse\" });\n\nexport type FileChangeRequestApprovalParams = {\n  readonly grantRoot?: string | null;\n  readonly itemId: string;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const FileChangeRequestApprovalParams = Schema.Struct({\n  grantRoot: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"[UNSTABLE] When set, the agent is asking the user to allow writes under this root for the remainder of the session (unclear if this is honored today).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  reason: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional explanatory reason (e.g. request for extra write access).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"FileChangeRequestApprovalParams\" });\n\nexport type FileChangeRequestApprovalResponse = {\n  readonly decision: FileChangeRequestApprovalResponse__FileChangeApprovalDecision;\n};\nexport const FileChangeRequestApprovalResponse = Schema.Struct({\n  decision: FileChangeRequestApprovalResponse__FileChangeApprovalDecision,\n}).annotate({ title: \"FileChangeRequestApprovalResponse\" });\n\nexport type FuzzyFileSearchParams = {\n  readonly cancellationToken?: string | null;\n  readonly query: string;\n  readonly roots: ReadonlyArray<string>;\n};\nexport const FuzzyFileSearchParams = Schema.Struct({\n  cancellationToken: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  query: Schema.String,\n  roots: Schema.Array(Schema.String),\n}).annotate({ title: \"FuzzyFileSearchParams\" });\n\nexport type FuzzyFileSearchResponse = {\n  readonly files: ReadonlyArray<FuzzyFileSearchResponse__FuzzyFileSearchResult>;\n};\nexport const FuzzyFileSearchResponse = Schema.Struct({\n  files: Schema.Array(FuzzyFileSearchResponse__FuzzyFileSearchResult),\n}).annotate({ title: \"FuzzyFileSearchResponse\" });\n\nexport type FuzzyFileSearchSessionCompletedNotification = { readonly sessionId: string };\nexport const FuzzyFileSearchSessionCompletedNotification = Schema.Struct({\n  sessionId: Schema.String,\n}).annotate({ title: \"FuzzyFileSearchSessionCompletedNotification\" });\n\nexport type FuzzyFileSearchSessionUpdatedNotification = {\n  readonly files: ReadonlyArray<FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult>;\n  readonly query: string;\n  readonly sessionId: string;\n};\nexport const FuzzyFileSearchSessionUpdatedNotification = Schema.Struct({\n  files: Schema.Array(FuzzyFileSearchSessionUpdatedNotification__FuzzyFileSearchResult),\n  query: Schema.String,\n  sessionId: Schema.String,\n}).annotate({ title: \"FuzzyFileSearchSessionUpdatedNotification\" });\n\nexport type GetAuthStatusParams = {\n  readonly includeToken?: boolean | null;\n  readonly refreshToken?: boolean | null;\n};\nexport const GetAuthStatusParams = Schema.Struct({\n  includeToken: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  refreshToken: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n}).annotate({ title: \"GetAuthStatusParams\" });\n\nexport type GetAuthStatusResponse = {\n  readonly authMethod: unknown | null;\n  readonly authToken: string | null;\n  readonly requiresOpenaiAuth: boolean | null;\n};\nexport const GetAuthStatusResponse = Schema.Struct({\n  authMethod: Schema.Union([Schema.Unknown, Schema.Null]),\n  authToken: Schema.Union([Schema.String, Schema.Null]),\n  requiresOpenaiAuth: Schema.Union([Schema.Boolean, Schema.Null]),\n}).annotate({ title: \"GetAuthStatusResponse\" });\n\nexport type GetConversationSummaryParams =\n  | { readonly rolloutPath: string }\n  | { readonly conversationId: string };\nexport const GetConversationSummaryParams = Schema.Union(\n  [Schema.Struct({ rolloutPath: Schema.String }), Schema.Struct({ conversationId: Schema.String })],\n  { mode: \"oneOf\" },\n).annotate({ title: \"GetConversationSummaryParams\" });\n\nexport type GetConversationSummaryResponse = { readonly summary: unknown };\nexport const GetConversationSummaryResponse = Schema.Struct({ summary: Schema.Unknown }).annotate({\n  title: \"GetConversationSummaryResponse\",\n});\n\nexport type GitDiffToRemoteParams = { readonly cwd: string };\nexport const GitDiffToRemoteParams = Schema.Struct({ cwd: Schema.String }).annotate({\n  title: \"GitDiffToRemoteParams\",\n});\n\nexport type GitDiffToRemoteResponse = { readonly sha: string; readonly diff: string };\nexport const GitDiffToRemoteResponse = Schema.Struct({\n  sha: Schema.String,\n  diff: Schema.String,\n}).annotate({ title: \"GitDiffToRemoteResponse\" });\n\nexport type JSONRPCError = {\n  readonly error: JSONRPCError__JSONRPCErrorError;\n  readonly id: JSONRPCError__RequestId;\n};\nexport const JSONRPCError = Schema.Struct({\n  error: JSONRPCError__JSONRPCErrorError,\n  id: JSONRPCError__RequestId,\n}).annotate({\n  title: \"JSONRPCError\",\n  description: \"A response to a request that indicates an error occurred.\",\n});\n\nexport type JSONRPCErrorError = {\n  readonly code: number;\n  readonly data?: unknown;\n  readonly message: string;\n};\nexport const JSONRPCErrorError = Schema.Struct({\n  code: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  data: Schema.optionalKey(Schema.Unknown),\n  message: Schema.String,\n}).annotate({ title: \"JSONRPCErrorError\" });\n\nexport type JSONRPCMessage =\n  | JSONRPCMessage__JSONRPCRequest\n  | JSONRPCMessage__JSONRPCNotification\n  | JSONRPCMessage__JSONRPCResponse\n  | JSONRPCMessage__JSONRPCError;\nexport const JSONRPCMessage = Schema.Union([\n  JSONRPCMessage__JSONRPCRequest,\n  JSONRPCMessage__JSONRPCNotification,\n  JSONRPCMessage__JSONRPCResponse,\n  JSONRPCMessage__JSONRPCError,\n]).annotate({\n  title: \"JSONRPCMessage\",\n  description:\n    \"Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.\",\n});\n\nexport type JSONRPCNotification = { readonly method: string; readonly params?: unknown };\nexport const JSONRPCNotification = Schema.Struct({\n  method: Schema.String,\n  params: Schema.optionalKey(Schema.Unknown),\n}).annotate({\n  title: \"JSONRPCNotification\",\n  description: \"A notification which does not expect a response.\",\n});\n\nexport type JSONRPCRequest = {\n  readonly id: JSONRPCRequest__RequestId;\n  readonly method: string;\n  readonly params?: unknown;\n  readonly trace?: JSONRPCRequest__W3cTraceContext | null;\n};\nexport const JSONRPCRequest = Schema.Struct({\n  id: JSONRPCRequest__RequestId,\n  method: Schema.String,\n  params: Schema.optionalKey(Schema.Unknown),\n  trace: Schema.optionalKey(\n    Schema.Union([JSONRPCRequest__W3cTraceContext, Schema.Null]).annotate({\n      description: \"Optional W3C Trace Context for distributed tracing.\",\n    }),\n  ),\n}).annotate({ title: \"JSONRPCRequest\", description: \"A request that expects a response.\" });\n\nexport type JSONRPCResponse = { readonly id: JSONRPCResponse__RequestId; readonly result: unknown };\nexport const JSONRPCResponse = Schema.Struct({\n  id: JSONRPCResponse__RequestId,\n  result: Schema.Unknown,\n}).annotate({\n  title: \"JSONRPCResponse\",\n  description: \"A successful (non-error) response to a request.\",\n});\n\nexport type McpServerElicitationRequestParams =\n  | {\n      readonly _meta?: unknown;\n      readonly message: string;\n      readonly mode: \"form\";\n      readonly requestedSchema: McpServerElicitationRequestParams__McpElicitationSchema;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly message: string;\n      readonly mode: \"openai/form\";\n      readonly requestedSchema: unknown;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    }\n  | {\n      readonly _meta?: unknown;\n      readonly elicitationId: string;\n      readonly message: string;\n      readonly mode: \"url\";\n      readonly url: string;\n      readonly serverName: string;\n      readonly threadId: string;\n      readonly turnId?: string | null;\n    };\nexport const McpServerElicitationRequestParams = Schema.Union(\n  [\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      message: Schema.String,\n      mode: Schema.Literal(\"form\"),\n      requestedSchema: McpServerElicitationRequestParams__McpElicitationSchema,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"McpServerElicitationRequestParams\" }),\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      message: Schema.String,\n      mode: Schema.Literal(\"openai/form\"),\n      requestedSchema: Schema.Unknown,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"McpServerElicitationRequestParams\" }),\n    Schema.Struct({\n      _meta: Schema.optionalKey(Schema.Unknown),\n      elicitationId: Schema.String,\n      message: Schema.String,\n      mode: Schema.Literal(\"url\"),\n      url: Schema.String,\n      serverName: Schema.String,\n      threadId: Schema.String,\n      turnId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Active Codex turn when this elicitation was observed, if app-server could correlate one.\\n\\nThis is nullable because MCP models elicitation as a standalone server-to-client request identified by the MCP server request id. It may be triggered during a turn, but turn context is app-server correlation rather than part of the protocol identity of the elicitation itself.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ title: \"McpServerElicitationRequestParams\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type McpServerElicitationRequestResponse = {\n  readonly _meta?: unknown;\n  readonly action: McpServerElicitationRequestResponse__McpServerElicitationAction;\n  readonly content?: unknown;\n};\nexport const McpServerElicitationRequestResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description: \"Optional client metadata for form-mode action handling.\",\n    }),\n  ),\n  action: McpServerElicitationRequestResponse__McpServerElicitationAction,\n  content: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description:\n        \"Structured user input for accepted elicitations, mirroring RMCP `CreateElicitationResult`.\\n\\nThis is nullable because decline/cancel responses have no content.\",\n    }),\n  ),\n}).annotate({ title: \"McpServerElicitationRequestResponse\" });\n\nexport type PermissionsRequestApprovalParams = {\n  readonly cwd: PermissionsRequestApprovalParams__AbsolutePathBuf;\n  readonly environmentId?: string | null;\n  readonly itemId: string;\n  readonly permissions: PermissionsRequestApprovalParams__RequestPermissionProfile;\n  readonly reason?: string | null;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const PermissionsRequestApprovalParams = Schema.Struct({\n  cwd: PermissionsRequestApprovalParams__AbsolutePathBuf,\n  environmentId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  itemId: Schema.String,\n  permissions: PermissionsRequestApprovalParams__RequestPermissionProfile,\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this approval request started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"PermissionsRequestApprovalParams\" });\n\nexport type PermissionsRequestApprovalResponse = {\n  readonly permissions: PermissionsRequestApprovalResponse__GrantedPermissionProfile;\n  readonly scope?: \"turn\" | \"session\";\n  readonly strictAutoReview?: boolean | null;\n};\nexport const PermissionsRequestApprovalResponse = Schema.Struct({\n  permissions: PermissionsRequestApprovalResponse__GrantedPermissionProfile,\n  scope: Schema.optionalKey(Schema.Literals([\"turn\", \"session\"]).annotate({ default: \"turn\" })),\n  strictAutoReview: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Review every subsequent command in this turn before normal sandboxed execution.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PermissionsRequestApprovalResponse\" });\n\nexport type PermissionsRequestApprovalResponse__PermissionGrantScope = \"turn\" | \"session\";\nexport const PermissionsRequestApprovalResponse__PermissionGrantScope = Schema.Literals([\n  \"turn\",\n  \"session\",\n]);\n\nexport type RequestId = string | number;\nexport const RequestId = Schema.Union([\n  Schema.String,\n  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n]).annotate({ title: \"RequestId\" });\n\nexport type ServerNotification =\n  | {\n      readonly method: \"error\";\n      readonly params: ServerNotification__ErrorNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/started\";\n      readonly params: ServerNotification__ThreadStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/status/changed\";\n      readonly params: ServerNotification__ThreadStatusChangedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/archived\";\n      readonly params: ServerNotification__ThreadArchivedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/deleted\";\n      readonly params: ServerNotification__ThreadDeletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/unarchived\";\n      readonly params: ServerNotification__ThreadUnarchivedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/closed\";\n      readonly params: ServerNotification__ThreadClosedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"skills/changed\";\n      readonly params: ServerNotification__SkillsChangedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/name/updated\";\n      readonly params: ServerNotification__ThreadNameUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/goal/updated\";\n      readonly params: ServerNotification__ThreadGoalUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/goal/cleared\";\n      readonly params: ServerNotification__ThreadGoalClearedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/environment/connected\";\n      readonly params: ServerNotification__EnvironmentConnectionNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/environment/disconnected\";\n      readonly params: ServerNotification__EnvironmentConnectionNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/settings/updated\";\n      readonly params: ServerNotification__ThreadSettingsUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/tokenUsage/updated\";\n      readonly params: ServerNotification__ThreadTokenUsageUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/started\";\n      readonly params: ServerNotification__TurnStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"hook/started\";\n      readonly params: ServerNotification__HookStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/completed\";\n      readonly params: ServerNotification__TurnCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"hook/completed\";\n      readonly params: ServerNotification__HookCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/diff/updated\";\n      readonly params: ServerNotification__TurnDiffUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/plan/updated\";\n      readonly params: ServerNotification__TurnPlanUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/started\";\n      readonly params: ServerNotification__ItemStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/autoApprovalReview/started\";\n      readonly params: ServerNotification__ItemGuardianApprovalReviewStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/autoApprovalReview/completed\";\n      readonly params: ServerNotification__ItemGuardianApprovalReviewCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/completed\";\n      readonly params: ServerNotification__ItemCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/agentMessage/delta\";\n      readonly params: ServerNotification__AgentMessageDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/plan/delta\";\n      readonly params: ServerNotification__PlanDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"command/exec/outputDelta\";\n      readonly params: ServerNotification__CommandExecOutputDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"process/outputDelta\";\n      readonly params: ServerNotification__ProcessOutputDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"process/exited\";\n      readonly params: ServerNotification__ProcessExitedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/commandExecution/outputDelta\";\n      readonly params: ServerNotification__CommandExecutionOutputDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/commandExecution/terminalInteraction\";\n      readonly params: ServerNotification__TerminalInteractionNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/fileChange/outputDelta\";\n      readonly params: ServerNotification__FileChangeOutputDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/fileChange/patchUpdated\";\n      readonly params: ServerNotification__FileChangePatchUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"serverRequest/resolved\";\n      readonly params: ServerNotification__ServerRequestResolvedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/mcpToolCall/progress\";\n      readonly params: ServerNotification__McpToolCallProgressNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"mcpServer/oauthLogin/completed\";\n      readonly params: ServerNotification__McpServerOauthLoginCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"mcpServer/startupStatus/updated\";\n      readonly params: ServerNotification__McpServerStatusUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"account/updated\";\n      readonly params: ServerNotification__AccountUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"account/rateLimits/updated\";\n      readonly params: ServerNotification__AccountRateLimitsUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"app/list/updated\";\n      readonly params: ServerNotification__AppListUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"remoteControl/status/changed\";\n      readonly params: ServerNotification__RemoteControlStatusChangedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"externalAgentConfig/import/progress\";\n      readonly params: ServerNotification__ExternalAgentConfigImportProgressNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"externalAgentConfig/import/completed\";\n      readonly params: ServerNotification__ExternalAgentConfigImportCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"fs/changed\";\n      readonly params: ServerNotification__FsChangedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/reasoning/summaryTextDelta\";\n      readonly params: ServerNotification__ReasoningSummaryTextDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/reasoning/summaryPartAdded\";\n      readonly params: ServerNotification__ReasoningSummaryPartAddedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"item/reasoning/textDelta\";\n      readonly params: ServerNotification__ReasoningTextDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/compacted\";\n      readonly params: ServerNotification__ContextCompactedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"model/rerouted\";\n      readonly params: ServerNotification__ModelReroutedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"model/verification\";\n      readonly params: ServerNotification__ModelVerificationNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"turn/moderationMetadata\";\n      readonly params: ServerNotification__TurnModerationMetadataNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"model/safetyBuffering/updated\";\n      readonly params: ServerNotification__ModelSafetyBufferingUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"warning\";\n      readonly params: ServerNotification__WarningNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"guardianWarning\";\n      readonly params: ServerNotification__GuardianWarningNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"deprecationNotice\";\n      readonly params: ServerNotification__DeprecationNoticeNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"configWarning\";\n      readonly params: ServerNotification__ConfigWarningNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"fuzzyFileSearch/sessionUpdated\";\n      readonly params: ServerNotification__FuzzyFileSearchSessionUpdatedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"fuzzyFileSearch/sessionCompleted\";\n      readonly params: ServerNotification__FuzzyFileSearchSessionCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/started\";\n      readonly params: ServerNotification__ThreadRealtimeStartedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/itemAdded\";\n      readonly params: ServerNotification__ThreadRealtimeItemAddedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/transcript/delta\";\n      readonly params: ServerNotification__ThreadRealtimeTranscriptDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/transcript/done\";\n      readonly params: ServerNotification__ThreadRealtimeTranscriptDoneNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/outputAudio/delta\";\n      readonly params: ServerNotification__ThreadRealtimeOutputAudioDeltaNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/sdp\";\n      readonly params: ServerNotification__ThreadRealtimeSdpNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/error\";\n      readonly params: ServerNotification__ThreadRealtimeErrorNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"thread/realtime/closed\";\n      readonly params: ServerNotification__ThreadRealtimeClosedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"windows/worldWritableWarning\";\n      readonly params: ServerNotification__WindowsWorldWritableWarningNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"windowsSandbox/setupCompleted\";\n      readonly params: ServerNotification__WindowsSandboxSetupCompletedNotification;\n      readonly emittedAtMs?: number;\n    }\n  | {\n      readonly method: \"account/login/completed\";\n      readonly params: ServerNotification__AccountLoginCompletedNotification;\n      readonly emittedAtMs?: number;\n    };\nexport const ServerNotification = Schema.Union(\n  [\n    Schema.Struct({\n      method: Schema.Literal(\"error\").annotate({ title: \"ErrorNotificationMethod\" }),\n      params: ServerNotification__ErrorNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/started\").annotate({\n        title: \"Thread/startedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/status/changed\").annotate({\n        title: \"Thread/status/changedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadStatusChangedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/archived\").annotate({\n        title: \"Thread/archivedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadArchivedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/deleted\").annotate({\n        title: \"Thread/deletedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadDeletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/unarchived\").annotate({\n        title: \"Thread/unarchivedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadUnarchivedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/closed\").annotate({\n        title: \"Thread/closedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadClosedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"skills/changed\").annotate({\n        title: \"Skills/changedNotificationMethod\",\n      }),\n      params: ServerNotification__SkillsChangedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/name/updated\").annotate({\n        title: \"Thread/name/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadNameUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/goal/updated\").annotate({\n        title: \"Thread/goal/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadGoalUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/goal/cleared\").annotate({\n        title: \"Thread/goal/clearedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadGoalClearedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/environment/connected\").annotate({\n        title: \"Thread/environment/connectedNotificationMethod\",\n      }),\n      params: ServerNotification__EnvironmentConnectionNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/environment/disconnected\").annotate({\n        title: \"Thread/environment/disconnectedNotificationMethod\",\n      }),\n      params: ServerNotification__EnvironmentConnectionNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/settings/updated\").annotate({\n        title: \"Thread/settings/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadSettingsUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/tokenUsage/updated\").annotate({\n        title: \"Thread/tokenUsage/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadTokenUsageUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/started\").annotate({ title: \"Turn/startedNotificationMethod\" }),\n      params: ServerNotification__TurnStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"hook/started\").annotate({ title: \"Hook/startedNotificationMethod\" }),\n      params: ServerNotification__HookStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/completed\").annotate({\n        title: \"Turn/completedNotificationMethod\",\n      }),\n      params: ServerNotification__TurnCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"hook/completed\").annotate({\n        title: \"Hook/completedNotificationMethod\",\n      }),\n      params: ServerNotification__HookCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/diff/updated\").annotate({\n        title: \"Turn/diff/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__TurnDiffUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/plan/updated\").annotate({\n        title: \"Turn/plan/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__TurnPlanUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/started\").annotate({ title: \"Item/startedNotificationMethod\" }),\n      params: ServerNotification__ItemStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/autoApprovalReview/started\").annotate({\n        title: \"Item/autoApprovalReview/startedNotificationMethod\",\n      }),\n      params: ServerNotification__ItemGuardianApprovalReviewStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/autoApprovalReview/completed\").annotate({\n        title: \"Item/autoApprovalReview/completedNotificationMethod\",\n      }),\n      params: ServerNotification__ItemGuardianApprovalReviewCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/completed\").annotate({\n        title: \"Item/completedNotificationMethod\",\n      }),\n      params: ServerNotification__ItemCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/agentMessage/delta\").annotate({\n        title: \"Item/agentMessage/deltaNotificationMethod\",\n      }),\n      params: ServerNotification__AgentMessageDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/plan/delta\").annotate({\n        title: \"Item/plan/deltaNotificationMethod\",\n      }),\n      params: ServerNotification__PlanDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"command/exec/outputDelta\").annotate({\n        title: \"Command/exec/outputDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__CommandExecOutputDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"process/outputDelta\").annotate({\n        title: \"Process/outputDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__ProcessOutputDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"process/exited\").annotate({\n        title: \"Process/exitedNotificationMethod\",\n      }),\n      params: ServerNotification__ProcessExitedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/commandExecution/outputDelta\").annotate({\n        title: \"Item/commandExecution/outputDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__CommandExecutionOutputDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/commandExecution/terminalInteraction\").annotate({\n        title: \"Item/commandExecution/terminalInteractionNotificationMethod\",\n      }),\n      params: ServerNotification__TerminalInteractionNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/fileChange/outputDelta\").annotate({\n        title: \"Item/fileChange/outputDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__FileChangeOutputDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/fileChange/patchUpdated\").annotate({\n        title: \"Item/fileChange/patchUpdatedNotificationMethod\",\n      }),\n      params: ServerNotification__FileChangePatchUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"serverRequest/resolved\").annotate({\n        title: \"ServerRequest/resolvedNotificationMethod\",\n      }),\n      params: ServerNotification__ServerRequestResolvedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/mcpToolCall/progress\").annotate({\n        title: \"Item/mcpToolCall/progressNotificationMethod\",\n      }),\n      params: ServerNotification__McpToolCallProgressNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"mcpServer/oauthLogin/completed\").annotate({\n        title: \"McpServer/oauthLogin/completedNotificationMethod\",\n      }),\n      params: ServerNotification__McpServerOauthLoginCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"mcpServer/startupStatus/updated\").annotate({\n        title: \"McpServer/startupStatus/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__McpServerStatusUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"account/updated\").annotate({\n        title: \"Account/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__AccountUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"account/rateLimits/updated\").annotate({\n        title: \"Account/rateLimits/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__AccountRateLimitsUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"app/list/updated\").annotate({\n        title: \"App/list/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__AppListUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"remoteControl/status/changed\").annotate({\n        title: \"RemoteControl/status/changedNotificationMethod\",\n      }),\n      params: ServerNotification__RemoteControlStatusChangedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"externalAgentConfig/import/progress\").annotate({\n        title: \"ExternalAgentConfig/import/progressNotificationMethod\",\n      }),\n      params: ServerNotification__ExternalAgentConfigImportProgressNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"externalAgentConfig/import/completed\").annotate({\n        title: \"ExternalAgentConfig/import/completedNotificationMethod\",\n      }),\n      params: ServerNotification__ExternalAgentConfigImportCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"fs/changed\").annotate({ title: \"Fs/changedNotificationMethod\" }),\n      params: ServerNotification__FsChangedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/reasoning/summaryTextDelta\").annotate({\n        title: \"Item/reasoning/summaryTextDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__ReasoningSummaryTextDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/reasoning/summaryPartAdded\").annotate({\n        title: \"Item/reasoning/summaryPartAddedNotificationMethod\",\n      }),\n      params: ServerNotification__ReasoningSummaryPartAddedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"item/reasoning/textDelta\").annotate({\n        title: \"Item/reasoning/textDeltaNotificationMethod\",\n      }),\n      params: ServerNotification__ReasoningTextDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/compacted\").annotate({\n        title: \"Thread/compactedNotificationMethod\",\n      }),\n      params: ServerNotification__ContextCompactedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"model/rerouted\").annotate({\n        title: \"Model/reroutedNotificationMethod\",\n      }),\n      params: ServerNotification__ModelReroutedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"model/verification\").annotate({\n        title: \"Model/verificationNotificationMethod\",\n      }),\n      params: ServerNotification__ModelVerificationNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"turn/moderationMetadata\").annotate({\n        title: \"Turn/moderationMetadataNotificationMethod\",\n      }),\n      params: ServerNotification__TurnModerationMetadataNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"model/safetyBuffering/updated\").annotate({\n        title: \"Model/safetyBuffering/updatedNotificationMethod\",\n      }),\n      params: ServerNotification__ModelSafetyBufferingUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"warning\").annotate({ title: \"WarningNotificationMethod\" }),\n      params: ServerNotification__WarningNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"guardianWarning\").annotate({\n        title: \"GuardianWarningNotificationMethod\",\n      }),\n      params: ServerNotification__GuardianWarningNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"deprecationNotice\").annotate({\n        title: \"DeprecationNoticeNotificationMethod\",\n      }),\n      params: ServerNotification__DeprecationNoticeNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"configWarning\").annotate({\n        title: \"ConfigWarningNotificationMethod\",\n      }),\n      params: ServerNotification__ConfigWarningNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"fuzzyFileSearch/sessionUpdated\").annotate({\n        title: \"FuzzyFileSearch/sessionUpdatedNotificationMethod\",\n      }),\n      params: ServerNotification__FuzzyFileSearchSessionUpdatedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"fuzzyFileSearch/sessionCompleted\").annotate({\n        title: \"FuzzyFileSearch/sessionCompletedNotificationMethod\",\n      }),\n      params: ServerNotification__FuzzyFileSearchSessionCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/started\").annotate({\n        title: \"Thread/realtime/startedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeStartedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/itemAdded\").annotate({\n        title: \"Thread/realtime/itemAddedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeItemAddedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/transcript/delta\").annotate({\n        title: \"Thread/realtime/transcript/deltaNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeTranscriptDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/transcript/done\").annotate({\n        title: \"Thread/realtime/transcript/doneNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeTranscriptDoneNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/outputAudio/delta\").annotate({\n        title: \"Thread/realtime/outputAudio/deltaNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeOutputAudioDeltaNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/sdp\").annotate({\n        title: \"Thread/realtime/sdpNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeSdpNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/error\").annotate({\n        title: \"Thread/realtime/errorNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeErrorNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"thread/realtime/closed\").annotate({\n        title: \"Thread/realtime/closedNotificationMethod\",\n      }),\n      params: ServerNotification__ThreadRealtimeClosedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"windows/worldWritableWarning\").annotate({\n        title: \"Windows/worldWritableWarningNotificationMethod\",\n      }),\n      params: ServerNotification__WindowsWorldWritableWarningNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"windowsSandbox/setupCompleted\").annotate({\n        title: \"WindowsSandbox/setupCompletedNotificationMethod\",\n      }),\n      params: ServerNotification__WindowsSandboxSetupCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n    Schema.Struct({\n      method: Schema.Literal(\"account/login/completed\").annotate({\n        title: \"Account/login/completedNotificationMethod\",\n      }),\n      params: ServerNotification__AccountLoginCompletedNotification,\n      emittedAtMs: Schema.optionalKey(\n        Schema.Number.annotate({\n          description:\n            \"Unix timestamp (in milliseconds) when app-server emitted this notification.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n      ),\n    }).annotate({\n      title: \"ServerNotification\",\n      description: \"Notification sent from the server to the client.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ByteRange = { readonly end: number; readonly start: number };\nexport const ServerNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type ServerNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const ServerNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type ServerNotification__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const ServerNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type ServerNotification__CommandExecOutputStream = \"stdout\" | \"stderr\";\nexport const ServerNotification__CommandExecOutputStream = Schema.Literals([\n  \"stdout\",\n  \"stderr\",\n]).annotate({ description: \"Stream label for `command/exec/outputDelta` notifications.\" });\n\nexport type ServerNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const ServerNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type ServerNotification__HookSource =\n  | \"system\"\n  | \"user\"\n  | \"project\"\n  | \"mdm\"\n  | \"sessionFlags\"\n  | \"plugin\"\n  | \"cloudRequirements\"\n  | \"cloudManagedConfig\"\n  | \"legacyManagedConfigFile\"\n  | \"legacyManagedConfigMdm\"\n  | \"unknown\";\nexport const ServerNotification__HookSource = Schema.Literals([\n  \"system\",\n  \"user\",\n  \"project\",\n  \"mdm\",\n  \"sessionFlags\",\n  \"plugin\",\n  \"cloudRequirements\",\n  \"cloudManagedConfig\",\n  \"legacyManagedConfigFile\",\n  \"legacyManagedConfigMdm\",\n  \"unknown\",\n]);\n\nexport type ServerNotification__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const ServerNotification__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type ServerNotification__NetworkAccess = \"restricted\" | \"enabled\";\nexport const ServerNotification__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type ServerNotification__ProcessOutputStream = \"stdout\" | \"stderr\";\nexport const ServerNotification__ProcessOutputStream = Schema.Literals([\n  \"stdout\",\n  \"stderr\",\n]).annotate({ description: \"Stream label for `process/outputDelta` notifications.\" });\n\nexport type ServerNotification__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: ServerNotification__SubAgentSource };\nexport const ServerNotification__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: ServerNotification__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ServerNotification__ThreadExtra = {};\nexport const ServerNotification__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type ServerNotification__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const ServerNotification__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type ServerNotification__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const ServerNotification__TurnItemsView = Schema.Literals([\"notLoaded\", \"summary\", \"full\"]);\n\nexport type ServerRequest =\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/commandExecution/requestApproval\";\n      readonly params: ServerRequest__CommandExecutionRequestApprovalParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/fileChange/requestApproval\";\n      readonly params: ServerRequest__FileChangeRequestApprovalParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/tool/requestUserInput\";\n      readonly params: ServerRequest__ToolRequestUserInputParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"mcpServer/elicitation/request\";\n      readonly params: ServerRequest__McpServerElicitationRequestParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/permissions/requestApproval\";\n      readonly params: ServerRequest__PermissionsRequestApprovalParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"item/tool/call\";\n      readonly params: ServerRequest__DynamicToolCallParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"account/chatgptAuthTokens/refresh\";\n      readonly params: ServerRequest__ChatgptAuthTokensRefreshParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"attestation/generate\";\n      readonly params: ServerRequest__AttestationGenerateParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"applyPatchApproval\";\n      readonly params: ServerRequest__ApplyPatchApprovalParams;\n    }\n  | {\n      readonly id: ServerRequest__RequestId;\n      readonly method: \"execCommandApproval\";\n      readonly params: ServerRequest__ExecCommandApprovalParams;\n    };\nexport const ServerRequest = Schema.Union(\n  [\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/commandExecution/requestApproval\").annotate({\n        title: \"Item/commandExecution/requestApprovalRequestMethod\",\n      }),\n      params: ServerRequest__CommandExecutionRequestApprovalParams,\n    }).annotate({\n      title: \"Item/commandExecution/requestApprovalRequest\",\n      description:\n        \"NEW APIs Sent when approval is requested for a specific command execution. This request is used for Turns started via turn/start.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/fileChange/requestApproval\").annotate({\n        title: \"Item/fileChange/requestApprovalRequestMethod\",\n      }),\n      params: ServerRequest__FileChangeRequestApprovalParams,\n    }).annotate({\n      title: \"Item/fileChange/requestApprovalRequest\",\n      description:\n        \"Sent when approval is requested for a specific file change. This request is used for Turns started via turn/start.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/tool/requestUserInput\").annotate({\n        title: \"Item/tool/requestUserInputRequestMethod\",\n      }),\n      params: ServerRequest__ToolRequestUserInputParams,\n    }).annotate({\n      title: \"Item/tool/requestUserInputRequest\",\n      description: \"EXPERIMENTAL - Request input from the user for a tool call.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"mcpServer/elicitation/request\").annotate({\n        title: \"McpServer/elicitation/requestRequestMethod\",\n      }),\n      params: ServerRequest__McpServerElicitationRequestParams,\n    }).annotate({\n      title: \"McpServer/elicitation/requestRequest\",\n      description: \"Request input for an MCP server elicitation.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/permissions/requestApproval\").annotate({\n        title: \"Item/permissions/requestApprovalRequestMethod\",\n      }),\n      params: ServerRequest__PermissionsRequestApprovalParams,\n    }).annotate({\n      title: \"Item/permissions/requestApprovalRequest\",\n      description: \"Request approval for additional permissions from the user.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"item/tool/call\").annotate({ title: \"Item/tool/callRequestMethod\" }),\n      params: ServerRequest__DynamicToolCallParams,\n    }).annotate({\n      title: \"Item/tool/callRequest\",\n      description: \"Execute a dynamic tool call on the client.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"account/chatgptAuthTokens/refresh\").annotate({\n        title: \"Account/chatgptAuthTokens/refreshRequestMethod\",\n      }),\n      params: ServerRequest__ChatgptAuthTokensRefreshParams,\n    }).annotate({ title: \"Account/chatgptAuthTokens/refreshRequest\" }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"attestation/generate\").annotate({\n        title: \"Attestation/generateRequestMethod\",\n      }),\n      params: ServerRequest__AttestationGenerateParams,\n    }).annotate({\n      title: \"Attestation/generateRequest\",\n      description: \"Generate a fresh upstream attestation result on demand.\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"applyPatchApproval\").annotate({\n        title: \"ApplyPatchApprovalRequestMethod\",\n      }),\n      params: ServerRequest__ApplyPatchApprovalParams,\n    }).annotate({\n      title: \"ApplyPatchApprovalRequest\",\n      description:\n        \"DEPRECATED APIs below Request to approve a patch. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).\",\n    }),\n    Schema.Struct({\n      id: ServerRequest__RequestId,\n      method: Schema.Literal(\"execCommandApproval\").annotate({\n        title: \"ExecCommandApprovalRequestMethod\",\n      }),\n      params: ServerRequest__ExecCommandApprovalParams,\n    }).annotate({\n      title: \"ExecCommandApprovalRequest\",\n      description:\n        \"Request to exec a command. This request is used for Turns started via the legacy APIs (i.e. SendUserTurn, SendUserMessage).\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  title: \"ServerRequest\",\n  description: \"Request initiated from the server and sent to the client.\",\n});\n\nexport type ServerRequest__AdditionalPermissionProfile = {\n  readonly fileSystem?: ServerRequest__AdditionalFileSystemPermissions | null;\n  readonly network?: ServerRequest__AdditionalNetworkPermissions | null;\n};\nexport const ServerRequest__AdditionalPermissionProfile = Schema.Struct({\n  fileSystem: Schema.optionalKey(\n    Schema.Union([ServerRequest__AdditionalFileSystemPermissions, Schema.Null]),\n  ),\n  network: Schema.optionalKey(\n    Schema.Union([ServerRequest__AdditionalNetworkPermissions, Schema.Null]).annotate({\n      description: \"Partial overlay used for per-command permission requests.\",\n    }),\n  ),\n});\n\nexport type ServerRequest__CommandExecutionApprovalDecision =\n  | \"accept\"\n  | \"acceptForSession\"\n  | {\n      readonly acceptWithExecpolicyAmendment: {\n        readonly execpolicy_amendment: ReadonlyArray<string>;\n      };\n    }\n  | {\n      readonly applyNetworkPolicyAmendment: {\n        readonly network_policy_amendment: ServerRequest__NetworkPolicyAmendment;\n      };\n    }\n  | \"decline\"\n  | \"cancel\";\nexport const ServerRequest__CommandExecutionApprovalDecision = Schema.Union(\n  [\n    Schema.Literal(\"accept\").annotate({ description: \"User approved the command.\" }),\n    Schema.Literal(\"acceptForSession\").annotate({\n      description:\n        \"User approved the command and future prompts in the same session-scoped approval cache should run without prompting.\",\n    }),\n    Schema.Struct({\n      acceptWithExecpolicyAmendment: Schema.Struct({\n        execpolicy_amendment: Schema.Array(Schema.String),\n      }),\n    }).annotate({\n      title: \"AcceptWithExecpolicyAmendmentCommandExecutionApprovalDecision\",\n      description:\n        \"User approved the command, and wants to apply the proposed execpolicy amendment so future matching commands can run without prompting.\",\n    }),\n    Schema.Struct({\n      applyNetworkPolicyAmendment: Schema.Struct({\n        network_policy_amendment: ServerRequest__NetworkPolicyAmendment,\n      }),\n    }).annotate({\n      title: \"ApplyNetworkPolicyAmendmentCommandExecutionApprovalDecision\",\n      description: \"User chose a persistent network policy rule (allow/deny) for this host.\",\n    }),\n    Schema.Literal(\"decline\").annotate({\n      description: \"User denied the command. The agent will continue the turn.\",\n    }),\n    Schema.Literal(\"cancel\").annotate({\n      description: \"User denied the command. The turn will also be immediately interrupted.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type ToolRequestUserInputParams = {\n  readonly autoResolutionMs?: number | null;\n  readonly itemId: string;\n  readonly questions: ReadonlyArray<ToolRequestUserInputParams__ToolRequestUserInputQuestion>;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const ToolRequestUserInputParams = Schema.Struct({\n  autoResolutionMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  itemId: Schema.String,\n  questions: Schema.Array(ToolRequestUserInputParams__ToolRequestUserInputQuestion),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"ToolRequestUserInputParams\",\n  description: \"EXPERIMENTAL. Params sent with a request_user_input event.\",\n});\n\nexport type ToolRequestUserInputResponse = {\n  readonly answers: {\n    readonly [x: string]: ToolRequestUserInputResponse__ToolRequestUserInputAnswer;\n  };\n};\nexport const ToolRequestUserInputResponse = Schema.Struct({\n  answers: Schema.Record(Schema.String, ToolRequestUserInputResponse__ToolRequestUserInputAnswer),\n}).annotate({\n  title: \"ToolRequestUserInputResponse\",\n  description: \"EXPERIMENTAL. Response payload mapping question ids to answers.\",\n});\n\nexport type V1InitializeParams = {\n  readonly capabilities?: V1InitializeParams__InitializeCapabilities | null;\n  readonly clientInfo: V1InitializeParams__ClientInfo;\n};\nexport const V1InitializeParams = Schema.Struct({\n  capabilities: Schema.optionalKey(\n    Schema.Union([V1InitializeParams__InitializeCapabilities, Schema.Null]),\n  ),\n  clientInfo: V1InitializeParams__ClientInfo,\n}).annotate({ title: \"InitializeParams\" });\n\nexport type V1InitializeResponse = {\n  readonly codexHome: string;\n  readonly platformFamily: string;\n  readonly platformOs: string;\n  readonly userAgent: string;\n};\nexport const V1InitializeResponse = Schema.Struct({\n  codexHome: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  platformFamily: Schema.String.annotate({\n    description:\n      'Platform family for the running app-server target, for example `\"unix\"` or `\"windows\"`.',\n  }),\n  platformOs: Schema.String.annotate({\n    description:\n      'Operating system for the running app-server target, for example `\"macos\"`, `\"linux\"`, or `\"windows\"`.',\n  }),\n  userAgent: Schema.String,\n}).annotate({ title: \"InitializeResponse\" });\n\nexport type V1InitializeResponse__AbsolutePathBuf = string;\nexport const V1InitializeResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2AccountLoginCompletedNotification = {\n  readonly error?: string | null;\n  readonly loginId?: string | null;\n  readonly success: boolean;\n};\nexport const V2AccountLoginCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  loginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  success: Schema.Boolean,\n}).annotate({ title: \"AccountLoginCompletedNotification\" });\n\nexport type V2AccountRateLimitsUpdatedNotification = {\n  readonly rateLimits: V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot;\n};\nexport const V2AccountRateLimitsUpdatedNotification = Schema.Struct({\n  rateLimits: V2AccountRateLimitsUpdatedNotification__RateLimitSnapshot,\n}).annotate({\n  title: \"AccountRateLimitsUpdatedNotification\",\n  description:\n    \"Sparse rolling rate-limit update.\\n\\nClients should merge available values into the most recent `account/rateLimits/read` response or refetch that snapshot. Nullable account metadata may be unavailable in a rolling update and does not clear a previously observed value.\",\n});\n\nexport type V2AccountUpdatedNotification = {\n  readonly authMode?: V2AccountUpdatedNotification__AuthMode | null;\n  readonly planType?: V2AccountUpdatedNotification__PlanType | null;\n};\nexport const V2AccountUpdatedNotification = Schema.Struct({\n  authMode: Schema.optionalKey(Schema.Union([V2AccountUpdatedNotification__AuthMode, Schema.Null])),\n  planType: Schema.optionalKey(Schema.Union([V2AccountUpdatedNotification__PlanType, Schema.Null])),\n}).annotate({ title: \"AccountUpdatedNotification\" });\n\nexport type V2AgentMessageDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2AgentMessageDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"AgentMessageDeltaNotification\" });\n\nexport type V2AppListUpdatedNotification = {\n  readonly data: ReadonlyArray<V2AppListUpdatedNotification__AppInfo>;\n};\nexport const V2AppListUpdatedNotification = Schema.Struct({\n  data: Schema.Array(V2AppListUpdatedNotification__AppInfo),\n}).annotate({\n  title: \"AppListUpdatedNotification\",\n  description: \"EXPERIMENTAL - notification emitted when the app list changes.\",\n});\n\nexport type V2AppsInstalledParams = {\n  readonly forceRefresh?: boolean;\n  readonly threadId?: string | null;\n};\nexport const V2AppsInstalledParams = Schema.Struct({\n  forceRefresh: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true and Apps are permitted, refresh and publish the hosted connector runtime tool snapshot first.\",\n    }),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional loaded thread id used to evaluate effective app configuration.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  title: \"AppsInstalledParams\",\n  description: \"Read the committed installed connector runtime snapshot.\",\n});\n\nexport type V2AppsInstalledResponse = {\n  readonly apps: ReadonlyArray<V2AppsInstalledResponse__InstalledApp>;\n};\nexport const V2AppsInstalledResponse = Schema.Struct({\n  apps: Schema.Array(V2AppsInstalledResponse__InstalledApp),\n}).annotate({\n  title: \"AppsInstalledResponse\",\n  description: \"The installed connectors in one committed runtime snapshot.\",\n});\n\nexport type V2AppsListParams = {\n  readonly cursor?: string | null;\n  readonly forceRefetch?: boolean;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const V2AppsListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  forceRefetch: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, bypass app caches and fetch the latest data from sources.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional thread id used to evaluate app feature gating from that thread's config.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  title: \"AppsListParams\",\n  description: \"EXPERIMENTAL - list available apps/connectors.\",\n});\n\nexport type V2AppsListResponse = {\n  readonly data: ReadonlyArray<V2AppsListResponse__AppInfo>;\n  readonly nextCursor?: string | null;\n};\nexport const V2AppsListResponse = Schema.Struct({\n  data: Schema.Array(V2AppsListResponse__AppInfo),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"AppsListResponse\", description: \"EXPERIMENTAL - app list response.\" });\n\nexport type V2AppsReadParams = {\n  readonly appIds: ReadonlyArray<string>;\n  readonly includeTools?: boolean;\n};\nexport const V2AppsReadParams = Schema.Struct({\n  appIds: Schema.Array(Schema.String).annotate({\n    description:\n      \"App ids to read. The server accepts at most 100 ids and deduplicates repeated ids while preserving their first-request order.\",\n  }),\n  includeTools: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, include display-only public tool summaries in the returned metadata.\",\n    }),\n  ),\n}).annotate({\n  title: \"AppsReadParams\",\n  description: \"EXPERIMENTAL - read metadata for specific apps/connectors.\",\n});\n\nexport type V2AppsReadResponse = {\n  readonly apps: ReadonlyArray<V2AppsReadResponse__ConnectorMetadata>;\n  readonly missingAppIds: ReadonlyArray<string>;\n};\nexport const V2AppsReadResponse = Schema.Struct({\n  apps: Schema.Array(V2AppsReadResponse__ConnectorMetadata),\n  missingAppIds: Schema.Array(Schema.String),\n}).annotate({ title: \"AppsReadResponse\", description: \"EXPERIMENTAL - app/read response.\" });\n\nexport type V2CancelLoginAccountParams = { readonly loginId: string };\nexport const V2CancelLoginAccountParams = Schema.Struct({ loginId: Schema.String }).annotate({\n  title: \"CancelLoginAccountParams\",\n});\n\nexport type V2CancelLoginAccountResponse = {\n  readonly status: V2CancelLoginAccountResponse__CancelLoginAccountStatus;\n};\nexport const V2CancelLoginAccountResponse = Schema.Struct({\n  status: V2CancelLoginAccountResponse__CancelLoginAccountStatus,\n}).annotate({ title: \"CancelLoginAccountResponse\" });\n\nexport type V2CommandExecOutputDeltaNotification = {\n  readonly capReached: boolean;\n  readonly deltaBase64: string;\n  readonly processId: string;\n  readonly stream: \"stdout\" | \"stderr\";\n};\nexport const V2CommandExecOutputDeltaNotification = Schema.Struct({\n  capReached: Schema.Boolean.annotate({\n    description:\n      \"`true` on the final streamed chunk for a stream when `outputBytesCap` truncated later output on that stream.\",\n  }),\n  deltaBase64: Schema.String.annotate({ description: \"Base64-encoded output bytes.\" }),\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n  stream: Schema.Literals([\"stdout\", \"stderr\"]).annotate({\n    description: \"Stream label for `command/exec/outputDelta` notifications.\",\n  }),\n}).annotate({\n  title: \"CommandExecOutputDeltaNotification\",\n  description:\n    \"Base64-encoded output chunk emitted for a streaming `command/exec` request.\\n\\nThese notifications are connection-scoped. If the originating connection closes, the server terminates the process.\",\n});\n\nexport type V2CommandExecOutputDeltaNotification__CommandExecOutputStream = \"stdout\" | \"stderr\";\nexport const V2CommandExecOutputDeltaNotification__CommandExecOutputStream = Schema.Literals([\n  \"stdout\",\n  \"stderr\",\n]).annotate({ description: \"Stream label for `command/exec/outputDelta` notifications.\" });\n\nexport type V2CommandExecParams = {\n  readonly command: ReadonlyArray<string>;\n  readonly cwd?: string | null;\n  readonly disableOutputCap?: boolean;\n  readonly disableTimeout?: boolean;\n  readonly env?: { readonly [x: string]: string | null } | null;\n  readonly outputBytesCap?: number | null;\n  readonly processId?: string | null;\n  readonly sandboxPolicy?: V2CommandExecParams__SandboxPolicy | null;\n  readonly size?: V2CommandExecParams__CommandExecTerminalSize | null;\n  readonly streamStdin?: boolean;\n  readonly streamStdoutStderr?: boolean;\n  readonly timeoutMs?: number | null;\n  readonly tty?: boolean;\n};\nexport const V2CommandExecParams = Schema.Struct({\n  command: Schema.Array(Schema.String).annotate({\n    description: \"Command argv vector. Empty arrays are rejected.\",\n  }),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional working directory. Defaults to the server cwd.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  disableOutputCap: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Disable stdout/stderr capture truncation for this request.\\n\\nCannot be combined with `outputBytesCap`.\",\n    }),\n  ),\n  disableTimeout: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Disable the timeout entirely for this request.\\n\\nCannot be combined with `timeoutMs`.\",\n    }),\n  ),\n  env: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Union([Schema.String, Schema.Null])).annotate({\n        description:\n          \"Optional environment overrides merged into the server-computed environment.\\n\\nMatching names override inherited values. Set a key to `null` to unset an inherited variable.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outputBytesCap: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Optional per-stream stdout/stderr capture cap in bytes.\\n\\nWhen omitted, the server default applies. Cannot be combined with `disableOutputCap`.\",\n        format: \"uint\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  processId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional client-supplied, connection-scoped process id.\\n\\nRequired for `tty`, `streamStdin`, `streamStdoutStderr`, and follow-up `command/exec/write`, `command/exec/resize`, and `command/exec/terminate` calls. When omitted, buffered execution gets an internal id that is not exposed to the client.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sandboxPolicy: Schema.optionalKey(\n    Schema.Union([V2CommandExecParams__SandboxPolicy, Schema.Null]).annotate({\n      description:\n        \"Optional sandbox policy for this command.\\n\\nUses the same shape as thread/turn execution sandbox configuration and defaults to the user's configured policy when omitted. Cannot be combined with `permissionProfile`.\",\n    }),\n  ),\n  size: Schema.optionalKey(\n    Schema.Union([V2CommandExecParams__CommandExecTerminalSize, Schema.Null]).annotate({\n      description: \"Optional initial PTY size in character cells. Only valid when `tty` is true.\",\n    }),\n  ),\n  streamStdin: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Allow follow-up `command/exec/write` requests to write stdin bytes.\\n\\nRequires a client-supplied `processId`.\",\n    }),\n  ),\n  streamStdoutStderr: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Stream stdout/stderr via `command/exec/outputDelta` notifications.\\n\\nStreamed bytes are not duplicated into the final response and require a client-supplied `processId`.\",\n    }),\n  ),\n  timeoutMs: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Optional timeout in milliseconds.\\n\\nWhen omitted, the server default applies. Cannot be combined with `disableTimeout`.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  tty: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Enable PTY mode.\\n\\nThis implies `streamStdin` and `streamStdoutStderr`.\",\n    }),\n  ),\n}).annotate({\n  title: \"CommandExecParams\",\n  description:\n    \"Run a standalone command (argv vector) in the server sandbox without creating a thread or turn.\\n\\nThe final `command/exec` response is deferred until the process exits and is sent only after all `command/exec/outputDelta` notifications for that connection have been emitted.\",\n});\n\nexport type V2CommandExecParams__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2CommandExecParams__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2CommandExecResizeParams = {\n  readonly processId: string;\n  readonly size: { readonly cols: number; readonly rows: number };\n};\nexport const V2CommandExecResizeParams = Schema.Struct({\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n  size: Schema.Struct({\n    cols: Schema.Number.annotate({\n      description: \"Terminal width in character cells.\",\n      format: \"uint16\",\n    })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n    rows: Schema.Number.annotate({\n      description: \"Terminal height in character cells.\",\n      format: \"uint16\",\n    })\n      .check(Schema.isInt())\n      .check(Schema.isGreaterThanOrEqualTo(0)),\n  }).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" }),\n}).annotate({\n  title: \"CommandExecResizeParams\",\n  description: \"Resize a running PTY-backed `command/exec` session.\",\n});\n\nexport type V2CommandExecResizeParams__CommandExecTerminalSize = {\n  readonly cols: number;\n  readonly rows: number;\n};\nexport const V2CommandExecResizeParams__CommandExecTerminalSize = Schema.Struct({\n  cols: Schema.Number.annotate({\n    description: \"Terminal width in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  rows: Schema.Number.annotate({\n    description: \"Terminal height in character cells.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({ description: \"PTY size in character cells for `command/exec` PTY sessions.\" });\n\nexport type V2CommandExecResizeResponse = {};\nexport const V2CommandExecResizeResponse = Schema.Struct({}).annotate({\n  title: \"CommandExecResizeResponse\",\n  description: \"Empty success response for `command/exec/resize`.\",\n});\n\nexport type V2CommandExecResponse = {\n  readonly exitCode: number;\n  readonly stderr: string;\n  readonly stdout: string;\n};\nexport const V2CommandExecResponse = Schema.Struct({\n  exitCode: Schema.Number.annotate({ description: \"Process exit code.\", format: \"int32\" }).check(\n    Schema.isInt(),\n  ),\n  stderr: Schema.String.annotate({\n    description:\n      \"Buffered stderr capture.\\n\\nEmpty when stderr was streamed via `command/exec/outputDelta`.\",\n  }),\n  stdout: Schema.String.annotate({\n    description:\n      \"Buffered stdout capture.\\n\\nEmpty when stdout was streamed via `command/exec/outputDelta`.\",\n  }),\n}).annotate({\n  title: \"CommandExecResponse\",\n  description: \"Final buffered result for `command/exec`.\",\n});\n\nexport type V2CommandExecTerminateParams = { readonly processId: string };\nexport const V2CommandExecTerminateParams = Schema.Struct({\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n}).annotate({\n  title: \"CommandExecTerminateParams\",\n  description: \"Terminate a running `command/exec` session.\",\n});\n\nexport type V2CommandExecTerminateResponse = {};\nexport const V2CommandExecTerminateResponse = Schema.Struct({}).annotate({\n  title: \"CommandExecTerminateResponse\",\n  description: \"Empty success response for `command/exec/terminate`.\",\n});\n\nexport type V2CommandExecutionOutputDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2CommandExecutionOutputDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"CommandExecutionOutputDeltaNotification\" });\n\nexport type V2CommandExecWriteParams = {\n  readonly closeStdin?: boolean;\n  readonly deltaBase64?: string | null;\n  readonly processId: string;\n};\nexport const V2CommandExecWriteParams = Schema.Struct({\n  closeStdin: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Close stdin after writing `deltaBase64`, if present.\",\n    }),\n  ),\n  deltaBase64: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional base64-encoded stdin bytes to write.\" }),\n      Schema.Null,\n    ]),\n  ),\n  processId: Schema.String.annotate({\n    description:\n      \"Client-supplied, connection-scoped `processId` from the original `command/exec` request.\",\n  }),\n}).annotate({\n  title: \"CommandExecWriteParams\",\n  description: \"Write stdin bytes to a running `command/exec` session, close stdin, or both.\",\n});\n\nexport type V2CommandExecWriteResponse = {};\nexport const V2CommandExecWriteResponse = Schema.Struct({}).annotate({\n  title: \"CommandExecWriteResponse\",\n  description: \"Empty success response for `command/exec/write`.\",\n});\n\nexport type V2ConfigBatchWriteParams = {\n  readonly edits: ReadonlyArray<V2ConfigBatchWriteParams__ConfigEdit>;\n  readonly expectedVersion?: string | null;\n  readonly filePath?: string | null;\n  readonly reloadUserConfig?: boolean;\n};\nexport const V2ConfigBatchWriteParams = Schema.Struct({\n  edits: Schema.Array(V2ConfigBatchWriteParams__ConfigEdit),\n  expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  filePath: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Path to the config file to write; defaults to the user's `config.toml` when omitted.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  reloadUserConfig: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When true, hot-reload the updated user config into all loaded threads after writing.\",\n    }),\n  ),\n}).annotate({ title: \"ConfigBatchWriteParams\" });\n\nexport type V2ConfigReadParams = { readonly cwd?: string | null; readonly includeLayers?: boolean };\nexport const V2ConfigReadParams = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional working directory to resolve project config layers. If specified, return the effective config as seen from that directory (i.e., including any project layers between `cwd` and the project/repo root).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeLayers: Schema.optionalKey(Schema.Boolean),\n}).annotate({ title: \"ConfigReadParams\" });\n\nexport type V2ConfigReadResponse = {\n  readonly config: V2ConfigReadResponse__Config;\n  readonly layers?: ReadonlyArray<V2ConfigReadResponse__ConfigLayer> | null;\n  readonly origins: { readonly [x: string]: V2ConfigReadResponse__ConfigLayerMetadata };\n};\nexport const V2ConfigReadResponse = Schema.Struct({\n  config: V2ConfigReadResponse__Config,\n  layers: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2ConfigReadResponse__ConfigLayer), Schema.Null]),\n  ),\n  origins: Schema.Record(Schema.String, V2ConfigReadResponse__ConfigLayerMetadata),\n}).annotate({ title: \"ConfigReadResponse\" });\n\nexport type V2ConfigReadResponse__AppConfig = {\n  readonly approvals_reviewer?: V2ConfigReadResponse__ApprovalsReviewer | null;\n  readonly default_tools_approval_mode?: V2ConfigReadResponse__AppToolApproval | null;\n  readonly default_tools_enabled?: boolean | null;\n  readonly destructive_enabled?: boolean | null;\n  readonly enabled?: boolean;\n  readonly open_world_enabled?: boolean | null;\n  readonly tools?: V2ConfigReadResponse__AppToolsConfig | null;\n};\nexport const V2ConfigReadResponse__AppConfig = Schema.Struct({\n  approvals_reviewer: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__ApprovalsReviewer, Schema.Null]),\n  ),\n  default_tools_approval_mode: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]),\n  ),\n  default_tools_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  destructive_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  enabled: Schema.optionalKey(Schema.Boolean.annotate({ default: true })),\n  open_world_enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  tools: Schema.optionalKey(Schema.Union([V2ConfigReadResponse__AppToolsConfig, Schema.Null])),\n});\n\nexport type V2ConfigReadResponse__AppsConfig = {\n  readonly _default?: V2ConfigReadResponse__AppsDefaultConfig | null;\n};\nexport const V2ConfigReadResponse__AppsConfig = Schema.Struct({\n  _default: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__AppsDefaultConfig, Schema.Null]),\n  ),\n});\n\nexport type V2ConfigReadResponse__AppToolConfig = {\n  readonly approval_mode?: V2ConfigReadResponse__AppToolApproval | null;\n  readonly enabled?: boolean | null;\n};\nexport const V2ConfigReadResponse__AppToolConfig = Schema.Struct({\n  approval_mode: Schema.optionalKey(\n    Schema.Union([V2ConfigReadResponse__AppToolApproval, Schema.Null]),\n  ),\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n});\n\nexport type V2ConfigRequirementsReadResponse = {\n  readonly requirements?: V2ConfigRequirementsReadResponse__ConfigRequirements | null;\n};\nexport const V2ConfigRequirementsReadResponse = Schema.Struct({\n  requirements: Schema.optionalKey(\n    Schema.Union([V2ConfigRequirementsReadResponse__ConfigRequirements, Schema.Null]).annotate({\n      description:\n        \"Null if no requirements are configured (e.g. no requirements.toml/MDM entries).\",\n    }),\n  ),\n}).annotate({ title: \"ConfigRequirementsReadResponse\" });\n\nexport type V2ConfigRequirementsReadResponse__ApprovalsReviewer =\n  | \"user\"\n  | \"auto_review\"\n  | \"guardian_subagent\";\nexport const V2ConfigRequirementsReadResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ConfigRequirementsReadResponse__ManagedHooksRequirements = {\n  readonly PermissionRequest: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly PostCompact: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly PostToolUse: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly PreCompact: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly PreToolUse: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly SessionEnd?: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly SessionStart: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly Stop: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly SubagentStart: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly SubagentStop: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly UserPromptSubmit: ReadonlyArray<V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup>;\n  readonly managedDir?: string | null;\n  readonly windowsManagedDir?: string | null;\n};\nexport const V2ConfigRequirementsReadResponse__ManagedHooksRequirements = Schema.Struct({\n  PermissionRequest: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  PostCompact: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  PostToolUse: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  PreCompact: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  PreToolUse: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  SessionEnd: Schema.optionalKey(\n    Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup).annotate({\n      default: [],\n    }),\n  ),\n  SessionStart: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  Stop: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  SubagentStart: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  SubagentStop: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  UserPromptSubmit: Schema.Array(V2ConfigRequirementsReadResponse__ConfiguredHookMatcherGroup),\n  managedDir: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  windowsManagedDir: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ConfigRequirementsReadResponse__NetworkRequirements = {\n  readonly allowLocalBinding?: boolean | null;\n  readonly allowUnixSockets?: ReadonlyArray<string> | null;\n  readonly allowUpstreamProxy?: boolean | null;\n  readonly allowedDomains?: ReadonlyArray<string> | null;\n  readonly dangerouslyAllowAllUnixSockets?: boolean | null;\n  readonly dangerouslyAllowNonLoopbackProxy?: boolean | null;\n  readonly deniedDomains?: ReadonlyArray<string> | null;\n  readonly domains?: {\n    readonly [x: string]: V2ConfigRequirementsReadResponse__NetworkDomainPermission;\n  } | null;\n  readonly enabled?: boolean | null;\n  readonly httpPort?: number | null;\n  readonly managedAllowedDomainsOnly?: boolean | null;\n  readonly socksPort?: number | null;\n  readonly unixSockets?: {\n    readonly [x: string]: V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission;\n  } | null;\n};\nexport const V2ConfigRequirementsReadResponse__NetworkRequirements = Schema.Struct({\n  allowLocalBinding: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowUnixSockets: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Legacy compatibility view derived from `unix_sockets`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  allowUpstreamProxy: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  allowedDomains: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Legacy compatibility view derived from `domains`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  dangerouslyAllowAllUnixSockets: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  dangerouslyAllowNonLoopbackProxy: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  deniedDomains: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Legacy compatibility view derived from `domains`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  domains: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(\n        Schema.String,\n        V2ConfigRequirementsReadResponse__NetworkDomainPermission,\n      ).annotate({ description: \"Canonical network permission map for `experimental_network`.\" }),\n      Schema.Null,\n    ]),\n  ),\n  enabled: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  httpPort: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint16\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  managedAllowedDomainsOnly: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"When true, only managed allowlist entries are respected while managed network enforcement is active.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  socksPort: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"uint16\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  unixSockets: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(\n        Schema.String,\n        V2ConfigRequirementsReadResponse__NetworkUnixSocketPermission,\n      ).annotate({\n        description: \"Canonical unix socket permission map for `experimental_network`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ConfigValueWriteParams = {\n  readonly expectedVersion?: string | null;\n  readonly filePath?: string | null;\n  readonly keyPath: string;\n  readonly mergeStrategy: V2ConfigValueWriteParams__MergeStrategy;\n  readonly value: unknown;\n};\nexport const V2ConfigValueWriteParams = Schema.Struct({\n  expectedVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  filePath: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Path to the config file to write; defaults to the user's `config.toml` when omitted.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  keyPath: Schema.String,\n  mergeStrategy: V2ConfigValueWriteParams__MergeStrategy,\n  value: Schema.Unknown,\n}).annotate({ title: \"ConfigValueWriteParams\" });\n\nexport type V2ConfigWarningNotification = {\n  readonly details?: string | null;\n  readonly path?: string | null;\n  readonly range?: V2ConfigWarningNotification__TextRange | null;\n  readonly summary: string;\n};\nexport const V2ConfigWarningNotification = Schema.Struct({\n  details: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional extra guidance or error details.\" }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional path to the config file that triggered the warning.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  range: Schema.optionalKey(\n    Schema.Union([V2ConfigWarningNotification__TextRange, Schema.Null]).annotate({\n      description: \"Optional range for the error location inside the config file.\",\n    }),\n  ),\n  summary: Schema.String.annotate({ description: \"Concise summary of the warning.\" }),\n}).annotate({ title: \"ConfigWarningNotification\" });\n\nexport type V2ConfigWriteResponse = {\n  readonly filePath: string;\n  readonly overriddenMetadata?: V2ConfigWriteResponse__OverriddenMetadata | null;\n  readonly status: V2ConfigWriteResponse__WriteStatus;\n  readonly version: string;\n};\nexport const V2ConfigWriteResponse = Schema.Struct({\n  filePath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  overriddenMetadata: Schema.optionalKey(\n    Schema.Union([V2ConfigWriteResponse__OverriddenMetadata, Schema.Null]),\n  ),\n  status: V2ConfigWriteResponse__WriteStatus,\n  version: Schema.String,\n}).annotate({ title: \"ConfigWriteResponse\" });\n\nexport type V2ConsumeAccountRateLimitResetCreditParams = {\n  readonly creditId?: string | null;\n  readonly idempotencyKey: string;\n};\nexport const V2ConsumeAccountRateLimitResetCreditParams = Schema.Struct({\n  creditId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque reset-credit identifier to redeem. When omitted, the backend selects the next available credit.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  idempotencyKey: Schema.String.annotate({\n    description:\n      \"Identifies one logical reset attempt. A UUID is recommended; reuse the same value when retrying that attempt.\",\n  }),\n}).annotate({ title: \"ConsumeAccountRateLimitResetCreditParams\" });\n\nexport type V2ConsumeAccountRateLimitResetCreditResponse = {\n  readonly outcome: V2ConsumeAccountRateLimitResetCreditResponse__ConsumeAccountRateLimitResetCreditOutcome;\n};\nexport const V2ConsumeAccountRateLimitResetCreditResponse = Schema.Struct({\n  outcome: V2ConsumeAccountRateLimitResetCreditResponse__ConsumeAccountRateLimitResetCreditOutcome,\n}).annotate({ title: \"ConsumeAccountRateLimitResetCreditResponse\" });\n\nexport type V2ContextCompactedNotification = { readonly threadId: string; readonly turnId: string };\nexport const V2ContextCompactedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"ContextCompactedNotification\",\n  description: \"Deprecated: Use `ContextCompaction` item type instead.\",\n});\n\nexport type V2DeprecationNoticeNotification = {\n  readonly details?: string | null;\n  readonly summary: string;\n};\nexport const V2DeprecationNoticeNotification = Schema.Struct({\n  details: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional extra guidance, such as migration steps or rationale.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  summary: Schema.String.annotate({ description: \"Concise summary of what is deprecated.\" }),\n}).annotate({ title: \"DeprecationNoticeNotification\" });\n\nexport type V2EnvironmentConnectionNotification = {\n  readonly environmentId: string;\n  readonly threadId: string;\n};\nexport const V2EnvironmentConnectionNotification = Schema.Struct({\n  environmentId: Schema.String,\n  threadId: Schema.String,\n}).annotate({ title: \"EnvironmentConnectionNotification\" });\n\nexport type V2ErrorNotification = {\n  readonly error: V2ErrorNotification__TurnError;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly willRetry: boolean;\n};\nexport const V2ErrorNotification = Schema.Struct({\n  error: V2ErrorNotification__TurnError,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  willRetry: Schema.Boolean,\n}).annotate({ title: \"ErrorNotification\" });\n\nexport type V2ExperimentalFeatureEnablementSetParams = {\n  readonly enablement: { readonly [x: string]: boolean };\n};\nexport const V2ExperimentalFeatureEnablementSetParams = Schema.Struct({\n  enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({\n    description:\n      \"Process-wide runtime feature enablement keyed by canonical feature name.\\n\\nOnly named features are updated. Omitted features are left unchanged. Send an empty map for a no-op.\",\n  }),\n}).annotate({ title: \"ExperimentalFeatureEnablementSetParams\" });\n\nexport type V2ExperimentalFeatureEnablementSetResponse = {\n  readonly enablement: { readonly [x: string]: boolean };\n};\nexport const V2ExperimentalFeatureEnablementSetResponse = Schema.Struct({\n  enablement: Schema.Record(Schema.String, Schema.Boolean).annotate({\n    description: \"Feature enablement entries updated by this request.\",\n  }),\n}).annotate({ title: \"ExperimentalFeatureEnablementSetResponse\" });\n\nexport type V2ExperimentalFeatureListParams = {\n  readonly cursor?: string | null;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const V2ExperimentalFeatureListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional loaded thread id. Pass this when showing feature state for an existing thread so enablement is computed from that thread's refreshed config, including project-local config for the thread's cwd.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ExperimentalFeatureListParams\" });\n\nexport type V2ExperimentalFeatureListResponse = {\n  readonly data: ReadonlyArray<V2ExperimentalFeatureListResponse__ExperimentalFeature>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ExperimentalFeatureListResponse = Schema.Struct({\n  data: Schema.Array(V2ExperimentalFeatureListResponse__ExperimentalFeature),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ExperimentalFeatureListResponse\" });\n\nexport type V2ExperimentalFeatureListResponse__ExperimentalFeatureStage =\n  | \"beta\"\n  | \"underDevelopment\"\n  | \"stable\"\n  | \"deprecated\"\n  | \"removed\";\nexport const V2ExperimentalFeatureListResponse__ExperimentalFeatureStage = Schema.Literals([\n  \"beta\",\n  \"underDevelopment\",\n  \"stable\",\n  \"deprecated\",\n  \"removed\",\n]);\n\nexport type V2ExternalAgentConfigDetectParams = {\n  readonly cwds?: ReadonlyArray<string> | null;\n  readonly includeHome?: boolean;\n  readonly migrationSource?: string | null;\n  readonly source?: string | null;\n};\nexport const V2ExternalAgentConfigDetectParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Zero or more working directories to include for repo-scoped detection.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeHome: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"If true, include detection under the user's home directory.\",\n    }),\n  ),\n  migrationSource: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional migration-source selector. Missing or unrecognized values use the default source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  source: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Deprecated field retained for compatibility. This field is ignored; use `migrationSource` to select the migration source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ExternalAgentConfigDetectParams\" });\n\nexport type V2ExternalAgentConfigDetectResponse = {\n  readonly items: ReadonlyArray<V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem>;\n};\nexport const V2ExternalAgentConfigDetectResponse = Schema.Struct({\n  items: Schema.Array(V2ExternalAgentConfigDetectResponse__ExternalAgentConfigMigrationItem),\n}).annotate({ title: \"ExternalAgentConfigDetectResponse\" });\n\nexport type V2ExternalAgentConfigImportCompletedNotification = {\n  readonly importId: string;\n  readonly itemTypeResults: ReadonlyArray<V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportTypeResult>;\n};\nexport const V2ExternalAgentConfigImportCompletedNotification = Schema.Struct({\n  importId: Schema.String,\n  itemTypeResults: Schema.Array(\n    V2ExternalAgentConfigImportCompletedNotification__ExternalAgentConfigImportTypeResult,\n  ),\n}).annotate({ title: \"ExternalAgentConfigImportCompletedNotification\" });\n\nexport type V2ExternalAgentConfigImportHistoriesReadResponse = {\n  readonly connectors: ReadonlyArray<V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorCandidate>;\n  readonly data: ReadonlyArray<V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportHistory>;\n};\nexport const V2ExternalAgentConfigImportHistoriesReadResponse = Schema.Struct({\n  connectors: Schema.Array(\n    V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentImportedConnectorCandidate,\n  ),\n  data: Schema.Array(\n    V2ExternalAgentConfigImportHistoriesReadResponse__ExternalAgentConfigImportHistory,\n  ),\n}).annotate({ title: \"ExternalAgentConfigImportHistoriesReadResponse\" });\n\nexport type V2ExternalAgentConfigImportParams = {\n  readonly migrationItems: ReadonlyArray<V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem>;\n  readonly migrationSource?: string | null;\n  readonly source?: string | null;\n};\nexport const V2ExternalAgentConfigImportParams = Schema.Struct({\n  migrationItems: Schema.Array(V2ExternalAgentConfigImportParams__ExternalAgentConfigMigrationItem),\n  migrationSource: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Migration-source selector used to produce the migration items. Pass the same value to detection and import; missing or unrecognized values use the default source.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  source: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional identifier for the product that initiated the import.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ExternalAgentConfigImportParams\" });\n\nexport type V2ExternalAgentConfigImportProgressNotification = {\n  readonly importId: string;\n  readonly itemTypeResults: ReadonlyArray<V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportTypeResult>;\n};\nexport const V2ExternalAgentConfigImportProgressNotification = Schema.Struct({\n  importId: Schema.String,\n  itemTypeResults: Schema.Array(\n    V2ExternalAgentConfigImportProgressNotification__ExternalAgentConfigImportTypeResult,\n  ),\n}).annotate({ title: \"ExternalAgentConfigImportProgressNotification\" });\n\nexport type V2ExternalAgentConfigImportResponse = { readonly importId: string };\nexport const V2ExternalAgentConfigImportResponse = Schema.Struct({\n  importId: Schema.String,\n}).annotate({ title: \"ExternalAgentConfigImportResponse\" });\n\nexport type V2FeedbackUploadParams = {\n  readonly classification: string;\n  readonly extraLogFiles?: ReadonlyArray<string> | null;\n  readonly includeLogs?: boolean;\n  readonly reason?: string | null;\n  readonly tags?: { readonly [x: string]: string } | null;\n  readonly threadId?: string | null;\n};\nexport const V2FeedbackUploadParams = Schema.Struct({\n  classification: Schema.String,\n  extraLogFiles: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  includeLogs: Schema.optionalKey(Schema.Boolean),\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  tags: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.String), Schema.Null]),\n  ),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"FeedbackUploadParams\" });\n\nexport type V2FeedbackUploadResponse = { readonly threadId: string };\nexport const V2FeedbackUploadResponse = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"FeedbackUploadResponse\",\n});\n\nexport type V2FileChangeOutputDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2FileChangeOutputDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"FileChangeOutputDeltaNotification\",\n  description:\n    \"Deprecated legacy notification for `apply_patch` textual output.\\n\\nThe server no longer emits this notification.\",\n});\n\nexport type V2FileChangePatchUpdatedNotification = {\n  readonly changes: ReadonlyArray<V2FileChangePatchUpdatedNotification__FileUpdateChange>;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2FileChangePatchUpdatedNotification = Schema.Struct({\n  changes: Schema.Array(V2FileChangePatchUpdatedNotification__FileUpdateChange),\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"FileChangePatchUpdatedNotification\" });\n\nexport type V2FsChangedNotification = {\n  readonly changedPaths: ReadonlyArray<V2FsChangedNotification__AbsolutePathBuf>;\n  readonly watchId: string;\n};\nexport const V2FsChangedNotification = Schema.Struct({\n  changedPaths: Schema.Array(V2FsChangedNotification__AbsolutePathBuf).annotate({\n    description: \"File or directory paths associated with this event.\",\n  }),\n  watchId: Schema.String.annotate({\n    description: \"Watch identifier previously provided to `fs/watch`.\",\n  }),\n}).annotate({\n  title: \"FsChangedNotification\",\n  description: \"Filesystem watch notification emitted for `fs/watch` subscribers.\",\n});\n\nexport type V2FsCopyParams = {\n  readonly destinationPath: string;\n  readonly recursive?: boolean;\n  readonly sourcePath: string;\n};\nexport const V2FsCopyParams = Schema.Struct({\n  destinationPath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Required for directory copies; ignored for file copies.\",\n    }),\n  ),\n  sourcePath: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({\n  title: \"FsCopyParams\",\n  description: \"Copy a file or directory tree on the host filesystem.\",\n});\n\nexport type V2FsCopyParams__AbsolutePathBuf = string;\nexport const V2FsCopyParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsCopyResponse = {};\nexport const V2FsCopyResponse = Schema.Struct({}).annotate({\n  title: \"FsCopyResponse\",\n  description: \"Successful response for `fs/copy`.\",\n});\n\nexport type V2FsCreateDirectoryParams = {\n  readonly path: string;\n  readonly recursive?: boolean | null;\n};\nexport const V2FsCreateDirectoryParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether parent directories should also be created. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  title: \"FsCreateDirectoryParams\",\n  description: \"Create a directory on the host filesystem.\",\n});\n\nexport type V2FsCreateDirectoryParams__AbsolutePathBuf = string;\nexport const V2FsCreateDirectoryParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsCreateDirectoryResponse = {};\nexport const V2FsCreateDirectoryResponse = Schema.Struct({}).annotate({\n  title: \"FsCreateDirectoryResponse\",\n  description: \"Successful response for `fs/createDirectory`.\",\n});\n\nexport type V2FsGetMetadataParams = { readonly path: string };\nexport const V2FsGetMetadataParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({\n  title: \"FsGetMetadataParams\",\n  description: \"Request metadata for an absolute path.\",\n});\n\nexport type V2FsGetMetadataParams__AbsolutePathBuf = string;\nexport const V2FsGetMetadataParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsGetMetadataResponse = {\n  readonly createdAtMs: number;\n  readonly isDirectory: boolean;\n  readonly isFile: boolean;\n  readonly isSymlink: boolean;\n  readonly modifiedAtMs: number;\n};\nexport const V2FsGetMetadataResponse = Schema.Struct({\n  createdAtMs: Schema.Number.annotate({\n    description: \"File creation time in Unix milliseconds when available, otherwise `0`.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  isDirectory: Schema.Boolean.annotate({\n    description: \"Whether the path resolves to a directory.\",\n  }),\n  isFile: Schema.Boolean.annotate({ description: \"Whether the path resolves to a regular file.\" }),\n  isSymlink: Schema.Boolean.annotate({\n    description: \"Whether the path itself is a symbolic link.\",\n  }),\n  modifiedAtMs: Schema.Number.annotate({\n    description: \"File modification time in Unix milliseconds when available, otherwise `0`.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n}).annotate({\n  title: \"FsGetMetadataResponse\",\n  description: \"Metadata returned by `fs/getMetadata`.\",\n});\n\nexport type V2FsReadDirectoryParams = { readonly path: string };\nexport const V2FsReadDirectoryParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({\n  title: \"FsReadDirectoryParams\",\n  description: \"List direct child names for a directory.\",\n});\n\nexport type V2FsReadDirectoryParams__AbsolutePathBuf = string;\nexport const V2FsReadDirectoryParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsReadDirectoryResponse = {\n  readonly entries: ReadonlyArray<V2FsReadDirectoryResponse__FsReadDirectoryEntry>;\n};\nexport const V2FsReadDirectoryResponse = Schema.Struct({\n  entries: Schema.Array(V2FsReadDirectoryResponse__FsReadDirectoryEntry).annotate({\n    description: \"Direct child entries in the requested directory.\",\n  }),\n}).annotate({\n  title: \"FsReadDirectoryResponse\",\n  description: \"Directory entries returned by `fs/readDirectory`.\",\n});\n\nexport type V2FsReadFileParams = { readonly path: string };\nexport const V2FsReadFileParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ title: \"FsReadFileParams\", description: \"Read a file from the host filesystem.\" });\n\nexport type V2FsReadFileParams__AbsolutePathBuf = string;\nexport const V2FsReadFileParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsReadFileResponse = { readonly dataBase64: string };\nexport const V2FsReadFileResponse = Schema.Struct({\n  dataBase64: Schema.String.annotate({ description: \"File contents encoded as base64.\" }),\n}).annotate({\n  title: \"FsReadFileResponse\",\n  description: \"Base64-encoded file contents returned by `fs/readFile`.\",\n});\n\nexport type V2FsRemoveParams = {\n  readonly force?: boolean | null;\n  readonly path: string;\n  readonly recursive?: boolean | null;\n};\nexport const V2FsRemoveParams = Schema.Struct({\n  force: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether missing paths should be ignored. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  recursive: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"Whether directory removal should recurse. Defaults to `true`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  title: \"FsRemoveParams\",\n  description: \"Remove a file or directory tree from the host filesystem.\",\n});\n\nexport type V2FsRemoveParams__AbsolutePathBuf = string;\nexport const V2FsRemoveParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsRemoveResponse = {};\nexport const V2FsRemoveResponse = Schema.Struct({}).annotate({\n  title: \"FsRemoveResponse\",\n  description: \"Successful response for `fs/remove`.\",\n});\n\nexport type V2FsUnwatchParams = { readonly watchId: string };\nexport const V2FsUnwatchParams = Schema.Struct({\n  watchId: Schema.String.annotate({\n    description: \"Watch identifier previously provided to `fs/watch`.\",\n  }),\n}).annotate({\n  title: \"FsUnwatchParams\",\n  description: \"Stop filesystem watch notifications for a prior `fs/watch`.\",\n});\n\nexport type V2FsUnwatchResponse = {};\nexport const V2FsUnwatchResponse = Schema.Struct({}).annotate({\n  title: \"FsUnwatchResponse\",\n  description: \"Successful response for `fs/unwatch`.\",\n});\n\nexport type V2FsWatchParams = { readonly path: string; readonly watchId: string };\nexport const V2FsWatchParams = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  watchId: Schema.String.annotate({\n    description: \"Connection-scoped watch identifier used for `fs/unwatch` and `fs/changed`.\",\n  }),\n}).annotate({\n  title: \"FsWatchParams\",\n  description: \"Start filesystem watch notifications for an absolute path.\",\n});\n\nexport type V2FsWatchParams__AbsolutePathBuf = string;\nexport const V2FsWatchParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsWatchResponse = { readonly path: string };\nexport const V2FsWatchResponse = Schema.Struct({\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ title: \"FsWatchResponse\", description: \"Successful response for `fs/watch`.\" });\n\nexport type V2FsWatchResponse__AbsolutePathBuf = string;\nexport const V2FsWatchResponse__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsWriteFileParams = { readonly dataBase64: string; readonly path: string };\nexport const V2FsWriteFileParams = Schema.Struct({\n  dataBase64: Schema.String.annotate({ description: \"File contents encoded as base64.\" }),\n  path: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n}).annotate({ title: \"FsWriteFileParams\", description: \"Write a file on the host filesystem.\" });\n\nexport type V2FsWriteFileParams__AbsolutePathBuf = string;\nexport const V2FsWriteFileParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2FsWriteFileResponse = {};\nexport const V2FsWriteFileResponse = Schema.Struct({}).annotate({\n  title: \"FsWriteFileResponse\",\n  description: \"Successful response for `fs/writeFile`.\",\n});\n\nexport type V2GetAccountParams = { readonly refreshToken?: boolean };\nexport const V2GetAccountParams = Schema.Struct({\n  refreshToken: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"When `true`, requests a proactive token refresh before returning.\\n\\nIn managed auth mode this triggers the normal refresh-token flow. In external auth mode this flag is ignored. Clients should refresh tokens themselves and call `account/login/start` with `chatgptAuthTokens`.\",\n    }),\n  ),\n}).annotate({ title: \"GetAccountParams\" });\n\nexport type V2GetAccountRateLimitsResponse = {\n  readonly rateLimitResetCredits?: V2GetAccountRateLimitsResponse__RateLimitResetCreditsSummary | null;\n  readonly rateLimits: {\n    readonly credits?: V2GetAccountRateLimitsResponse__CreditsSnapshot | null;\n    readonly individualLimit?: V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot | null;\n    readonly limitId?: string | null;\n    readonly limitName?: string | null;\n    readonly planType?: V2GetAccountRateLimitsResponse__PlanType | null;\n    readonly primary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;\n    readonly rateLimitReachedType?: V2GetAccountRateLimitsResponse__RateLimitReachedType | null;\n    readonly secondary?: V2GetAccountRateLimitsResponse__RateLimitWindow | null;\n    readonly spendControlReached?: boolean | null;\n  };\n  readonly rateLimitsByLimitId?: {\n    readonly [x: string]: V2GetAccountRateLimitsResponse__RateLimitSnapshot;\n  } | null;\n};\nexport const V2GetAccountRateLimitsResponse = Schema.Struct({\n  rateLimitResetCredits: Schema.optionalKey(\n    Schema.Union([V2GetAccountRateLimitsResponse__RateLimitResetCreditsSummary, Schema.Null]),\n  ),\n  rateLimits: Schema.Struct({\n    credits: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__CreditsSnapshot, Schema.Null]),\n    ),\n    individualLimit: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__SpendControlLimitSnapshot, Schema.Null]),\n    ),\n    limitId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    limitName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    planType: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__PlanType, Schema.Null]),\n    ),\n    primary: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),\n    ),\n    rateLimitReachedType: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__RateLimitReachedType, Schema.Null]),\n    ),\n    secondary: Schema.optionalKey(\n      Schema.Union([V2GetAccountRateLimitsResponse__RateLimitWindow, Schema.Null]),\n    ),\n    spendControlReached: Schema.optionalKey(\n      Schema.Union([\n        Schema.Boolean.annotate({\n          description:\n            \"Backend-reported spend-control state. `None` is unavailable, not a sparse-update recovery.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n  }).annotate({\n    description: \"Backward-compatible single-bucket view; mirrors the historical payload.\",\n  }),\n  rateLimitsByLimitId: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, V2GetAccountRateLimitsResponse__RateLimitSnapshot).annotate({\n        description: \"Multi-bucket view keyed by metered `limit_id` (for example, `codex`).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"GetAccountRateLimitsResponse\" });\n\nexport type V2GetAccountResponse = {\n  readonly account?: V2GetAccountResponse__Account | null;\n  readonly requiresOpenaiAuth: boolean;\n};\nexport const V2GetAccountResponse = Schema.Struct({\n  account: Schema.optionalKey(Schema.Union([V2GetAccountResponse__Account, Schema.Null])),\n  requiresOpenaiAuth: Schema.Boolean,\n}).annotate({ title: \"GetAccountResponse\" });\n\nexport type V2GetAccountTokenUsageResponse = {\n  readonly dailyUsageBuckets?: ReadonlyArray<V2GetAccountTokenUsageResponse__AccountTokenUsageDailyBucket> | null;\n  readonly summary: V2GetAccountTokenUsageResponse__AccountTokenUsageSummary;\n};\nexport const V2GetAccountTokenUsageResponse = Schema.Struct({\n  dailyUsageBuckets: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2GetAccountTokenUsageResponse__AccountTokenUsageDailyBucket),\n      Schema.Null,\n    ]),\n  ),\n  summary: V2GetAccountTokenUsageResponse__AccountTokenUsageSummary,\n}).annotate({ title: \"GetAccountTokenUsageResponse\" });\n\nexport type V2GetWorkspaceMessagesResponse = {\n  readonly featureEnabled: boolean;\n  readonly messages: ReadonlyArray<V2GetWorkspaceMessagesResponse__WorkspaceMessage>;\n};\nexport const V2GetWorkspaceMessagesResponse = Schema.Struct({\n  featureEnabled: Schema.Boolean.annotate({\n    description: \"Whether the workspace-message backend route is available for this client.\",\n  }),\n  messages: Schema.Array(V2GetWorkspaceMessagesResponse__WorkspaceMessage).annotate({\n    description: \"Active workspace messages returned by the backend.\",\n  }),\n}).annotate({ title: \"GetWorkspaceMessagesResponse\" });\n\nexport type V2GuardianWarningNotification = { readonly message: string; readonly threadId: string };\nexport const V2GuardianWarningNotification = Schema.Struct({\n  message: Schema.String.annotate({\n    description: \"Concise guardian warning message for the user.\",\n  }),\n  threadId: Schema.String.annotate({ description: \"Thread target for the guardian warning.\" }),\n}).annotate({ title: \"GuardianWarningNotification\" });\n\nexport type V2HookCompletedNotification = {\n  readonly run: V2HookCompletedNotification__HookRunSummary;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const V2HookCompletedNotification = Schema.Struct({\n  run: V2HookCompletedNotification__HookRunSummary,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"HookCompletedNotification\" });\n\nexport type V2HookCompletedNotification__HookSource =\n  | \"system\"\n  | \"user\"\n  | \"project\"\n  | \"mdm\"\n  | \"sessionFlags\"\n  | \"plugin\"\n  | \"cloudRequirements\"\n  | \"cloudManagedConfig\"\n  | \"legacyManagedConfigFile\"\n  | \"legacyManagedConfigMdm\"\n  | \"unknown\";\nexport const V2HookCompletedNotification__HookSource = Schema.Literals([\n  \"system\",\n  \"user\",\n  \"project\",\n  \"mdm\",\n  \"sessionFlags\",\n  \"plugin\",\n  \"cloudRequirements\",\n  \"cloudManagedConfig\",\n  \"legacyManagedConfigFile\",\n  \"legacyManagedConfigMdm\",\n  \"unknown\",\n]);\n\nexport type V2HooksListParams = { readonly cwds?: ReadonlyArray<string> };\nexport const V2HooksListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"When empty, defaults to the current session working directory.\",\n    }),\n  ),\n}).annotate({ title: \"HooksListParams\" });\n\nexport type V2HooksListResponse = {\n  readonly data: ReadonlyArray<V2HooksListResponse__HooksListEntry>;\n};\nexport const V2HooksListResponse = Schema.Struct({\n  data: Schema.Array(V2HooksListResponse__HooksListEntry),\n}).annotate({ title: \"HooksListResponse\" });\n\nexport type V2HookStartedNotification = {\n  readonly run: V2HookStartedNotification__HookRunSummary;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const V2HookStartedNotification = Schema.Struct({\n  run: V2HookStartedNotification__HookRunSummary,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"HookStartedNotification\" });\n\nexport type V2HookStartedNotification__HookSource =\n  | \"system\"\n  | \"user\"\n  | \"project\"\n  | \"mdm\"\n  | \"sessionFlags\"\n  | \"plugin\"\n  | \"cloudRequirements\"\n  | \"cloudManagedConfig\"\n  | \"legacyManagedConfigFile\"\n  | \"legacyManagedConfigMdm\"\n  | \"unknown\";\nexport const V2HookStartedNotification__HookSource = Schema.Literals([\n  \"system\",\n  \"user\",\n  \"project\",\n  \"mdm\",\n  \"sessionFlags\",\n  \"plugin\",\n  \"cloudRequirements\",\n  \"cloudManagedConfig\",\n  \"legacyManagedConfigFile\",\n  \"legacyManagedConfigMdm\",\n  \"unknown\",\n]);\n\nexport type V2ItemCompletedNotification = {\n  readonly completedAtMs: number;\n  readonly item: V2ItemCompletedNotification__ThreadItem;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ItemCompletedNotification = Schema.Struct({\n  completedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this item lifecycle completed.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  item: V2ItemCompletedNotification__ThreadItem,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ItemCompletedNotification\" });\n\nexport type V2ItemCompletedNotification__ByteRange = {\n  readonly end: number;\n  readonly start: number;\n};\nexport const V2ItemCompletedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ItemCompletedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ItemCompletedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ItemCompletedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ItemCompletedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemCompletedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ItemCompletedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ItemGuardianApprovalReviewCompletedNotification = {\n  readonly action: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction;\n  readonly completedAtMs: number;\n  readonly decisionSource: V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource;\n  readonly review: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview;\n  readonly reviewId: string;\n  readonly startedAtMs: number;\n  readonly targetItemId?: string | null;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ItemGuardianApprovalReviewCompletedNotification = Schema.Struct({\n  action: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReviewAction,\n  completedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review completed.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  decisionSource: V2ItemGuardianApprovalReviewCompletedNotification__AutoReviewDecisionSource,\n  review: V2ItemGuardianApprovalReviewCompletedNotification__GuardianApprovalReview,\n  reviewId: Schema.String.annotate({ description: \"Stable identifier for this review.\" }),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  targetItemId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Identifier for the reviewed item or tool call when one exists.\\n\\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\\n\\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"ItemGuardianApprovalReviewCompletedNotification\",\n  description:\n    \"[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.\",\n});\n\nexport type V2ItemGuardianApprovalReviewStartedNotification = {\n  readonly action: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction;\n  readonly review: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview;\n  readonly reviewId: string;\n  readonly startedAtMs: number;\n  readonly targetItemId?: string | null;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ItemGuardianApprovalReviewStartedNotification = Schema.Struct({\n  action: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReviewAction,\n  review: V2ItemGuardianApprovalReviewStartedNotification__GuardianApprovalReview,\n  reviewId: Schema.String.annotate({ description: \"Stable identifier for this review.\" }),\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this review started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  targetItemId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Identifier for the reviewed item or tool call when one exists.\\n\\nIn most cases, one review maps to one target item. The exceptions are - execve reviews, where a single command may contain multiple execve calls to review (only possible when using the shell_zsh_fork feature) - network policy reviews, where there is no target item\\n\\nA network call is triggered by a CommandExecution item, so having a target_item_id set to the CommandExecution item would be misleading because the review is about the network call, not the command execution. Therefore, target_item_id is set to None for network policy reviews.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"ItemGuardianApprovalReviewStartedNotification\",\n  description:\n    \"[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.\",\n});\n\nexport type V2ItemStartedNotification = {\n  readonly item: V2ItemStartedNotification__ThreadItem;\n  readonly startedAtMs: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ItemStartedNotification = Schema.Struct({\n  item: V2ItemStartedNotification__ThreadItem,\n  startedAtMs: Schema.Number.annotate({\n    description: \"Unix timestamp (in milliseconds) when this item lifecycle started.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ItemStartedNotification\" });\n\nexport type V2ItemStartedNotification__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ItemStartedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ItemStartedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ItemStartedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ItemStartedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ItemStartedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ItemStartedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ItemStartedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ListMcpServerStatusParams = {\n  readonly cursor?: string | null;\n  readonly detail?: V2ListMcpServerStatusParams__McpServerStatusDetail | null;\n  readonly limit?: number | null;\n  readonly threadId?: string | null;\n};\nexport const V2ListMcpServerStatusParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  detail: Schema.optionalKey(\n    Schema.Union([V2ListMcpServerStatusParams__McpServerStatusDetail, Schema.Null]).annotate({\n      description:\n        \"Controls how much MCP inventory data to fetch for each server. Defaults to `Full` when omitted.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a server-defined value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ListMcpServerStatusParams\" });\n\nexport type V2ListMcpServerStatusResponse = {\n  readonly data: ReadonlyArray<V2ListMcpServerStatusResponse__McpServerStatus>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ListMcpServerStatusResponse = Schema.Struct({\n  data: Schema.Array(V2ListMcpServerStatusResponse__McpServerStatus),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ListMcpServerStatusResponse\" });\n\nexport type V2LoginAccountParams =\n  | { readonly apiKey: string; readonly type: \"apiKey\" }\n  | {\n      readonly appBrand?: V2LoginAccountParams__LoginAppBrand | null;\n      readonly codexStreamlinedLogin?: boolean;\n      readonly type: \"chatgpt\";\n      readonly useHostedLoginSuccessPage?: boolean;\n    }\n  | { readonly type: \"chatgptDeviceCode\" }\n  | {\n      readonly accessToken: string;\n      readonly chatgptAccountId: string;\n      readonly chatgptPlanType?: string | null;\n      readonly type: \"chatgptAuthTokens\";\n    }\n  | { readonly apiKey: string; readonly region: string; readonly type: \"amazonBedrock\" };\nexport const V2LoginAccountParams = Schema.Union(\n  [\n    Schema.Struct({\n      apiKey: Schema.String,\n      type: Schema.Literal(\"apiKey\").annotate({ title: \"ApiKeyv2::LoginAccountParamsType\" }),\n    }).annotate({ title: \"ApiKeyv2::LoginAccountParams\" }),\n    Schema.Struct({\n      appBrand: Schema.optionalKey(\n        Schema.Union([V2LoginAccountParams__LoginAppBrand, Schema.Null]),\n      ),\n      codexStreamlinedLogin: Schema.optionalKey(Schema.Boolean),\n      type: Schema.Literal(\"chatgpt\").annotate({ title: \"Chatgptv2::LoginAccountParamsType\" }),\n      useHostedLoginSuccessPage: Schema.optionalKey(Schema.Boolean),\n    }).annotate({ title: \"Chatgptv2::LoginAccountParams\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"chatgptDeviceCode\").annotate({\n        title: \"ChatgptDeviceCodev2::LoginAccountParamsType\",\n      }),\n    }).annotate({ title: \"ChatgptDeviceCodev2::LoginAccountParams\" }),\n    Schema.Struct({\n      accessToken: Schema.String.annotate({\n        description:\n          \"Access token (JWT) supplied by the client. This token is used for backend API requests and email extraction.\",\n      }),\n      chatgptAccountId: Schema.String.annotate({\n        description: \"Workspace/account identifier supplied by the client.\",\n      }),\n      chatgptPlanType: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"Optional plan type supplied by the client.\\n\\nWhen `null`, Codex attempts to derive the plan type from access-token claims. If unavailable, the plan defaults to `unknown`.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.Literal(\"chatgptAuthTokens\").annotate({\n        title: \"ChatgptAuthTokensv2::LoginAccountParamsType\",\n      }),\n    }).annotate({\n      title: \"ChatgptAuthTokensv2::LoginAccountParams\",\n      description:\n        \"[UNSTABLE] FOR OPENAI INTERNAL USE ONLY - DO NOT USE. The access token must contain the same scopes that Codex-managed ChatGPT auth tokens have.\",\n    }),\n    Schema.Struct({\n      apiKey: Schema.String,\n      region: Schema.String,\n      type: Schema.Literal(\"amazonBedrock\").annotate({\n        title: \"AmazonBedrockv2::LoginAccountParamsType\",\n      }),\n    }).annotate({\n      title: \"AmazonBedrockv2::LoginAccountParams\",\n      description: \"[UNSTABLE] Managed Amazon Bedrock login is experimental.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ title: \"LoginAccountParams\" });\n\nexport type V2LoginAccountResponse =\n  | { readonly type: \"apiKey\" }\n  | { readonly authUrl: string; readonly loginId: string; readonly type: \"chatgpt\" }\n  | {\n      readonly loginId: string;\n      readonly type: \"chatgptDeviceCode\";\n      readonly userCode: string;\n      readonly verificationUrl: string;\n    }\n  | { readonly type: \"chatgptAuthTokens\" }\n  | { readonly type: \"amazonBedrock\" };\nexport const V2LoginAccountResponse = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"apiKey\").annotate({ title: \"ApiKeyv2::LoginAccountResponseType\" }),\n    }).annotate({ title: \"ApiKeyv2::LoginAccountResponse\" }),\n    Schema.Struct({\n      authUrl: Schema.String.annotate({\n        description: \"URL the client should open in a browser to initiate the OAuth flow.\",\n      }),\n      loginId: Schema.String,\n      type: Schema.Literal(\"chatgpt\").annotate({ title: \"Chatgptv2::LoginAccountResponseType\" }),\n    }).annotate({ title: \"Chatgptv2::LoginAccountResponse\" }),\n    Schema.Struct({\n      loginId: Schema.String,\n      type: Schema.Literal(\"chatgptDeviceCode\").annotate({\n        title: \"ChatgptDeviceCodev2::LoginAccountResponseType\",\n      }),\n      userCode: Schema.String.annotate({\n        description: \"One-time code the user must enter after signing in.\",\n      }),\n      verificationUrl: Schema.String.annotate({\n        description:\n          \"URL the client should open in a browser to complete device code authorization.\",\n      }),\n    }).annotate({ title: \"ChatgptDeviceCodev2::LoginAccountResponse\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"chatgptAuthTokens\").annotate({\n        title: \"ChatgptAuthTokensv2::LoginAccountResponseType\",\n      }),\n    }).annotate({ title: \"ChatgptAuthTokensv2::LoginAccountResponse\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"amazonBedrock\").annotate({\n        title: \"AmazonBedrockv2::LoginAccountResponseType\",\n      }),\n    }).annotate({ title: \"AmazonBedrockv2::LoginAccountResponse\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ title: \"LoginAccountResponse\" });\n\nexport type V2LogoutAccountResponse = {};\nexport const V2LogoutAccountResponse = Schema.Struct({}).annotate({\n  title: \"LogoutAccountResponse\",\n});\n\nexport type V2MarketplaceAddParams = {\n  readonly refName?: string | null;\n  readonly source: string;\n  readonly sparsePaths?: ReadonlyArray<string> | null;\n};\nexport const V2MarketplaceAddParams = Schema.Struct({\n  refName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  source: Schema.String,\n  sparsePaths: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n}).annotate({ title: \"MarketplaceAddParams\" });\n\nexport type V2MarketplaceAddResponse = {\n  readonly alreadyAdded: boolean;\n  readonly installedRoot: V2MarketplaceAddResponse__AbsolutePathBuf;\n  readonly marketplaceName: string;\n};\nexport const V2MarketplaceAddResponse = Schema.Struct({\n  alreadyAdded: Schema.Boolean,\n  installedRoot: V2MarketplaceAddResponse__AbsolutePathBuf,\n  marketplaceName: Schema.String,\n}).annotate({ title: \"MarketplaceAddResponse\" });\n\nexport type V2MarketplaceRemoveParams = { readonly marketplaceName: string };\nexport const V2MarketplaceRemoveParams = Schema.Struct({ marketplaceName: Schema.String }).annotate(\n  { title: \"MarketplaceRemoveParams\" },\n);\n\nexport type V2MarketplaceRemoveResponse = {\n  readonly installedRoot?: V2MarketplaceRemoveResponse__AbsolutePathBuf | null;\n  readonly marketplaceName: string;\n};\nexport const V2MarketplaceRemoveResponse = Schema.Struct({\n  installedRoot: Schema.optionalKey(\n    Schema.Union([V2MarketplaceRemoveResponse__AbsolutePathBuf, Schema.Null]),\n  ),\n  marketplaceName: Schema.String,\n}).annotate({ title: \"MarketplaceRemoveResponse\" });\n\nexport type V2MarketplaceUpgradeParams = { readonly marketplaceName?: string | null };\nexport const V2MarketplaceUpgradeParams = Schema.Struct({\n  marketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"MarketplaceUpgradeParams\" });\n\nexport type V2MarketplaceUpgradeResponse = {\n  readonly errors: ReadonlyArray<V2MarketplaceUpgradeResponse__MarketplaceUpgradeErrorInfo>;\n  readonly selectedMarketplaces: ReadonlyArray<string>;\n  readonly upgradedRoots: ReadonlyArray<V2MarketplaceUpgradeResponse__AbsolutePathBuf>;\n};\nexport const V2MarketplaceUpgradeResponse = Schema.Struct({\n  errors: Schema.Array(V2MarketplaceUpgradeResponse__MarketplaceUpgradeErrorInfo),\n  selectedMarketplaces: Schema.Array(Schema.String),\n  upgradedRoots: Schema.Array(V2MarketplaceUpgradeResponse__AbsolutePathBuf),\n}).annotate({ title: \"MarketplaceUpgradeResponse\" });\n\nexport type V2McpResourceReadParams = {\n  readonly server: string;\n  readonly threadId?: string | null;\n  readonly uri: string;\n};\nexport const V2McpResourceReadParams = Schema.Struct({\n  server: Schema.String,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n}).annotate({ title: \"McpResourceReadParams\" });\n\nexport type V2McpResourceReadResponse = {\n  readonly contents: ReadonlyArray<V2McpResourceReadResponse__ResourceContent>;\n};\nexport const V2McpResourceReadResponse = Schema.Struct({\n  contents: Schema.Array(V2McpResourceReadResponse__ResourceContent),\n}).annotate({ title: \"McpResourceReadResponse\" });\n\nexport type V2McpServerOauthLoginCompletedNotification = {\n  readonly error?: string | null;\n  readonly name: string;\n  readonly success: boolean;\n  readonly threadId?: string | null;\n};\nexport const V2McpServerOauthLoginCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  success: Schema.Boolean,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"McpServerOauthLoginCompletedNotification\" });\n\nexport type V2McpServerOauthLoginParams = {\n  readonly name: string;\n  readonly scopes?: ReadonlyArray<string> | null;\n  readonly threadId?: string | null;\n  readonly timeoutSecs?: number | null;\n};\nexport const V2McpServerOauthLoginParams = Schema.Struct({\n  name: Schema.String,\n  scopes: Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null])),\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  timeoutSecs: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n}).annotate({ title: \"McpServerOauthLoginParams\" });\n\nexport type V2McpServerOauthLoginResponse = { readonly authorizationUrl: string };\nexport const V2McpServerOauthLoginResponse = Schema.Struct({\n  authorizationUrl: Schema.String,\n}).annotate({ title: \"McpServerOauthLoginResponse\" });\n\nexport type V2McpServerRefreshResponse = {};\nexport const V2McpServerRefreshResponse = Schema.Struct({}).annotate({\n  title: \"McpServerRefreshResponse\",\n});\n\nexport type V2McpServerStatusUpdatedNotification = {\n  readonly error?: string | null;\n  readonly failureReason?: V2McpServerStatusUpdatedNotification__McpServerStartupFailureReason | null;\n  readonly name: string;\n  readonly status: V2McpServerStatusUpdatedNotification__McpServerStartupState;\n  readonly threadId?: string | null;\n};\nexport const V2McpServerStatusUpdatedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  failureReason: Schema.optionalKey(\n    Schema.Union([\n      V2McpServerStatusUpdatedNotification__McpServerStartupFailureReason,\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String,\n  status: V2McpServerStatusUpdatedNotification__McpServerStartupState,\n  threadId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"McpServerStatusUpdatedNotification\" });\n\nexport type V2McpServerToolCallParams = {\n  readonly _meta?: unknown;\n  readonly arguments?: unknown;\n  readonly server: string;\n  readonly threadId: string;\n  readonly tool: string;\n};\nexport const V2McpServerToolCallParams = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  arguments: Schema.optionalKey(Schema.Unknown),\n  server: Schema.String,\n  threadId: Schema.String,\n  tool: Schema.String,\n}).annotate({ title: \"McpServerToolCallParams\" });\n\nexport type V2McpServerToolCallResponse = {\n  readonly _meta?: unknown;\n  readonly content: ReadonlyArray<unknown>;\n  readonly isError?: boolean | null;\n  readonly structuredContent?: unknown;\n};\nexport const V2McpServerToolCallResponse = Schema.Struct({\n  _meta: Schema.optionalKey(Schema.Unknown),\n  content: Schema.Array(Schema.Unknown),\n  isError: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  structuredContent: Schema.optionalKey(Schema.Unknown),\n}).annotate({ title: \"McpServerToolCallResponse\" });\n\nexport type V2McpToolCallProgressNotification = {\n  readonly itemId: string;\n  readonly message: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2McpToolCallProgressNotification = Schema.Struct({\n  itemId: Schema.String,\n  message: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"McpToolCallProgressNotification\" });\n\nexport type V2ModelListParams = {\n  readonly cursor?: string | null;\n  readonly includeHidden?: boolean | null;\n  readonly limit?: number | null;\n};\nexport const V2ModelListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  includeHidden: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description: \"When true, include models that are hidden from the default picker list.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ModelListParams\" });\n\nexport type V2ModelListResponse = {\n  readonly data: ReadonlyArray<V2ModelListResponse__Model>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ModelListResponse = Schema.Struct({\n  data: Schema.Array(V2ModelListResponse__Model),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ModelListResponse\" });\n\nexport type V2ModelProviderCapabilitiesReadParams = {};\nexport const V2ModelProviderCapabilitiesReadParams = Schema.Struct({}).annotate({\n  title: \"ModelProviderCapabilitiesReadParams\",\n});\n\nexport type V2ModelProviderCapabilitiesReadResponse = {\n  readonly imageGeneration: boolean;\n  readonly namespaceTools: boolean;\n  readonly webSearch: boolean;\n};\nexport const V2ModelProviderCapabilitiesReadResponse = Schema.Struct({\n  imageGeneration: Schema.Boolean,\n  namespaceTools: Schema.Boolean,\n  webSearch: Schema.Boolean,\n}).annotate({ title: \"ModelProviderCapabilitiesReadResponse\" });\n\nexport type V2ModelReroutedNotification = {\n  readonly fromModel: string;\n  readonly reason: V2ModelReroutedNotification__ModelRerouteReason;\n  readonly threadId: string;\n  readonly toModel: string;\n  readonly turnId: string;\n};\nexport const V2ModelReroutedNotification = Schema.Struct({\n  fromModel: Schema.String,\n  reason: V2ModelReroutedNotification__ModelRerouteReason,\n  threadId: Schema.String,\n  toModel: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ModelReroutedNotification\" });\n\nexport type V2ModelSafetyBufferingUpdatedNotification = {\n  readonly fasterModel?: string | null;\n  readonly model: string;\n  readonly reasons: ReadonlyArray<string>;\n  readonly showBufferingUi: boolean;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly useCases: ReadonlyArray<string>;\n};\nexport const V2ModelSafetyBufferingUpdatedNotification = Schema.Struct({\n  fasterModel: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.String,\n  reasons: Schema.Array(Schema.String),\n  showBufferingUi: Schema.Boolean,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  useCases: Schema.Array(Schema.String),\n}).annotate({ title: \"ModelSafetyBufferingUpdatedNotification\" });\n\nexport type V2ModelVerificationNotification = {\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly verifications: ReadonlyArray<V2ModelVerificationNotification__ModelVerification>;\n};\nexport const V2ModelVerificationNotification = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n  verifications: Schema.Array(V2ModelVerificationNotification__ModelVerification),\n}).annotate({ title: \"ModelVerificationNotification\" });\n\nexport type V2PermissionProfileListParams = {\n  readonly cursor?: string | null;\n  readonly cwd?: string | null;\n  readonly limit?: number | null;\n};\nexport const V2PermissionProfileListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional working directory to resolve project config layers.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to the full result set.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PermissionProfileListParams\" });\n\nexport type V2PermissionProfileListResponse = {\n  readonly data: ReadonlyArray<V2PermissionProfileListResponse__PermissionProfileSummary>;\n  readonly nextCursor?: string | null;\n};\nexport const V2PermissionProfileListResponse = Schema.Struct({\n  data: Schema.Array(V2PermissionProfileListResponse__PermissionProfileSummary),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. If None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PermissionProfileListResponse\" });\n\nexport type V2PlanDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2PlanDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"PlanDeltaNotification\",\n  description:\n    \"EXPERIMENTAL - proposed plan streaming deltas for plan items. Clients should not assume concatenated deltas match the completed plan item content.\",\n});\n\nexport type V2PluginInstalledParams = {\n  readonly cwds?: ReadonlyArray<V2PluginInstalledParams__AbsolutePathBuf> | null;\n  readonly installSuggestionPluginNames?: ReadonlyArray<string> | null;\n};\nexport const V2PluginInstalledParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2PluginInstalledParams__AbsolutePathBuf).annotate({\n        description: \"Optional working directories used to discover repo marketplaces.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  installSuggestionPluginNames: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Additional uninstalled plugin names that should be returned when present locally. This is used by mention surfaces that intentionally expose install entrypoints.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PluginInstalledParams\" });\n\nexport type V2PluginInstalledResponse = {\n  readonly marketplaceLoadErrors?: ReadonlyArray<V2PluginInstalledResponse__MarketplaceLoadErrorInfo>;\n  readonly marketplaces: ReadonlyArray<V2PluginInstalledResponse__PluginMarketplaceEntry>;\n};\nexport const V2PluginInstalledResponse = Schema.Struct({\n  marketplaceLoadErrors: Schema.optionalKey(\n    Schema.Array(V2PluginInstalledResponse__MarketplaceLoadErrorInfo).annotate({ default: [] }),\n  ),\n  marketplaces: Schema.Array(V2PluginInstalledResponse__PluginMarketplaceEntry),\n}).annotate({ title: \"PluginInstalledResponse\" });\n\nexport type V2PluginInstalledResponse__PluginAvailability = \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\nexport const V2PluginInstalledResponse__PluginAvailability = Schema.Literals([\n  \"DISABLED_BY_ADMIN\",\n  \"AVAILABLE\",\n]);\n\nexport type V2PluginInstallParams = {\n  readonly marketplacePath?: V2PluginInstallParams__AbsolutePathBuf | null;\n  readonly pluginName: string;\n  readonly remoteMarketplaceName?: string | null;\n};\nexport const V2PluginInstallParams = Schema.Struct({\n  marketplacePath: Schema.optionalKey(\n    Schema.Union([V2PluginInstallParams__AbsolutePathBuf, Schema.Null]),\n  ),\n  pluginName: Schema.String,\n  remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"PluginInstallParams\" });\n\nexport type V2PluginInstallResponse = {\n  readonly appsNeedingAuth: ReadonlyArray<V2PluginInstallResponse__AppSummary>;\n  readonly authPolicy: V2PluginInstallResponse__PluginAuthPolicy;\n};\nexport const V2PluginInstallResponse = Schema.Struct({\n  appsNeedingAuth: Schema.Array(V2PluginInstallResponse__AppSummary),\n  authPolicy: V2PluginInstallResponse__PluginAuthPolicy,\n}).annotate({ title: \"PluginInstallResponse\" });\n\nexport type V2PluginListParams = {\n  readonly cwds?: ReadonlyArray<V2PluginListParams__AbsolutePathBuf> | null;\n  readonly marketplaceKinds?: ReadonlyArray<V2PluginListParams__PluginListMarketplaceKind> | null;\n};\nexport const V2PluginListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2PluginListParams__AbsolutePathBuf).annotate({\n        description:\n          \"Optional working directories used to discover repo marketplaces. When omitted, only home-scoped marketplaces and the official curated marketplace are considered.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  marketplaceKinds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2PluginListParams__PluginListMarketplaceKind).annotate({\n        description:\n          \"Optional marketplace kind filter. When omitted, only local marketplaces are queried, plus the default remote catalog when enabled by feature flag.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"PluginListParams\" });\n\nexport type V2PluginListResponse = {\n  readonly featuredPluginIds?: ReadonlyArray<string>;\n  readonly marketplaceLoadErrors?: ReadonlyArray<V2PluginListResponse__MarketplaceLoadErrorInfo>;\n  readonly marketplaces: ReadonlyArray<V2PluginListResponse__PluginMarketplaceEntry>;\n};\nexport const V2PluginListResponse = Schema.Struct({\n  featuredPluginIds: Schema.optionalKey(Schema.Array(Schema.String).annotate({ default: [] })),\n  marketplaceLoadErrors: Schema.optionalKey(\n    Schema.Array(V2PluginListResponse__MarketplaceLoadErrorInfo).annotate({ default: [] }),\n  ),\n  marketplaces: Schema.Array(V2PluginListResponse__PluginMarketplaceEntry),\n}).annotate({ title: \"PluginListResponse\" });\n\nexport type V2PluginListResponse__PluginAvailability = \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\nexport const V2PluginListResponse__PluginAvailability = Schema.Literals([\n  \"DISABLED_BY_ADMIN\",\n  \"AVAILABLE\",\n]);\n\nexport type V2PluginReadParams = {\n  readonly marketplacePath?: V2PluginReadParams__AbsolutePathBuf | null;\n  readonly pluginName: string;\n  readonly remoteMarketplaceName?: string | null;\n};\nexport const V2PluginReadParams = Schema.Struct({\n  marketplacePath: Schema.optionalKey(\n    Schema.Union([V2PluginReadParams__AbsolutePathBuf, Schema.Null]),\n  ),\n  pluginName: Schema.String,\n  remoteMarketplaceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"PluginReadParams\" });\n\nexport type V2PluginReadResponse = { readonly plugin: V2PluginReadResponse__PluginDetail };\nexport const V2PluginReadResponse = Schema.Struct({\n  plugin: V2PluginReadResponse__PluginDetail,\n}).annotate({ title: \"PluginReadResponse\" });\n\nexport type V2PluginReadResponse__PluginAvailability = \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\nexport const V2PluginReadResponse__PluginAvailability = Schema.Literals([\n  \"DISABLED_BY_ADMIN\",\n  \"AVAILABLE\",\n]);\n\nexport type V2PluginShareCheckoutParams = { readonly remotePluginId: string };\nexport const V2PluginShareCheckoutParams = Schema.Struct({\n  remotePluginId: Schema.String,\n}).annotate({ title: \"PluginShareCheckoutParams\" });\n\nexport type V2PluginShareCheckoutResponse = {\n  readonly marketplaceName: string;\n  readonly marketplacePath: V2PluginShareCheckoutResponse__AbsolutePathBuf;\n  readonly pluginId: string;\n  readonly pluginName: string;\n  readonly pluginPath: V2PluginShareCheckoutResponse__AbsolutePathBuf;\n  readonly remotePluginId: string;\n  readonly remoteVersion?: string | null;\n};\nexport const V2PluginShareCheckoutResponse = Schema.Struct({\n  marketplaceName: Schema.String,\n  marketplacePath: V2PluginShareCheckoutResponse__AbsolutePathBuf,\n  pluginId: Schema.String,\n  pluginName: Schema.String,\n  pluginPath: V2PluginShareCheckoutResponse__AbsolutePathBuf,\n  remotePluginId: Schema.String,\n  remoteVersion: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"PluginShareCheckoutResponse\" });\n\nexport type V2PluginShareDeleteParams = { readonly remotePluginId: string };\nexport const V2PluginShareDeleteParams = Schema.Struct({ remotePluginId: Schema.String }).annotate({\n  title: \"PluginShareDeleteParams\",\n});\n\nexport type V2PluginShareDeleteResponse = {};\nexport const V2PluginShareDeleteResponse = Schema.Struct({}).annotate({\n  title: \"PluginShareDeleteResponse\",\n});\n\nexport type V2PluginShareListParams = {};\nexport const V2PluginShareListParams = Schema.Struct({}).annotate({\n  title: \"PluginShareListParams\",\n});\n\nexport type V2PluginShareListResponse = {\n  readonly data: ReadonlyArray<V2PluginShareListResponse__PluginShareListItem>;\n};\nexport const V2PluginShareListResponse = Schema.Struct({\n  data: Schema.Array(V2PluginShareListResponse__PluginShareListItem),\n}).annotate({ title: \"PluginShareListResponse\" });\n\nexport type V2PluginShareListResponse__PluginAvailability = \"DISABLED_BY_ADMIN\" | \"AVAILABLE\";\nexport const V2PluginShareListResponse__PluginAvailability = Schema.Literals([\n  \"DISABLED_BY_ADMIN\",\n  \"AVAILABLE\",\n]);\n\nexport type V2PluginShareSaveParams = {\n  readonly discoverability?: V2PluginShareSaveParams__PluginShareDiscoverability | null;\n  readonly pluginPath: V2PluginShareSaveParams__AbsolutePathBuf;\n  readonly remotePluginId?: string | null;\n  readonly shareTargets?: ReadonlyArray<V2PluginShareSaveParams__PluginShareTarget> | null;\n};\nexport const V2PluginShareSaveParams = Schema.Struct({\n  discoverability: Schema.optionalKey(\n    Schema.Union([V2PluginShareSaveParams__PluginShareDiscoverability, Schema.Null]),\n  ),\n  pluginPath: V2PluginShareSaveParams__AbsolutePathBuf,\n  remotePluginId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  shareTargets: Schema.optionalKey(\n    Schema.Union([Schema.Array(V2PluginShareSaveParams__PluginShareTarget), Schema.Null]),\n  ),\n}).annotate({ title: \"PluginShareSaveParams\" });\n\nexport type V2PluginShareSaveResponse = {\n  readonly remotePluginId: string;\n  readonly shareUrl: string;\n};\nexport const V2PluginShareSaveResponse = Schema.Struct({\n  remotePluginId: Schema.String,\n  shareUrl: Schema.String,\n}).annotate({ title: \"PluginShareSaveResponse\" });\n\nexport type V2PluginShareUpdateTargetsParams = {\n  readonly discoverability: V2PluginShareUpdateTargetsParams__PluginShareUpdateDiscoverability;\n  readonly remotePluginId: string;\n  readonly shareTargets: ReadonlyArray<V2PluginShareUpdateTargetsParams__PluginShareTarget>;\n};\nexport const V2PluginShareUpdateTargetsParams = Schema.Struct({\n  discoverability: V2PluginShareUpdateTargetsParams__PluginShareUpdateDiscoverability,\n  remotePluginId: Schema.String,\n  shareTargets: Schema.Array(V2PluginShareUpdateTargetsParams__PluginShareTarget),\n}).annotate({ title: \"PluginShareUpdateTargetsParams\" });\n\nexport type V2PluginShareUpdateTargetsResponse = {\n  readonly discoverability: V2PluginShareUpdateTargetsResponse__PluginShareDiscoverability;\n  readonly principals: ReadonlyArray<V2PluginShareUpdateTargetsResponse__PluginSharePrincipal>;\n};\nexport const V2PluginShareUpdateTargetsResponse = Schema.Struct({\n  discoverability: V2PluginShareUpdateTargetsResponse__PluginShareDiscoverability,\n  principals: Schema.Array(V2PluginShareUpdateTargetsResponse__PluginSharePrincipal),\n}).annotate({ title: \"PluginShareUpdateTargetsResponse\" });\n\nexport type V2PluginSkillReadParams = {\n  readonly remoteMarketplaceName: string;\n  readonly remotePluginId: string;\n  readonly skillName: string;\n};\nexport const V2PluginSkillReadParams = Schema.Struct({\n  remoteMarketplaceName: Schema.String,\n  remotePluginId: Schema.String,\n  skillName: Schema.String,\n}).annotate({ title: \"PluginSkillReadParams\" });\n\nexport type V2PluginSkillReadResponse = { readonly contents?: string | null };\nexport const V2PluginSkillReadResponse = Schema.Struct({\n  contents: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"PluginSkillReadResponse\" });\n\nexport type V2PluginUninstallParams = { readonly pluginId: string };\nexport const V2PluginUninstallParams = Schema.Struct({ pluginId: Schema.String }).annotate({\n  title: \"PluginUninstallParams\",\n});\n\nexport type V2PluginUninstallResponse = {};\nexport const V2PluginUninstallResponse = Schema.Struct({}).annotate({\n  title: \"PluginUninstallResponse\",\n});\n\nexport type V2ProcessExitedNotification = {\n  readonly exitCode: number;\n  readonly processHandle: string;\n  readonly stderr: string;\n  readonly stderrCapReached: boolean;\n  readonly stdout: string;\n  readonly stdoutCapReached: boolean;\n};\nexport const V2ProcessExitedNotification = Schema.Struct({\n  exitCode: Schema.Number.annotate({ description: \"Process exit code.\", format: \"int32\" }).check(\n    Schema.isInt(),\n  ),\n  processHandle: Schema.String.annotate({\n    description: \"Client-supplied, connection-scoped `processHandle` from `process/spawn`.\",\n  }),\n  stderr: Schema.String.annotate({\n    description:\n      \"Buffered stderr capture.\\n\\nEmpty when stderr was streamed via `process/outputDelta`.\",\n  }),\n  stderrCapReached: Schema.Boolean.annotate({\n    description:\n      \"Whether stderr reached `outputBytesCap`.\\n\\nIn streaming mode, stderr is empty and cap state is also reported on the final stderr `process/outputDelta` notification.\",\n  }),\n  stdout: Schema.String.annotate({\n    description:\n      \"Buffered stdout capture.\\n\\nEmpty when stdout was streamed via `process/outputDelta`.\",\n  }),\n  stdoutCapReached: Schema.Boolean.annotate({\n    description:\n      \"Whether stdout reached `outputBytesCap`.\\n\\nIn streaming mode, stdout is empty and cap state is also reported on the final stdout `process/outputDelta` notification.\",\n  }),\n}).annotate({\n  title: \"ProcessExitedNotification\",\n  description: \"Final process exit notification for `process/spawn`.\",\n});\n\nexport type V2ProcessOutputDeltaNotification = {\n  readonly capReached: boolean;\n  readonly deltaBase64: string;\n  readonly processHandle: string;\n  readonly stream: \"stdout\" | \"stderr\";\n};\nexport const V2ProcessOutputDeltaNotification = Schema.Struct({\n  capReached: Schema.Boolean.annotate({\n    description:\n      \"True on the final streamed chunk for this stream when output was truncated by `outputBytesCap`.\",\n  }),\n  deltaBase64: Schema.String.annotate({ description: \"Base64-encoded output bytes.\" }),\n  processHandle: Schema.String.annotate({\n    description: \"Client-supplied, connection-scoped `processHandle` from `process/spawn`.\",\n  }),\n  stream: Schema.Literals([\"stdout\", \"stderr\"]).annotate({\n    description: \"Stream label for `process/outputDelta` notifications.\",\n  }),\n}).annotate({\n  title: \"ProcessOutputDeltaNotification\",\n  description: \"Base64-encoded output chunk emitted for a streaming `process/spawn` request.\",\n});\n\nexport type V2ProcessOutputDeltaNotification__ProcessOutputStream = \"stdout\" | \"stderr\";\nexport const V2ProcessOutputDeltaNotification__ProcessOutputStream = Schema.Literals([\n  \"stdout\",\n  \"stderr\",\n]).annotate({ description: \"Stream label for `process/outputDelta` notifications.\" });\n\nexport type V2RawResponseCompletedNotification = {\n  readonly responseId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n  readonly usage?: V2RawResponseCompletedNotification__TokenUsageBreakdown | null;\n};\nexport const V2RawResponseCompletedNotification = Schema.Struct({\n  responseId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n  usage: Schema.optionalKey(\n    Schema.Union([V2RawResponseCompletedNotification__TokenUsageBreakdown, Schema.Null]),\n  ),\n}).annotate({\n  title: \"RawResponseCompletedNotification\",\n  description:\n    \"Internal-only notification containing the exact usage from one upstream Responses API completion.\",\n});\n\nexport type V2RawResponseItemCompletedNotification = {\n  readonly item: V2RawResponseItemCompletedNotification__ResponseItem;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2RawResponseItemCompletedNotification = Schema.Struct({\n  item: V2RawResponseItemCompletedNotification__ResponseItem,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"RawResponseItemCompletedNotification\" });\n\nexport type V2ReasoningSummaryPartAddedNotification = {\n  readonly itemId: string;\n  readonly summaryIndex: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ReasoningSummaryPartAddedNotification = Schema.Struct({\n  itemId: Schema.String,\n  summaryIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ReasoningSummaryPartAddedNotification\" });\n\nexport type V2ReasoningSummaryTextDeltaNotification = {\n  readonly delta: string;\n  readonly itemId: string;\n  readonly summaryIndex: number;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ReasoningSummaryTextDeltaNotification = Schema.Struct({\n  delta: Schema.String,\n  itemId: Schema.String,\n  summaryIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ReasoningSummaryTextDeltaNotification\" });\n\nexport type V2ReasoningTextDeltaNotification = {\n  readonly contentIndex: number;\n  readonly delta: string;\n  readonly itemId: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2ReasoningTextDeltaNotification = Schema.Struct({\n  contentIndex: Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n  delta: Schema.String,\n  itemId: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"ReasoningTextDeltaNotification\" });\n\nexport type V2RemoteControlStatusChangedNotification = {\n  readonly environmentId?: string | null;\n  readonly installationId: string;\n  readonly serverName: string;\n  readonly status: V2RemoteControlStatusChangedNotification__RemoteControlConnectionStatus;\n};\nexport const V2RemoteControlStatusChangedNotification = Schema.Struct({\n  environmentId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  installationId: Schema.String,\n  serverName: Schema.String,\n  status: V2RemoteControlStatusChangedNotification__RemoteControlConnectionStatus,\n}).annotate({\n  title: \"RemoteControlStatusChangedNotification\",\n  description: \"Current remote-control connection status and remote identity exposed to clients.\",\n});\n\nexport type V2ReviewStartParams = {\n  readonly delivery?: V2ReviewStartParams__ReviewDelivery | null;\n  readonly target: V2ReviewStartParams__ReviewTarget;\n  readonly threadId: string;\n};\nexport const V2ReviewStartParams = Schema.Struct({\n  delivery: Schema.optionalKey(\n    Schema.Union([V2ReviewStartParams__ReviewDelivery, Schema.Null]).annotate({\n      description:\n        \"Where to run the review: inline (default) on the current thread or detached on a new thread (returned in `reviewThreadId`).\",\n    }),\n  ),\n  target: V2ReviewStartParams__ReviewTarget,\n  threadId: Schema.String,\n}).annotate({ title: \"ReviewStartParams\" });\n\nexport type V2ReviewStartResponse = {\n  readonly reviewThreadId: string;\n  readonly turn: V2ReviewStartResponse__Turn;\n};\nexport const V2ReviewStartResponse = Schema.Struct({\n  reviewThreadId: Schema.String.annotate({\n    description:\n      \"Identifies the thread where the review runs.\\n\\nFor inline reviews, this is the original thread id. For detached reviews, this is the id of the new review thread.\",\n  }),\n  turn: V2ReviewStartResponse__Turn,\n}).annotate({ title: \"ReviewStartResponse\" });\n\nexport type V2ReviewStartResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ReviewStartResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ReviewStartResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ReviewStartResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ReviewStartResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ReviewStartResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ReviewStartResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ReviewStartResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ReviewStartResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ReviewStartResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2SendAddCreditsNudgeEmailParams = {\n  readonly creditType: V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType;\n};\nexport const V2SendAddCreditsNudgeEmailParams = Schema.Struct({\n  creditType: V2SendAddCreditsNudgeEmailParams__AddCreditsNudgeCreditType,\n}).annotate({ title: \"SendAddCreditsNudgeEmailParams\" });\n\nexport type V2SendAddCreditsNudgeEmailResponse = {\n  readonly status: V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus;\n};\nexport const V2SendAddCreditsNudgeEmailResponse = Schema.Struct({\n  status: V2SendAddCreditsNudgeEmailResponse__AddCreditsNudgeEmailStatus,\n}).annotate({ title: \"SendAddCreditsNudgeEmailResponse\" });\n\nexport type V2ServerRequestResolvedNotification = {\n  readonly requestId: V2ServerRequestResolvedNotification__RequestId;\n  readonly threadId: string;\n};\nexport const V2ServerRequestResolvedNotification = Schema.Struct({\n  requestId: V2ServerRequestResolvedNotification__RequestId,\n  threadId: Schema.String,\n}).annotate({ title: \"ServerRequestResolvedNotification\" });\n\nexport type V2SkillsChangedNotification = {};\nexport const V2SkillsChangedNotification = Schema.Struct({}).annotate({\n  title: \"SkillsChangedNotification\",\n  description:\n    \"Notification emitted when watched local skill files change.\\n\\nTreat this as an invalidation signal and re-run `skills/list` with the client's current parameters when refreshed skill metadata is needed.\",\n});\n\nexport type V2SkillsConfigWriteParams = {\n  readonly enabled: boolean;\n  readonly name?: string | null;\n  readonly path?: V2SkillsConfigWriteParams__AbsolutePathBuf | null;\n};\nexport const V2SkillsConfigWriteParams = Schema.Struct({\n  enabled: Schema.Boolean,\n  name: Schema.optionalKey(\n    Schema.Union([Schema.String.annotate({ description: \"Name-based selector.\" }), Schema.Null]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([V2SkillsConfigWriteParams__AbsolutePathBuf, Schema.Null]).annotate({\n      description: \"Path-based selector.\",\n    }),\n  ),\n}).annotate({ title: \"SkillsConfigWriteParams\" });\n\nexport type V2SkillsConfigWriteResponse = { readonly effectiveEnabled: boolean };\nexport const V2SkillsConfigWriteResponse = Schema.Struct({\n  effectiveEnabled: Schema.Boolean,\n}).annotate({ title: \"SkillsConfigWriteResponse\" });\n\nexport type V2SkillsExtraRootsSetParams = {\n  readonly extraRoots: ReadonlyArray<V2SkillsExtraRootsSetParams__AbsolutePathBuf>;\n};\nexport const V2SkillsExtraRootsSetParams = Schema.Struct({\n  extraRoots: Schema.Array(V2SkillsExtraRootsSetParams__AbsolutePathBuf),\n}).annotate({ title: \"SkillsExtraRootsSetParams\" });\n\nexport type V2SkillsExtraRootsSetResponse = {};\nexport const V2SkillsExtraRootsSetResponse = Schema.Struct({}).annotate({\n  title: \"SkillsExtraRootsSetResponse\",\n});\n\nexport type V2SkillsListParams = {\n  readonly cwds?: ReadonlyArray<string>;\n  readonly forceReload?: boolean;\n};\nexport const V2SkillsListParams = Schema.Struct({\n  cwds: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"When empty, defaults to the current session working directory.\",\n    }),\n  ),\n  forceReload: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, bypass the skills cache and re-scan skills from disk.\",\n    }),\n  ),\n}).annotate({ title: \"SkillsListParams\" });\n\nexport type V2SkillsListResponse = {\n  readonly data: ReadonlyArray<V2SkillsListResponse__SkillsListEntry>;\n};\nexport const V2SkillsListResponse = Schema.Struct({\n  data: Schema.Array(V2SkillsListResponse__SkillsListEntry),\n}).annotate({ title: \"SkillsListResponse\" });\n\nexport type V2TerminalInteractionNotification = {\n  readonly itemId: string;\n  readonly processId: string;\n  readonly stdin: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2TerminalInteractionNotification = Schema.Struct({\n  itemId: Schema.String,\n  processId: Schema.String,\n  stdin: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"TerminalInteractionNotification\" });\n\nexport type V2ThreadApproveGuardianDeniedActionParams = {\n  readonly event: unknown;\n  readonly threadId: string;\n};\nexport const V2ThreadApproveGuardianDeniedActionParams = Schema.Struct({\n  event: Schema.Unknown.annotate({\n    description: \"Serialized `codex_protocol::protocol::GuardianAssessmentEvent`.\",\n  }),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadApproveGuardianDeniedActionParams\" });\n\nexport type V2ThreadApproveGuardianDeniedActionResponse = {};\nexport const V2ThreadApproveGuardianDeniedActionResponse = Schema.Struct({}).annotate({\n  title: \"ThreadApproveGuardianDeniedActionResponse\",\n});\n\nexport type V2ThreadArchivedNotification = { readonly threadId: string };\nexport const V2ThreadArchivedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadArchivedNotification\",\n});\n\nexport type V2ThreadArchiveParams = { readonly threadId: string };\nexport const V2ThreadArchiveParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadArchiveParams\",\n});\n\nexport type V2ThreadArchiveResponse = {};\nexport const V2ThreadArchiveResponse = Schema.Struct({}).annotate({\n  title: \"ThreadArchiveResponse\",\n});\n\nexport type V2ThreadClosedNotification = { readonly threadId: string };\nexport const V2ThreadClosedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadClosedNotification\",\n});\n\nexport type V2ThreadCompactStartParams = { readonly threadId: string };\nexport const V2ThreadCompactStartParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadCompactStartParams\",\n});\n\nexport type V2ThreadCompactStartResponse = {};\nexport const V2ThreadCompactStartResponse = Schema.Struct({}).annotate({\n  title: \"ThreadCompactStartResponse\",\n});\n\nexport type V2ThreadDeletedNotification = { readonly threadId: string };\nexport const V2ThreadDeletedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadDeletedNotification\",\n});\n\nexport type V2ThreadDeleteParams = { readonly threadId: string };\nexport const V2ThreadDeleteParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadDeleteParams\",\n});\n\nexport type V2ThreadDeleteResponse = {};\nexport const V2ThreadDeleteResponse = Schema.Struct({}).annotate({ title: \"ThreadDeleteResponse\" });\n\nexport type V2ThreadForkParams = {\n  readonly approvalPolicy?: V2ThreadForkParams__AskForApproval | null;\n  readonly approvalsReviewer?: V2ThreadForkParams__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly ephemeral?: boolean;\n  readonly lastTurnId?: string | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly sandbox?: V2ThreadForkParams__SandboxMode | null;\n  readonly serviceTier?: string | null;\n  readonly threadId: string;\n  readonly threadSource?: V2ThreadForkParams__ThreadSource | null;\n};\nexport const V2ThreadForkParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([V2ThreadForkParams__AskForApproval, Schema.Null]),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([V2ThreadForkParams__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  ephemeral: Schema.optionalKey(Schema.Boolean),\n  lastTurnId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional last turn id to fork through, inclusive.\\n\\nWhen specified, turns after `last_turn_id` are omitted from the fork. The referenced turn cannot be in progress.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Configuration overrides for the forked thread, if any.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([V2ThreadForkParams__SandboxMode, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadForkParams__ThreadSource, Schema.Null]).annotate({\n      description:\n        \"Optional client-supplied analytics source classification for this forked thread.\",\n    }),\n  ),\n}).annotate({\n  title: \"ThreadForkParams\",\n  description:\n    \"There are two ways to fork a thread: 1. By thread_id: load the thread from disk by thread_id and fork it into a new thread. 2. By path: load the thread from disk by path and fork it into a new thread.\\n\\nIf using a non-empty path, the thread_id param will be ignored. Empty string path values are treated as absent.\\n\\nPrefer using thread_id whenever possible.\",\n});\n\nexport type V2ThreadForkParams__AbsolutePathBuf = string;\nexport const V2ThreadForkParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadForkResponse = {\n  readonly approvalPolicy: V2ThreadForkResponse__AskForApproval;\n  readonly approvalsReviewer: \"user\" | \"auto_review\" | \"guardian_subagent\";\n  readonly cwd: V2ThreadForkResponse__AbsolutePathBuf;\n  readonly instructionSources?: ReadonlyArray<V2ThreadForkResponse__LegacyAppPathString>;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly reasoningEffort?: V2ThreadForkResponse__ReasoningEffort | null;\n  readonly sandbox:\n    | { readonly type: \"dangerFullAccess\" }\n    | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n    | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n    | {\n        readonly excludeSlashTmp?: boolean;\n        readonly excludeTmpdirEnvVar?: boolean;\n        readonly networkAccess?: boolean;\n        readonly type: \"workspaceWrite\";\n        readonly writableRoots?: ReadonlyArray<V2ThreadForkResponse__AbsolutePathBuf>;\n      };\n  readonly serviceTier?: string | null;\n  readonly thread: V2ThreadForkResponse__Thread;\n};\nexport const V2ThreadForkResponse = Schema.Struct({\n  approvalPolicy: V2ThreadForkResponse__AskForApproval,\n  approvalsReviewer: Schema.Literals([\"user\", \"auto_review\", \"guardian_subagent\"]).annotate({\n    description:\n      \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n  }),\n  cwd: V2ThreadForkResponse__AbsolutePathBuf,\n  instructionSources: Schema.optionalKey(\n    Schema.Array(V2ThreadForkResponse__LegacyAppPathString).annotate({\n      description:\n        \"Environment-native paths to instruction source files currently loaded for this thread.\",\n      default: [],\n    }),\n  ),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  reasoningEffort: Schema.optionalKey(\n    Schema.Union([V2ThreadForkResponse__ReasoningEffort, Schema.Null]),\n  ),\n  sandbox: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"dangerFullAccess\").annotate({\n          title: \"DangerFullAccessSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n      }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(\n          Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n        ),\n        type: Schema.Literal(\"externalSandbox\").annotate({\n          title: \"ExternalSandboxSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n      Schema.Struct({\n        excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"workspaceWrite\").annotate({\n          title: \"WorkspaceWriteSandboxPolicyType\",\n        }),\n        writableRoots: Schema.optionalKey(\n          Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }),\n        ),\n      }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Legacy sandbox policy retained for compatibility. Experimental clients should prefer `activePermissionProfile` for profile provenance.\",\n  }),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  thread: V2ThreadForkResponse__Thread,\n}).annotate({ title: \"ThreadForkResponse\" });\n\nexport type V2ThreadForkResponse__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const V2ThreadForkResponse__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type V2ThreadForkResponse__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadForkResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadForkResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadForkResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadForkResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadForkResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadForkResponse__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadForkResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadForkResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadForkResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadForkResponse__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadForkResponse__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadForkResponse__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2ThreadForkResponse__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2ThreadForkResponse__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2ThreadForkResponse__AbsolutePathBuf>;\n    };\nexport const V2ThreadForkResponse__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2ThreadForkResponse__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadForkResponse__SubAgentSource };\nexport const V2ThreadForkResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadForkResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__ThreadExtra = {};\nexport const V2ThreadForkResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadForkResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadForkResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadForkResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadForkResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadForkResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadForkResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadForkResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadForkResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadGoalClearedNotification = { readonly threadId: string };\nexport const V2ThreadGoalClearedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadGoalClearedNotification\",\n});\n\nexport type V2ThreadGoalClearParams = { readonly threadId: string };\nexport const V2ThreadGoalClearParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadGoalClearParams\",\n});\n\nexport type V2ThreadGoalClearResponse = { readonly cleared: boolean };\nexport const V2ThreadGoalClearResponse = Schema.Struct({ cleared: Schema.Boolean }).annotate({\n  title: \"ThreadGoalClearResponse\",\n});\n\nexport type V2ThreadGoalGetParams = { readonly threadId: string };\nexport const V2ThreadGoalGetParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadGoalGetParams\",\n});\n\nexport type V2ThreadGoalGetResponse = {\n  readonly goal?: V2ThreadGoalGetResponse__ThreadGoal | null;\n};\nexport const V2ThreadGoalGetResponse = Schema.Struct({\n  goal: Schema.optionalKey(Schema.Union([V2ThreadGoalGetResponse__ThreadGoal, Schema.Null])),\n}).annotate({ title: \"ThreadGoalGetResponse\" });\n\nexport type V2ThreadGoalSetParams = {\n  readonly objective?: string | null;\n  readonly status?: V2ThreadGoalSetParams__ThreadGoalStatus | null;\n  readonly threadId: string;\n  readonly tokenBudget?: number | null;\n};\nexport const V2ThreadGoalSetParams = Schema.Struct({\n  objective: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  status: Schema.optionalKey(Schema.Union([V2ThreadGoalSetParams__ThreadGoalStatus, Schema.Null])),\n  threadId: Schema.String,\n  tokenBudget: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n}).annotate({ title: \"ThreadGoalSetParams\" });\n\nexport type V2ThreadGoalSetResponse = { readonly goal: V2ThreadGoalSetResponse__ThreadGoal };\nexport const V2ThreadGoalSetResponse = Schema.Struct({\n  goal: V2ThreadGoalSetResponse__ThreadGoal,\n}).annotate({ title: \"ThreadGoalSetResponse\" });\n\nexport type V2ThreadGoalUpdatedNotification = {\n  readonly goal: V2ThreadGoalUpdatedNotification__ThreadGoal;\n  readonly threadId: string;\n  readonly turnId?: string | null;\n};\nexport const V2ThreadGoalUpdatedNotification = Schema.Struct({\n  goal: V2ThreadGoalUpdatedNotification__ThreadGoal,\n  threadId: Schema.String,\n  turnId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ThreadGoalUpdatedNotification\" });\n\nexport type V2ThreadInjectItemsParams = {\n  readonly items: ReadonlyArray<unknown>;\n  readonly threadId: string;\n};\nexport const V2ThreadInjectItemsParams = Schema.Struct({\n  items: Schema.Array(Schema.Unknown).annotate({\n    description: \"Raw Responses API items to append to the thread's model-visible history.\",\n  }),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadInjectItemsParams\" });\n\nexport type V2ThreadInjectItemsResponse = {};\nexport const V2ThreadInjectItemsResponse = Schema.Struct({}).annotate({\n  title: \"ThreadInjectItemsResponse\",\n});\n\nexport type V2ThreadListParams = {\n  readonly archived?: boolean | null;\n  readonly cursor?: string | null;\n  readonly cwd?: V2ThreadListParams__ThreadListCwdFilter | null;\n  readonly limit?: number | null;\n  readonly modelProviders?: ReadonlyArray<string> | null;\n  readonly searchTerm?: string | null;\n  readonly sortDirection?: V2ThreadListParams__SortDirection | null;\n  readonly sortKey?: V2ThreadListParams__ThreadSortKey | null;\n  readonly sourceKinds?: ReadonlyArray<V2ThreadListParams__ThreadSourceKind> | null;\n  readonly useStateDbOnly?: boolean;\n};\nexport const V2ThreadListParams = Schema.Struct({\n  archived: Schema.optionalKey(\n    Schema.Union([\n      Schema.Boolean.annotate({\n        description:\n          \"Optional archived filter; when set to true, only archived threads are returned. If false or null, only non-archived threads are returned.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([V2ThreadListParams__ThreadListCwdFilter, Schema.Null]).annotate({\n      description:\n        \"Optional cwd filter or filters; when set, only threads whose session cwd exactly matches one of these paths are returned.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to a reasonable server-side value.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  modelProviders: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Optional provider filter; when set, only sessions recorded under these providers are returned. When present but empty, includes all providers.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  searchTerm: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional substring filter for the extracted thread title.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sortDirection: Schema.optionalKey(\n    Schema.Union([V2ThreadListParams__SortDirection, Schema.Null]).annotate({\n      description: \"Optional sort direction; defaults to descending (newest first).\",\n    }),\n  ),\n  sortKey: Schema.optionalKey(\n    Schema.Union([V2ThreadListParams__ThreadSortKey, Schema.Null]).annotate({\n      description: \"Optional sort key; defaults to created_at.\",\n    }),\n  ),\n  sourceKinds: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2ThreadListParams__ThreadSourceKind).annotate({\n        description:\n          \"Optional source filter; when set, only sessions from these source kinds are returned. When omitted or empty, defaults to interactive sources.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  useStateDbOnly: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"If true, return from the state DB without scanning JSONL rollouts to repair thread metadata. Omitted or false preserves scan-and-repair behavior.\",\n    }),\n  ),\n}).annotate({ title: \"ThreadListParams\" });\n\nexport type V2ThreadListResponse = {\n  readonly backwardsCursor?: string | null;\n  readonly data: ReadonlyArray<V2ThreadListResponse__Thread>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ThreadListResponse = Schema.Struct({\n  backwardsCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass as `cursor` when reversing `sortDirection`. This is only populated when the page contains at least one thread. Use it with the opposite `sortDirection`; for timestamp sorts it anchors at the start of the page timestamp so same-second updates are not skipped.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  data: Schema.Array(V2ThreadListResponse__Thread),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ThreadListResponse\" });\n\nexport type V2ThreadListResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadListResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadListResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadListResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadListResponse__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadListResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadListResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadListResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadListResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadListResponse__SubAgentSource };\nexport const V2ThreadListResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadListResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__ThreadExtra = {};\nexport const V2ThreadListResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadListResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadListResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadListResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadListResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadListResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadListResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadListResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadListResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadLoadedListParams = {\n  readonly cursor?: string | null;\n  readonly limit?: number | null;\n};\nexport const V2ThreadLoadedListParams = Schema.Struct({\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Opaque pagination cursor returned by a previous call.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional page size; defaults to no limit.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ThreadLoadedListParams\" });\n\nexport type V2ThreadLoadedListResponse = {\n  readonly data: ReadonlyArray<string>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ThreadLoadedListResponse = Schema.Struct({\n  data: Schema.Array(Schema.String).annotate({\n    description: \"Thread ids for sessions currently loaded in memory.\",\n  }),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor to pass to the next call to continue after the last item. if None, there are no more items to return.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"ThreadLoadedListResponse\" });\n\nexport type V2ThreadMetadataUpdateParams = {\n  readonly gitInfo?: V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams | null;\n  readonly threadId: string;\n};\nexport const V2ThreadMetadataUpdateParams = Schema.Struct({\n  gitInfo: Schema.optionalKey(\n    Schema.Union([\n      V2ThreadMetadataUpdateParams__ThreadMetadataGitInfoUpdateParams,\n      Schema.Null,\n    ]).annotate({\n      description:\n        \"Patch the stored Git metadata for this thread. Omit a field to leave it unchanged, set it to `null` to clear it, or provide a string to replace the stored value.\",\n    }),\n  ),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadMetadataUpdateParams\" });\n\nexport type V2ThreadMetadataUpdateResponse = {\n  readonly thread: V2ThreadMetadataUpdateResponse__Thread;\n};\nexport const V2ThreadMetadataUpdateResponse = Schema.Struct({\n  thread: V2ThreadMetadataUpdateResponse__Thread,\n}).annotate({ title: \"ThreadMetadataUpdateResponse\" });\n\nexport type V2ThreadMetadataUpdateResponse__ByteRange = {\n  readonly end: number;\n  readonly start: number;\n};\nexport const V2ThreadMetadataUpdateResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadMetadataUpdateResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadMetadataUpdateResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadMetadataUpdateResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadMetadataUpdateResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource };\nexport const V2ThreadMetadataUpdateResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadMetadataUpdateResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__ThreadExtra = {};\nexport const V2ThreadMetadataUpdateResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadMetadataUpdateResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadMetadataUpdateResponse__ThreadHistoryMode = Schema.Literals([\n  \"legacy\",\n  \"paginated\",\n]);\n\nexport type V2ThreadMetadataUpdateResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadMetadataUpdateResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadMetadataUpdateResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadMetadataUpdateResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadMetadataUpdateResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadMetadataUpdateResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadNameUpdatedNotification = {\n  readonly threadId: string;\n  readonly threadName?: string | null;\n};\nexport const V2ThreadNameUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  threadName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ title: \"ThreadNameUpdatedNotification\" });\n\nexport type V2ThreadReadParams = { readonly includeTurns?: boolean; readonly threadId: string };\nexport const V2ThreadReadParams = Schema.Struct({\n  includeTurns: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"When true, include turns and their items from rollout history.\",\n    }),\n  ),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadReadParams\" });\n\nexport type V2ThreadReadResponse = { readonly thread: V2ThreadReadResponse__Thread };\nexport const V2ThreadReadResponse = Schema.Struct({\n  thread: V2ThreadReadResponse__Thread,\n}).annotate({ title: \"ThreadReadResponse\" });\n\nexport type V2ThreadReadResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadReadResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadReadResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadReadResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadReadResponse__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2ThreadReadResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadReadResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadReadResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadReadResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadReadResponse__SubAgentSource };\nexport const V2ThreadReadResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadReadResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__ThreadExtra = {};\nexport const V2ThreadReadResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadReadResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadReadResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadReadResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadReadResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadReadResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadReadResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadReadResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadReadResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadRealtimeClosedNotification = {\n  readonly reason?: string | null;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeClosedNotification = Schema.Struct({\n  reason: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeClosedNotification\",\n  description: \"EXPERIMENTAL - emitted when thread realtime transport closes.\",\n});\n\nexport type V2ThreadRealtimeErrorNotification = {\n  readonly message: string;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeErrorNotification = Schema.Struct({\n  message: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeErrorNotification\",\n  description: \"EXPERIMENTAL - emitted when thread realtime encounters an error.\",\n});\n\nexport type V2ThreadRealtimeItemAddedNotification = {\n  readonly item: unknown;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeItemAddedNotification = Schema.Struct({\n  item: Schema.Unknown,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeItemAddedNotification\",\n  description: \"EXPERIMENTAL - raw non-audio thread realtime item emitted by the backend.\",\n});\n\nexport type V2ThreadRealtimeOutputAudioDeltaNotification = {\n  readonly audio: V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeOutputAudioDeltaNotification = Schema.Struct({\n  audio: V2ThreadRealtimeOutputAudioDeltaNotification__ThreadRealtimeAudioChunk,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeOutputAudioDeltaNotification\",\n  description: \"EXPERIMENTAL - streamed output audio emitted by thread realtime.\",\n});\n\nexport type V2ThreadRealtimeSdpNotification = { readonly sdp: string; readonly threadId: string };\nexport const V2ThreadRealtimeSdpNotification = Schema.Struct({\n  sdp: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeSdpNotification\",\n  description: \"EXPERIMENTAL - emitted with the remote SDP for a WebRTC realtime session.\",\n});\n\nexport type V2ThreadRealtimeStartedNotification = {\n  readonly realtimeSessionId?: string | null;\n  readonly threadId: string;\n  readonly version: V2ThreadRealtimeStartedNotification__RealtimeConversationVersion;\n};\nexport const V2ThreadRealtimeStartedNotification = Schema.Struct({\n  realtimeSessionId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n  version: V2ThreadRealtimeStartedNotification__RealtimeConversationVersion,\n}).annotate({\n  title: \"ThreadRealtimeStartedNotification\",\n  description: \"EXPERIMENTAL - emitted when thread realtime startup is accepted.\",\n});\n\nexport type V2ThreadRealtimeTranscriptDeltaNotification = {\n  readonly delta: string;\n  readonly role: string;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeTranscriptDeltaNotification = Schema.Struct({\n  delta: Schema.String.annotate({ description: \"Live transcript delta from the realtime event.\" }),\n  role: Schema.String,\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeTranscriptDeltaNotification\",\n  description:\n    \"EXPERIMENTAL - flat transcript delta emitted whenever realtime transcript text changes.\",\n});\n\nexport type V2ThreadRealtimeTranscriptDoneNotification = {\n  readonly role: string;\n  readonly text: string;\n  readonly threadId: string;\n};\nexport const V2ThreadRealtimeTranscriptDoneNotification = Schema.Struct({\n  role: Schema.String,\n  text: Schema.String.annotate({ description: \"Final complete text for the transcript part.\" }),\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRealtimeTranscriptDoneNotification\",\n  description:\n    \"EXPERIMENTAL - final transcript text emitted when realtime completes a transcript part.\",\n});\n\nexport type V2ThreadResumeParams = {\n  readonly approvalPolicy?: V2ThreadResumeParams__AskForApproval | null;\n  readonly approvalsReviewer?: V2ThreadResumeParams__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly personality?: V2ThreadResumeParams__Personality | null;\n  readonly sandbox?: V2ThreadResumeParams__SandboxMode | null;\n  readonly serviceTier?: string | null;\n  readonly threadId: string;\n};\nexport const V2ThreadResumeParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeParams__AskForApproval, Schema.Null]),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeParams__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Configuration overrides for the resumed thread, if any.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  personality: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__Personality, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__SandboxMode, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadResumeParams\",\n  description:\n    \"There are three ways to resume a thread: 1. By thread_id: load the thread from disk by thread_id and resume it. 2. By history: instantiate the thread from memory and resume it. 3. By path: load the thread from disk by path and resume it.\\n\\nFor non-running threads, the precedence is: history > non-empty path > thread_id. If using history or a non-empty path for a non-running thread, the thread_id param will be ignored.\\n\\nIf thread_id identifies a running thread, app-server rejoins that thread and treats a non-empty path as a consistency check against the active rollout path. Empty string path values are treated as absent.\\n\\nPrefer using thread_id whenever possible.\",\n});\n\nexport type V2ThreadResumeParams__AbsolutePathBuf = string;\nexport const V2ThreadResumeParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadResumeParams__ResponseItem =\n  | {\n      readonly content: ReadonlyArray<V2ThreadResumeParams__ContentItem>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly phase?: V2ThreadResumeParams__MessagePhase | null;\n      readonly role: string;\n      readonly type: \"message\";\n    }\n  | {\n      readonly author: string;\n      readonly content: ReadonlyArray<V2ThreadResumeParams__AgentMessageInputContent>;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly recipient: string;\n      readonly type: \"agent_message\";\n    }\n  | {\n      readonly content?: ReadonlyArray<V2ThreadResumeParams__ReasoningItemContent> | null;\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly summary: ReadonlyArray<V2ThreadResumeParams__ReasoningItemReasoningSummary>;\n      readonly type: \"reasoning\";\n    }\n  | {\n      readonly action: V2ThreadResumeParams__LocalShellAction;\n      readonly call_id?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly status: V2ThreadResumeParams__LocalShellStatus;\n      readonly type: \"local_shell_call\";\n    }\n  | {\n      readonly arguments: string;\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly type: \"function_call\";\n    }\n  | {\n      readonly arguments: unknown;\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"tool_search_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly output: V2ThreadResumeParams__FunctionCallOutputBody;\n      readonly type: \"function_call_output\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly input: string;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly name: string;\n      readonly namespace?: string | null;\n      readonly status?: string | null;\n      readonly type: \"custom_tool_call\";\n    }\n  | {\n      readonly call_id: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly name?: string | null;\n      readonly output: V2ThreadResumeParams__FunctionCallOutputBody;\n      readonly type: \"custom_tool_call_output\";\n    }\n  | {\n      readonly call_id?: string | null;\n      readonly execution: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly status: string;\n      readonly tools: ReadonlyArray<unknown>;\n      readonly type: \"tool_search_output\";\n    }\n  | {\n      readonly action?: V2ThreadResumeParams__ResponsesApiWebSearchAction | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly status?: string | null;\n      readonly type: \"web_search_call\";\n    }\n  | {\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly result: string;\n      readonly revised_prompt?: string | null;\n      readonly status: string;\n      readonly type: \"image_generation_call\";\n    }\n  | {\n      readonly encrypted_content: string;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"compaction\";\n    }\n  | { readonly type: \"compaction_trigger\" }\n  | {\n      readonly encrypted_content?: string | null;\n      readonly id?: string | null;\n      readonly internal_chat_message_metadata_passthrough?: V2ThreadResumeParams__InternalChatMessageMetadataPassthrough | null;\n      readonly type: \"context_compaction\";\n    }\n  | { readonly type: \"other\" };\nexport const V2ThreadResumeParams__ResponseItem = Schema.Union(\n  [\n    Schema.Struct({\n      content: Schema.Array(V2ThreadResumeParams__ContentItem),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      phase: Schema.optionalKey(Schema.Union([V2ThreadResumeParams__MessagePhase, Schema.Null])),\n      role: Schema.String,\n      type: Schema.Literal(\"message\").annotate({ title: \"MessageResponseItemType\" }),\n    }).annotate({ title: \"MessageResponseItem\" }),\n    Schema.Struct({\n      author: Schema.String,\n      content: Schema.Array(V2ThreadResumeParams__AgentMessageInputContent),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      recipient: Schema.String,\n      type: Schema.Literal(\"agent_message\").annotate({ title: \"AgentMessageResponseItemType\" }),\n    }).annotate({ title: \"AgentMessageResponseItem\" }),\n    Schema.Struct({\n      content: Schema.optionalKey(\n        Schema.Union([Schema.Array(V2ThreadResumeParams__ReasoningItemContent), Schema.Null]),\n      ),\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      summary: Schema.Array(V2ThreadResumeParams__ReasoningItemReasoningSummary),\n      type: Schema.Literal(\"reasoning\").annotate({ title: \"ReasoningResponseItemType\" }),\n    }).annotate({ title: \"ReasoningResponseItem\" }),\n    Schema.Struct({\n      action: V2ThreadResumeParams__LocalShellAction,\n      call_id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Set when using the Responses API.\" }),\n          Schema.Null,\n        ]),\n      ),\n      id: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Legacy id field retained for compatibility with older payloads.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: V2ThreadResumeParams__LocalShellStatus,\n      type: Schema.Literal(\"local_shell_call\").annotate({\n        title: \"LocalShellCallResponseItemType\",\n      }),\n    }).annotate({ title: \"LocalShellCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.String,\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"function_call\").annotate({ title: \"FunctionCallResponseItemType\" }),\n    }).annotate({ title: \"FunctionCallResponseItem\" }),\n    Schema.Struct({\n      arguments: Schema.Unknown,\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"tool_search_call\").annotate({\n        title: \"ToolSearchCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      output: V2ThreadResumeParams__FunctionCallOutputBody,\n      type: Schema.Literal(\"function_call_output\").annotate({\n        title: \"FunctionCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"FunctionCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      input: Schema.String,\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.String,\n      namespace: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"custom_tool_call\").annotate({\n        title: \"CustomToolCallResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      name: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      output: V2ThreadResumeParams__FunctionCallOutputBody,\n      type: Schema.Literal(\"custom_tool_call_output\").annotate({\n        title: \"CustomToolCallOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"CustomToolCallOutputResponseItem\" }),\n    Schema.Struct({\n      call_id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      execution: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.String,\n      tools: Schema.Array(Schema.Unknown),\n      type: Schema.Literal(\"tool_search_output\").annotate({\n        title: \"ToolSearchOutputResponseItemType\",\n      }),\n    }).annotate({ title: \"ToolSearchOutputResponseItem\" }),\n    Schema.Struct({\n      action: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__ResponsesApiWebSearchAction, Schema.Null]),\n      ),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      status: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      type: Schema.Literal(\"web_search_call\").annotate({ title: \"WebSearchCallResponseItemType\" }),\n    }).annotate({ title: \"WebSearchCallResponseItem\" }),\n    Schema.Struct({\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      result: Schema.String,\n      revised_prompt: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      status: Schema.String,\n      type: Schema.Literal(\"image_generation_call\").annotate({\n        title: \"ImageGenerationCallResponseItemType\",\n      }),\n    }).annotate({ title: \"ImageGenerationCallResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.String,\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      type: Schema.Literal(\"compaction\").annotate({ title: \"CompactionResponseItemType\" }),\n    }).annotate({ title: \"CompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"compaction_trigger\").annotate({\n        title: \"CompactionTriggerResponseItemType\",\n      }),\n    }).annotate({ title: \"CompactionTriggerResponseItem\" }),\n    Schema.Struct({\n      encrypted_content: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      id: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      internal_chat_message_metadata_passthrough: Schema.optionalKey(\n        Schema.Union([V2ThreadResumeParams__InternalChatMessageMetadataPassthrough, Schema.Null]),\n      ),\n      type: Schema.Literal(\"context_compaction\").annotate({\n        title: \"ContextCompactionResponseItemType\",\n      }),\n    }).annotate({ title: \"ContextCompactionResponseItem\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"other\").annotate({ title: \"OtherResponseItemType\" }),\n    }).annotate({ title: \"OtherResponseItem\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeParams__ThreadResumeInitialTurnsPageParams = {\n  readonly itemsView?: V2ThreadResumeParams__TurnItemsView | null;\n  readonly limit?: number | null;\n  readonly sortDirection?: V2ThreadResumeParams__SortDirection | null;\n};\nexport const V2ThreadResumeParams__ThreadResumeInitialTurnsPageParams = Schema.Struct({\n  itemsView: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeParams__TurnItemsView, Schema.Null]).annotate({\n      description: \"How much item detail to include for each returned turn; defaults to summary.\",\n    }),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Optional turn page size.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  sortDirection: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeParams__SortDirection, Schema.Null]).annotate({\n      description: \"Optional turn pagination direction; defaults to descending.\",\n    }),\n  ),\n});\n\nexport type V2ThreadResumeResponse = {\n  readonly approvalPolicy: V2ThreadResumeResponse__AskForApproval;\n  readonly approvalsReviewer: \"user\" | \"auto_review\" | \"guardian_subagent\";\n  readonly cwd: V2ThreadResumeResponse__AbsolutePathBuf;\n  readonly instructionSources?: ReadonlyArray<V2ThreadResumeResponse__LegacyAppPathString>;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly reasoningEffort?: V2ThreadResumeResponse__ReasoningEffort | null;\n  readonly sandbox:\n    | { readonly type: \"dangerFullAccess\" }\n    | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n    | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n    | {\n        readonly excludeSlashTmp?: boolean;\n        readonly excludeTmpdirEnvVar?: boolean;\n        readonly networkAccess?: boolean;\n        readonly type: \"workspaceWrite\";\n        readonly writableRoots?: ReadonlyArray<V2ThreadResumeResponse__AbsolutePathBuf>;\n      };\n  readonly serviceTier?: string | null;\n  readonly thread: V2ThreadResumeResponse__Thread;\n};\nexport const V2ThreadResumeResponse = Schema.Struct({\n  approvalPolicy: V2ThreadResumeResponse__AskForApproval,\n  approvalsReviewer: Schema.Literals([\"user\", \"auto_review\", \"guardian_subagent\"]).annotate({\n    description:\n      \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n  }),\n  cwd: V2ThreadResumeResponse__AbsolutePathBuf,\n  instructionSources: Schema.optionalKey(\n    Schema.Array(V2ThreadResumeResponse__LegacyAppPathString).annotate({\n      description:\n        \"Environment-native paths to instruction source files currently loaded for this thread.\",\n      default: [],\n    }),\n  ),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  reasoningEffort: Schema.optionalKey(\n    Schema.Union([V2ThreadResumeResponse__ReasoningEffort, Schema.Null]),\n  ),\n  sandbox: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"dangerFullAccess\").annotate({\n          title: \"DangerFullAccessSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n      }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(\n          Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n        ),\n        type: Schema.Literal(\"externalSandbox\").annotate({\n          title: \"ExternalSandboxSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n      Schema.Struct({\n        excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"workspaceWrite\").annotate({\n          title: \"WorkspaceWriteSandboxPolicyType\",\n        }),\n        writableRoots: Schema.optionalKey(\n          Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }),\n        ),\n      }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Legacy sandbox policy retained for compatibility. Experimental clients should prefer `activePermissionProfile` for profile provenance.\",\n  }),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  thread: V2ThreadResumeResponse__Thread,\n}).annotate({ title: \"ThreadResumeResponse\" });\n\nexport type V2ThreadResumeResponse__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const V2ThreadResumeResponse__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type V2ThreadResumeResponse__ApprovalsReviewer =\n  | \"user\"\n  | \"auto_review\"\n  | \"guardian_subagent\";\nexport const V2ThreadResumeResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadResumeResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadResumeResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadResumeResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadResumeResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadResumeResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadResumeResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadResumeResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadResumeResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadResumeResponse__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadResumeResponse__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadResumeResponse__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2ThreadResumeResponse__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2ThreadResumeResponse__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2ThreadResumeResponse__AbsolutePathBuf>;\n    };\nexport const V2ThreadResumeResponse__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2ThreadResumeResponse__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadResumeResponse__SubAgentSource };\nexport const V2ThreadResumeResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadResumeResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__ThreadExtra = {};\nexport const V2ThreadResumeResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadResumeResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadResumeResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadResumeResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadResumeResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadResumeResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadResumeResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadResumeResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadResumeResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadResumeResponse__TurnsPage = {\n  readonly backwardsCursor?: string | null;\n  readonly data: ReadonlyArray<V2ThreadResumeResponse__Turn>;\n  readonly nextCursor?: string | null;\n};\nexport const V2ThreadResumeResponse__TurnsPage = Schema.Struct({\n  backwardsCursor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  data: Schema.Array(V2ThreadResumeResponse__Turn),\n  nextCursor: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n});\n\nexport type V2ThreadRollbackParams = { readonly numTurns: number; readonly threadId: string };\nexport const V2ThreadRollbackParams = Schema.Struct({\n  numTurns: Schema.Number.annotate({\n    description:\n      \"The number of turns to drop from the end of the thread. Must be >= 1.\\n\\nThis only modifies the thread's history and does not revert local file changes that have been made by the agent. Clients are responsible for reverting these changes.\",\n    format: \"uint32\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  threadId: Schema.String,\n}).annotate({\n  title: \"ThreadRollbackParams\",\n  description: \"DEPRECATED: `thread/rollback` will be removed soon.\",\n});\n\nexport type V2ThreadRollbackResponse = {\n  readonly thread: {\n    readonly agentNickname?: string | null;\n    readonly agentRole?: string | null;\n    readonly cliVersion: string;\n    readonly createdAt: number;\n    readonly cwd: string;\n    readonly ephemeral: boolean;\n    readonly forkedFromId?: string | null;\n    readonly gitInfo?: V2ThreadRollbackResponse__GitInfo | null;\n    readonly id: string;\n    readonly modelProvider: string;\n    readonly name?: string | null;\n    readonly parentThreadId?: string | null;\n    readonly path?: string | null;\n    readonly preview: string;\n    readonly recencyAt?: number | null;\n    readonly sessionId: string;\n    readonly source:\n      | \"cli\"\n      | \"vscode\"\n      | \"exec\"\n      | \"appServer\"\n      | \"unknown\"\n      | { readonly custom: string }\n      | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource };\n    readonly status:\n      | { readonly type: \"notLoaded\" }\n      | { readonly type: \"idle\" }\n      | { readonly type: \"systemError\" }\n      | {\n          readonly activeFlags: ReadonlyArray<V2ThreadRollbackResponse__ThreadActiveFlag>;\n          readonly type: \"active\";\n        };\n    readonly threadSource?: V2ThreadRollbackResponse__ThreadSource | null;\n    readonly turns: ReadonlyArray<V2ThreadRollbackResponse__Turn>;\n    readonly updatedAt: number;\n  };\n};\nexport const V2ThreadRollbackResponse = Schema.Struct({\n  thread: Schema.Struct({\n    agentNickname: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    agentRole: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    cliVersion: Schema.String.annotate({\n      description: \"Version of the CLI that created the thread.\",\n    }),\n    createdAt: Schema.Number.annotate({\n      description: \"Unix timestamp (in seconds) when the thread was created.\",\n      format: \"int64\",\n    }).check(Schema.isInt()),\n    cwd: Schema.String.annotate({\n      description:\n        \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n    }),\n    ephemeral: Schema.Boolean.annotate({\n      description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n    }),\n    forkedFromId: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Source thread id when this thread was created by forking another thread.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    gitInfo: Schema.optionalKey(\n      Schema.Union([V2ThreadRollbackResponse__GitInfo, Schema.Null]).annotate({\n        description: \"Optional Git metadata captured when the thread was created.\",\n      }),\n    ),\n    id: Schema.String.annotate({\n      description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n    }),\n    modelProvider: Schema.String.annotate({\n      description: \"Model provider used for this thread (for example, 'openai').\",\n    }),\n    name: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n        Schema.Null,\n      ]),\n    ),\n    parentThreadId: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    path: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n        Schema.Null,\n      ]),\n    ),\n    preview: Schema.String.annotate({\n      description: \"Usually the first user message in the thread, if available.\",\n    }),\n    recencyAt: Schema.optionalKey(\n      Schema.Union([\n        Schema.Number.annotate({\n          description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n          format: \"int64\",\n        }).check(Schema.isInt()),\n        Schema.Null,\n      ]),\n    ),\n    sessionId: Schema.String.annotate({\n      description: \"Session id shared by threads that belong to the same session tree.\",\n    }),\n    source: Schema.Union(\n      [\n        Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n        Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n        Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({\n          title: \"SubAgentSessionSource\",\n        }),\n      ],\n      { mode: \"oneOf\" },\n    ).annotate({\n      description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n    }),\n    status: Schema.Union(\n      [\n        Schema.Struct({\n          type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n        }).annotate({ title: \"NotLoadedThreadStatus\" }),\n        Schema.Struct({\n          type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n        }).annotate({ title: \"IdleThreadStatus\" }),\n        Schema.Struct({\n          type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n        }).annotate({ title: \"SystemErrorThreadStatus\" }),\n        Schema.Struct({\n          activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag),\n          type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n        }).annotate({ title: \"ActiveThreadStatus\" }),\n      ],\n      { mode: \"oneOf\" },\n    ).annotate({ description: \"Current runtime status for the thread.\" }),\n    threadSource: Schema.optionalKey(\n      Schema.Union([V2ThreadRollbackResponse__ThreadSource, Schema.Null]).annotate({\n        description: \"Optional analytics source classification for this thread.\",\n      }),\n    ),\n    turns: Schema.Array(V2ThreadRollbackResponse__Turn).annotate({\n      description:\n        \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n    }),\n    updatedAt: Schema.Number.annotate({\n      description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n      format: \"int64\",\n    }).check(Schema.isInt()),\n  }).annotate({\n    description:\n      \"The updated thread after applying the rollback, with `turns` populated.\\n\\nThe ThreadItems stored in each Turn are lossy since we explicitly do not persist all agent interactions, such as command executions. This is the same behavior as `thread/resume`.\",\n  }),\n}).annotate({ title: \"ThreadRollbackResponse\" });\n\nexport type V2ThreadRollbackResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadRollbackResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadRollbackResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadRollbackResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadRollbackResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadRollbackResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadRollbackResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadRollbackResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadRollbackResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource };\nexport const V2ThreadRollbackResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__Thread = {\n  readonly agentNickname?: string | null;\n  readonly agentRole?: string | null;\n  readonly cliVersion: string;\n  readonly createdAt: number;\n  readonly cwd: string;\n  readonly ephemeral: boolean;\n  readonly forkedFromId?: string | null;\n  readonly gitInfo?: V2ThreadRollbackResponse__GitInfo | null;\n  readonly id: string;\n  readonly modelProvider: string;\n  readonly name?: string | null;\n  readonly parentThreadId?: string | null;\n  readonly path?: string | null;\n  readonly preview: string;\n  readonly recencyAt?: number | null;\n  readonly sessionId: string;\n  readonly source:\n    | \"cli\"\n    | \"vscode\"\n    | \"exec\"\n    | \"appServer\"\n    | \"unknown\"\n    | { readonly custom: string }\n    | { readonly subAgent: V2ThreadRollbackResponse__SubAgentSource };\n  readonly status:\n    | { readonly type: \"notLoaded\" }\n    | { readonly type: \"idle\" }\n    | { readonly type: \"systemError\" }\n    | {\n        readonly activeFlags: ReadonlyArray<V2ThreadRollbackResponse__ThreadActiveFlag>;\n        readonly type: \"active\";\n      };\n  readonly threadSource?: V2ThreadRollbackResponse__ThreadSource | null;\n  readonly turns: ReadonlyArray<V2ThreadRollbackResponse__Turn>;\n  readonly updatedAt: number;\n};\nexport const V2ThreadRollbackResponse__Thread = Schema.Struct({\n  agentNickname: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional random unique nickname assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentRole: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cliVersion: Schema.String.annotate({\n    description: \"Version of the CLI that created the thread.\",\n  }),\n  createdAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was created.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n  cwd: Schema.String.annotate({\n    description:\n      \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n  }),\n  ephemeral: Schema.Boolean.annotate({\n    description: \"Whether the thread is ephemeral and should not be materialized on disk.\",\n  }),\n  forkedFromId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Source thread id when this thread was created by forking another thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  gitInfo: Schema.optionalKey(\n    Schema.Union([V2ThreadRollbackResponse__GitInfo, Schema.Null]).annotate({\n      description: \"Optional Git metadata captured when the thread was created.\",\n    }),\n  ),\n  id: Schema.String.annotate({\n    description: \"Identifier for this thread. Codex-generated thread IDs are UUIDv7.\",\n  }),\n  modelProvider: Schema.String.annotate({\n    description: \"Model provider used for this thread (for example, 'openai').\",\n  }),\n  name: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional user-facing thread title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  parentThreadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"The ID of the parent thread. This will only be set if this thread is a subagent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"[UNSTABLE] Path to the thread on disk.\" }),\n      Schema.Null,\n    ]),\n  ),\n  preview: Schema.String.annotate({\n    description: \"Usually the first user message in the thread, if available.\",\n  }),\n  recencyAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Unix timestamp (in seconds) used for thread recency ordering.\",\n        format: \"int64\",\n      }).check(Schema.isInt()),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description: \"Session id shared by threads that belong to the same session tree.\",\n  }),\n  source: Schema.Union(\n    [\n      Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n      Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n      Schema.Struct({ subAgent: V2ThreadRollbackResponse__SubAgentSource }).annotate({\n        title: \"SubAgentSessionSource\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description: \"Origin of the thread (CLI, VSCode, codex exec, codex app-server, etc.).\",\n  }),\n  status: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n      }).annotate({ title: \"NotLoadedThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n      }).annotate({ title: \"IdleThreadStatus\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n      }).annotate({ title: \"SystemErrorThreadStatus\" }),\n      Schema.Struct({\n        activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag),\n        type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n      }).annotate({ title: \"ActiveThreadStatus\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Current runtime status for the thread.\" }),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadRollbackResponse__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional analytics source classification for this thread.\",\n    }),\n  ),\n  turns: Schema.Array(V2ThreadRollbackResponse__Turn).annotate({\n    description:\n      \"Only populated on `thread/resume`, `thread/rollback`, `thread/fork`, and `thread/read` (when `includeTurns` is true) responses. For all other responses and notifications returning a Thread, the turns field will be an empty list.\",\n  }),\n  updatedAt: Schema.Number.annotate({\n    description: \"Unix timestamp (in seconds) when the thread was last updated.\",\n    format: \"int64\",\n  }).check(Schema.isInt()),\n});\n\nexport type V2ThreadRollbackResponse__ThreadExtra = {};\nexport const V2ThreadRollbackResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadRollbackResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadRollbackResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadRollbackResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadRollbackResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadRollbackResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadRollbackResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadRollbackResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadRollbackResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadSetNameParams = { readonly name: string; readonly threadId: string };\nexport const V2ThreadSetNameParams = Schema.Struct({\n  name: Schema.String,\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadSetNameParams\" });\n\nexport type V2ThreadSetNameResponse = {};\nexport const V2ThreadSetNameResponse = Schema.Struct({}).annotate({\n  title: \"ThreadSetNameResponse\",\n});\n\nexport type V2ThreadSettingsUpdatedNotification = {\n  readonly threadId: string;\n  readonly threadSettings: V2ThreadSettingsUpdatedNotification__ThreadSettings;\n};\nexport const V2ThreadSettingsUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  threadSettings: V2ThreadSettingsUpdatedNotification__ThreadSettings,\n}).annotate({ title: \"ThreadSettingsUpdatedNotification\" });\n\nexport type V2ThreadSettingsUpdatedNotification__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadSettingsUpdatedNotification__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadSettingsUpdatedNotification__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2ThreadSettingsUpdatedNotification__NetworkAccess = Schema.Literals([\n  \"restricted\",\n  \"enabled\",\n]);\n\nexport type V2ThreadShellCommandParams = { readonly command: string; readonly threadId: string };\nexport const V2ThreadShellCommandParams = Schema.Struct({\n  command: Schema.String.annotate({\n    description:\n      \"Shell command string evaluated by the thread's configured shell. Unlike `command/exec`, this intentionally preserves shell syntax such as pipes, redirects, and quoting. This runs unsandboxed with full access rather than inheriting the thread sandbox policy.\",\n  }),\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadShellCommandParams\" });\n\nexport type V2ThreadShellCommandResponse = {};\nexport const V2ThreadShellCommandResponse = Schema.Struct({}).annotate({\n  title: \"ThreadShellCommandResponse\",\n});\n\nexport type V2ThreadStartedNotification = { readonly thread: V2ThreadStartedNotification__Thread };\nexport const V2ThreadStartedNotification = Schema.Struct({\n  thread: V2ThreadStartedNotification__Thread,\n}).annotate({ title: \"ThreadStartedNotification\" });\n\nexport type V2ThreadStartedNotification__ByteRange = {\n  readonly end: number;\n  readonly start: number;\n};\nexport const V2ThreadStartedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadStartedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadStartedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadStartedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadStartedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadStartedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadStartedNotification__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadStartedNotification__SubAgentSource };\nexport const V2ThreadStartedNotification__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadStartedNotification__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__ThreadExtra = {};\nexport const V2ThreadStartedNotification__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadStartedNotification__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadStartedNotification__ThreadHistoryMode = Schema.Literals([\n  \"legacy\",\n  \"paginated\",\n]);\n\nexport type V2ThreadStartedNotification__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadStartedNotification__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadStartedNotification__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadStartedNotification__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartedNotification__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadStartedNotification__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadStartParams = {\n  readonly approvalPolicy?: V2ThreadStartParams__AskForApproval | null;\n  readonly approvalsReviewer?: V2ThreadStartParams__ApprovalsReviewer | null;\n  readonly baseInstructions?: string | null;\n  readonly config?: { readonly [x: string]: unknown } | null;\n  readonly cwd?: string | null;\n  readonly developerInstructions?: string | null;\n  readonly ephemeral?: boolean | null;\n  readonly model?: string | null;\n  readonly modelProvider?: string | null;\n  readonly personality?: V2ThreadStartParams__Personality | null;\n  readonly sandbox?: V2ThreadStartParams__SandboxMode | null;\n  readonly serviceName?: string | null;\n  readonly serviceTier?: string | null;\n  readonly sessionStartSource?: V2ThreadStartParams__ThreadStartSource | null;\n  readonly threadSource?: V2ThreadStartParams__ThreadSource | null;\n};\nexport const V2ThreadStartParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([V2ThreadStartParams__AskForApproval, Schema.Null]),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([V2ThreadStartParams__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this thread and subsequent turns.\",\n    }),\n  ),\n  baseInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  config: Schema.optionalKey(\n    Schema.Union([Schema.Record(Schema.String, Schema.Unknown), Schema.Null]),\n  ),\n  cwd: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  developerInstructions: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  ephemeral: Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])),\n  model: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  modelProvider: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  personality: Schema.optionalKey(Schema.Union([V2ThreadStartParams__Personality, Schema.Null])),\n  sandbox: Schema.optionalKey(Schema.Union([V2ThreadStartParams__SandboxMode, Schema.Null])),\n  serviceName: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  sessionStartSource: Schema.optionalKey(\n    Schema.Union([V2ThreadStartParams__ThreadStartSource, Schema.Null]),\n  ),\n  threadSource: Schema.optionalKey(\n    Schema.Union([V2ThreadStartParams__ThreadSource, Schema.Null]).annotate({\n      description: \"Optional client-supplied analytics source classification for this thread.\",\n    }),\n  ),\n}).annotate({ title: \"ThreadStartParams\" });\n\nexport type V2ThreadStartParams__AbsolutePathBuf = string;\nexport const V2ThreadStartParams__AbsolutePathBuf = Schema.String.annotate({\n  description:\n    \"A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\\n\\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.\",\n});\n\nexport type V2ThreadStartParams__CapabilityRootLocation = {\n  readonly environmentId: string;\n  readonly path: string;\n  readonly type: \"environment\";\n};\nexport const V2ThreadStartParams__CapabilityRootLocation = Schema.Union(\n  [\n    Schema.Struct({\n      environmentId: Schema.String,\n      path: Schema.String.annotate({\n        description: \"Absolute path for the root in the selected environment.\",\n      }),\n      type: Schema.Literal(\"environment\").annotate({\n        title: \"EnvironmentCapabilityRootLocationType\",\n      }),\n    }).annotate({\n      title: \"EnvironmentCapabilityRootLocation\",\n      description: \"A path owned by an execution environment.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"Location used to resolve a selected capability root.\" });\n\nexport type V2ThreadStartParams__DynamicToolSpec =\n  | {\n      readonly deferLoading?: boolean;\n      readonly description: string;\n      readonly inputSchema: unknown;\n      readonly name: string;\n      readonly type: \"function\";\n    }\n  | {\n      readonly description: string;\n      readonly name: string;\n      readonly tools: ReadonlyArray<V2ThreadStartParams__DynamicToolNamespaceTool>;\n      readonly type: \"namespace\";\n    };\nexport const V2ThreadStartParams__DynamicToolSpec = Schema.Union(\n  [\n    Schema.Struct({\n      deferLoading: Schema.optionalKey(Schema.Boolean),\n      description: Schema.String,\n      inputSchema: Schema.Unknown,\n      name: Schema.String,\n      type: Schema.Literal(\"function\").annotate({ title: \"FunctionDynamicToolSpecType\" }),\n    }).annotate({ title: \"FunctionDynamicToolSpec\" }),\n    Schema.Struct({\n      description: Schema.String,\n      name: Schema.String,\n      tools: Schema.Array(V2ThreadStartParams__DynamicToolNamespaceTool),\n      type: Schema.Literal(\"namespace\").annotate({ title: \"NamespaceDynamicToolSpecType\" }),\n    }).annotate({ title: \"NamespaceDynamicToolSpec\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartParams__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadStartParams__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadStartParams__SelectedCapabilityRoot = {\n  readonly id: string;\n  readonly location: {\n    readonly environmentId: string;\n    readonly path: string;\n    readonly type: \"environment\";\n  };\n};\nexport const V2ThreadStartParams__SelectedCapabilityRoot = Schema.Struct({\n  id: Schema.String.annotate({\n    description: \"Stable identifier supplied by the capability selection platform.\",\n  }),\n  location: Schema.Union(\n    [\n      Schema.Struct({\n        environmentId: Schema.String,\n        path: Schema.String.annotate({\n          description: \"Absolute path for the root in the selected environment.\",\n        }),\n        type: Schema.Literal(\"environment\").annotate({\n          title: \"EnvironmentCapabilityRootLocationType\",\n        }),\n      }).annotate({\n        title: \"EnvironmentCapabilityRootLocation\",\n        description: \"A path owned by an execution environment.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"Location used to resolve a selected capability root.\" }),\n}).annotate({\n  description: \"A user-selected root that can expose one or more runtime capabilities.\",\n});\n\nexport type V2ThreadStartParams__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadStartParams__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadStartParams__TurnEnvironmentParams = {\n  readonly cwd: V2ThreadStartParams__LegacyAppPathString;\n  readonly environmentId: string;\n  readonly runtimeWorkspaceRoots?: ReadonlyArray<V2ThreadStartParams__LegacyAppPathString> | null;\n};\nexport const V2ThreadStartParams__TurnEnvironmentParams = Schema.Struct({\n  cwd: V2ThreadStartParams__LegacyAppPathString,\n  environmentId: Schema.String,\n  runtimeWorkspaceRoots: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2ThreadStartParams__LegacyAppPathString).annotate({\n        description: \"Environment-native runtime workspace roots. Omitted defaults to `cwd`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2ThreadStartResponse = {\n  readonly approvalPolicy: V2ThreadStartResponse__AskForApproval;\n  readonly approvalsReviewer: \"user\" | \"auto_review\" | \"guardian_subagent\";\n  readonly cwd: V2ThreadStartResponse__AbsolutePathBuf;\n  readonly instructionSources?: ReadonlyArray<V2ThreadStartResponse__LegacyAppPathString>;\n  readonly model: string;\n  readonly modelProvider: string;\n  readonly reasoningEffort?: V2ThreadStartResponse__ReasoningEffort | null;\n  readonly sandbox:\n    | { readonly type: \"dangerFullAccess\" }\n    | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n    | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n    | {\n        readonly excludeSlashTmp?: boolean;\n        readonly excludeTmpdirEnvVar?: boolean;\n        readonly networkAccess?: boolean;\n        readonly type: \"workspaceWrite\";\n        readonly writableRoots?: ReadonlyArray<V2ThreadStartResponse__AbsolutePathBuf>;\n      };\n  readonly serviceTier?: string | null;\n  readonly thread: V2ThreadStartResponse__Thread;\n};\nexport const V2ThreadStartResponse = Schema.Struct({\n  approvalPolicy: V2ThreadStartResponse__AskForApproval,\n  approvalsReviewer: Schema.Literals([\"user\", \"auto_review\", \"guardian_subagent\"]).annotate({\n    description:\n      \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n  }),\n  cwd: V2ThreadStartResponse__AbsolutePathBuf,\n  instructionSources: Schema.optionalKey(\n    Schema.Array(V2ThreadStartResponse__LegacyAppPathString).annotate({\n      description:\n        \"Environment-native paths to instruction source files currently loaded for this thread.\",\n      default: [],\n    }),\n  ),\n  model: Schema.String,\n  modelProvider: Schema.String,\n  reasoningEffort: Schema.optionalKey(\n    Schema.Union([V2ThreadStartResponse__ReasoningEffort, Schema.Null]),\n  ),\n  sandbox: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"dangerFullAccess\").annotate({\n          title: \"DangerFullAccessSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n      }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n      Schema.Struct({\n        networkAccess: Schema.optionalKey(\n          Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n        ),\n        type: Schema.Literal(\"externalSandbox\").annotate({\n          title: \"ExternalSandboxSandboxPolicyType\",\n        }),\n      }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n      Schema.Struct({\n        excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n        type: Schema.Literal(\"workspaceWrite\").annotate({\n          title: \"WorkspaceWriteSandboxPolicyType\",\n        }),\n        writableRoots: Schema.optionalKey(\n          Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }),\n        ),\n      }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Legacy sandbox policy retained for compatibility. Experimental clients should prefer `activePermissionProfile` for profile provenance.\",\n  }),\n  serviceTier: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  thread: V2ThreadStartResponse__Thread,\n}).annotate({ title: \"ThreadStartResponse\" });\n\nexport type V2ThreadStartResponse__ActivePermissionProfile = {\n  readonly extends?: string | null;\n  readonly id: string;\n};\nexport const V2ThreadStartResponse__ActivePermissionProfile = Schema.Struct({\n  extends: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Parent profile identifier from the selected permissions profile's `extends` setting, when present.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({\n    description:\n      \"Identifier from `default_permissions` or the implicit built-in default, such as `:workspace` or a user-defined `[permissions.<id>]` profile.\",\n  }),\n});\n\nexport type V2ThreadStartResponse__ApprovalsReviewer = \"user\" | \"auto_review\" | \"guardian_subagent\";\nexport const V2ThreadStartResponse__ApprovalsReviewer = Schema.Literals([\n  \"user\",\n  \"auto_review\",\n  \"guardian_subagent\",\n]).annotate({\n  description:\n    \"Configures who approval requests are routed to for review. Examples include sandbox escapes, blocked network access, MCP approval prompts, and ARC escalations. Defaults to `user`. `auto_review` uses a carefully prompted subagent to gather relevant context and apply a risk-based decision framework before approving or denying the request. The legacy value `guardian_subagent` is accepted for compatibility.\",\n});\n\nexport type V2ThreadStartResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadStartResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadStartResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadStartResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadStartResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadStartResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadStartResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadStartResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadStartResponse__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2ThreadStartResponse__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2ThreadStartResponse__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2ThreadStartResponse__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2ThreadStartResponse__SandboxPolicy =\n  | { readonly type: \"dangerFullAccess\" }\n  | { readonly networkAccess?: boolean; readonly type: \"readOnly\" }\n  | { readonly networkAccess?: \"restricted\" | \"enabled\"; readonly type: \"externalSandbox\" }\n  | {\n      readonly excludeSlashTmp?: boolean;\n      readonly excludeTmpdirEnvVar?: boolean;\n      readonly networkAccess?: boolean;\n      readonly type: \"workspaceWrite\";\n      readonly writableRoots?: ReadonlyArray<V2ThreadStartResponse__AbsolutePathBuf>;\n    };\nexport const V2ThreadStartResponse__SandboxPolicy = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"dangerFullAccess\").annotate({\n        title: \"DangerFullAccessSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"DangerFullAccessSandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"readOnly\").annotate({ title: \"ReadOnlySandboxPolicyType\" }),\n    }).annotate({ title: \"ReadOnlySandboxPolicy\" }),\n    Schema.Struct({\n      networkAccess: Schema.optionalKey(\n        Schema.Literals([\"restricted\", \"enabled\"]).annotate({ default: \"restricted\" }),\n      ),\n      type: Schema.Literal(\"externalSandbox\").annotate({\n        title: \"ExternalSandboxSandboxPolicyType\",\n      }),\n    }).annotate({ title: \"ExternalSandboxSandboxPolicy\" }),\n    Schema.Struct({\n      excludeSlashTmp: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      excludeTmpdirEnvVar: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      networkAccess: Schema.optionalKey(Schema.Boolean.annotate({ default: false })),\n      type: Schema.Literal(\"workspaceWrite\").annotate({ title: \"WorkspaceWriteSandboxPolicyType\" }),\n      writableRoots: Schema.optionalKey(\n        Schema.Array(V2ThreadStartResponse__AbsolutePathBuf).annotate({ default: [] }),\n      ),\n    }).annotate({ title: \"WorkspaceWriteSandboxPolicy\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadStartResponse__SubAgentSource };\nexport const V2ThreadStartResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadStartResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__ThreadExtra = {};\nexport const V2ThreadStartResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadStartResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadStartResponse__ThreadHistoryMode = Schema.Literals([\"legacy\", \"paginated\"]);\n\nexport type V2ThreadStartResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadStartResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadStartResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadStartResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadStartResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadStartResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadStatusChangedNotification = {\n  readonly status: V2ThreadStatusChangedNotification__ThreadStatus;\n  readonly threadId: string;\n};\nexport const V2ThreadStatusChangedNotification = Schema.Struct({\n  status: V2ThreadStatusChangedNotification__ThreadStatus,\n  threadId: Schema.String,\n}).annotate({ title: \"ThreadStatusChangedNotification\" });\n\nexport type V2ThreadTokenUsageUpdatedNotification = {\n  readonly threadId: string;\n  readonly tokenUsage: V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage;\n  readonly turnId: string;\n};\nexport const V2ThreadTokenUsageUpdatedNotification = Schema.Struct({\n  threadId: Schema.String,\n  tokenUsage: V2ThreadTokenUsageUpdatedNotification__ThreadTokenUsage,\n  turnId: Schema.String,\n}).annotate({ title: \"ThreadTokenUsageUpdatedNotification\" });\n\nexport type V2ThreadUnarchivedNotification = { readonly threadId: string };\nexport const V2ThreadUnarchivedNotification = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadUnarchivedNotification\",\n});\n\nexport type V2ThreadUnarchiveParams = { readonly threadId: string };\nexport const V2ThreadUnarchiveParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadUnarchiveParams\",\n});\n\nexport type V2ThreadUnarchiveResponse = { readonly thread: V2ThreadUnarchiveResponse__Thread };\nexport const V2ThreadUnarchiveResponse = Schema.Struct({\n  thread: V2ThreadUnarchiveResponse__Thread,\n}).annotate({ title: \"ThreadUnarchiveResponse\" });\n\nexport type V2ThreadUnarchiveResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2ThreadUnarchiveResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2ThreadUnarchiveResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2ThreadUnarchiveResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2ThreadUnarchiveResponse__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2ThreadUnarchiveResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2ThreadUnarchiveResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2ThreadUnarchiveResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2ThreadUnarchiveResponse__SessionSource =\n  | \"cli\"\n  | \"vscode\"\n  | \"exec\"\n  | \"appServer\"\n  | \"unknown\"\n  | { readonly custom: string }\n  | { readonly subAgent: V2ThreadUnarchiveResponse__SubAgentSource };\nexport const V2ThreadUnarchiveResponse__SessionSource = Schema.Union(\n  [\n    Schema.Literals([\"cli\", \"vscode\", \"exec\", \"appServer\", \"unknown\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomSessionSource\" }),\n    Schema.Struct({ subAgent: V2ThreadUnarchiveResponse__SubAgentSource }).annotate({\n      title: \"SubAgentSessionSource\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__ThreadExtra = {};\nexport const V2ThreadUnarchiveResponse__ThreadExtra = Schema.Struct({}).annotate({\n  description: \"Extra app-server data for a thread.\",\n});\n\nexport type V2ThreadUnarchiveResponse__ThreadHistoryMode = \"legacy\" | \"paginated\";\nexport const V2ThreadUnarchiveResponse__ThreadHistoryMode = Schema.Literals([\n  \"legacy\",\n  \"paginated\",\n]);\n\nexport type V2ThreadUnarchiveResponse__ThreadStatus =\n  | { readonly type: \"notLoaded\" }\n  | { readonly type: \"idle\" }\n  | { readonly type: \"systemError\" }\n  | {\n      readonly activeFlags: ReadonlyArray<V2ThreadUnarchiveResponse__ThreadActiveFlag>;\n      readonly type: \"active\";\n    };\nexport const V2ThreadUnarchiveResponse__ThreadStatus = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"notLoaded\").annotate({ title: \"NotLoadedThreadStatusType\" }),\n    }).annotate({ title: \"NotLoadedThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"idle\").annotate({ title: \"IdleThreadStatusType\" }),\n    }).annotate({ title: \"IdleThreadStatus\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"systemError\").annotate({ title: \"SystemErrorThreadStatusType\" }),\n    }).annotate({ title: \"SystemErrorThreadStatus\" }),\n    Schema.Struct({\n      activeFlags: Schema.Array(V2ThreadUnarchiveResponse__ThreadActiveFlag),\n      type: Schema.Literal(\"active\").annotate({ title: \"ActiveThreadStatusType\" }),\n    }).annotate({ title: \"ActiveThreadStatus\" }),\n  ],\n  { mode: \"oneOf\" },\n);\n\nexport type V2ThreadUnarchiveResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2ThreadUnarchiveResponse__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2ThreadUnsubscribeParams = { readonly threadId: string };\nexport const V2ThreadUnsubscribeParams = Schema.Struct({ threadId: Schema.String }).annotate({\n  title: \"ThreadUnsubscribeParams\",\n});\n\nexport type V2ThreadUnsubscribeResponse = {\n  readonly status: V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus;\n};\nexport const V2ThreadUnsubscribeResponse = Schema.Struct({\n  status: V2ThreadUnsubscribeResponse__ThreadUnsubscribeStatus,\n}).annotate({ title: \"ThreadUnsubscribeResponse\" });\n\nexport type V2TurnCompletedNotification = {\n  readonly threadId: string;\n  readonly turn: V2TurnCompletedNotification__Turn;\n};\nexport const V2TurnCompletedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turn: V2TurnCompletedNotification__Turn,\n}).annotate({ title: \"TurnCompletedNotification\" });\n\nexport type V2TurnCompletedNotification__ByteRange = {\n  readonly end: number;\n  readonly start: number;\n};\nexport const V2TurnCompletedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnCompletedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2TurnCompletedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2TurnCompletedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2TurnCompletedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnCompletedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2TurnCompletedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2TurnCompletedNotification__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2TurnCompletedNotification__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2TurnDiffUpdatedNotification = {\n  readonly diff: string;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2TurnDiffUpdatedNotification = Schema.Struct({\n  diff: Schema.String,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({\n  title: \"TurnDiffUpdatedNotification\",\n  description:\n    \"Notification that the turn-level unified diff has changed. Contains the latest aggregated diff across all file changes in the turn.\",\n});\n\nexport type V2TurnInterruptParams = { readonly threadId: string; readonly turnId: string };\nexport const V2TurnInterruptParams = Schema.Struct({\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"TurnInterruptParams\" });\n\nexport type V2TurnInterruptResponse = {};\nexport const V2TurnInterruptResponse = Schema.Struct({}).annotate({\n  title: \"TurnInterruptResponse\",\n});\n\nexport type V2TurnModerationMetadataNotification = {\n  readonly metadata: unknown;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2TurnModerationMetadataNotification = Schema.Struct({\n  metadata: Schema.Unknown,\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"TurnModerationMetadataNotification\" });\n\nexport type V2TurnPlanUpdatedNotification = {\n  readonly explanation?: string | null;\n  readonly plan: ReadonlyArray<V2TurnPlanUpdatedNotification__TurnPlanStep>;\n  readonly threadId: string;\n  readonly turnId: string;\n};\nexport const V2TurnPlanUpdatedNotification = Schema.Struct({\n  explanation: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  plan: Schema.Array(V2TurnPlanUpdatedNotification__TurnPlanStep),\n  threadId: Schema.String,\n  turnId: Schema.String,\n}).annotate({ title: \"TurnPlanUpdatedNotification\" });\n\nexport type V2TurnStartedNotification = {\n  readonly threadId: string;\n  readonly turn: V2TurnStartedNotification__Turn;\n};\nexport const V2TurnStartedNotification = Schema.Struct({\n  threadId: Schema.String,\n  turn: V2TurnStartedNotification__Turn,\n}).annotate({ title: \"TurnStartedNotification\" });\n\nexport type V2TurnStartedNotification__ByteRange = { readonly end: number; readonly start: number };\nexport const V2TurnStartedNotification__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnStartedNotification__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2TurnStartedNotification__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2TurnStartedNotification__CollabAgentToolCallStatus =\n  | \"inProgress\"\n  | \"completed\"\n  | \"failed\";\nexport const V2TurnStartedNotification__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartedNotification__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2TurnStartedNotification__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2TurnStartedNotification__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2TurnStartedNotification__TurnItemsView = Schema.Literals([\n  \"notLoaded\",\n  \"summary\",\n  \"full\",\n]);\n\nexport type V2TurnStartParams = {\n  readonly approvalPolicy?: V2TurnStartParams__AskForApproval | null;\n  readonly approvalsReviewer?: V2TurnStartParams__ApprovalsReviewer | null;\n  readonly clientUserMessageId?: string | null;\n  readonly cwd?: string | null;\n  readonly effort?: V2TurnStartParams__ReasoningEffort | null;\n  readonly input: ReadonlyArray<V2TurnStartParams__UserInput>;\n  readonly model?: string | null;\n  readonly outputSchema?: unknown;\n  readonly personality?: V2TurnStartParams__Personality | null;\n  readonly sandboxPolicy?: V2TurnStartParams__SandboxPolicy | null;\n  readonly serviceTier?: string | null;\n  readonly summary?: V2TurnStartParams__ReasoningSummary | null;\n  readonly threadId: string;\n};\nexport const V2TurnStartParams = Schema.Struct({\n  approvalPolicy: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__AskForApproval, Schema.Null]).annotate({\n      description: \"Override the approval policy for this turn and subsequent turns.\",\n    }),\n  ),\n  approvalsReviewer: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__ApprovalsReviewer, Schema.Null]).annotate({\n      description:\n        \"Override where approval requests are routed for review on this turn and subsequent turns.\",\n    }),\n  ),\n  clientUserMessageId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the working directory for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  effort: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__ReasoningEffort, Schema.Null]).annotate({\n      description: \"Override the reasoning effort for this turn and subsequent turns.\",\n    }),\n  ),\n  input: Schema.Array(V2TurnStartParams__UserInput),\n  model: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the model for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outputSchema: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description:\n        \"Optional JSON Schema used to constrain the final assistant message for this turn.\",\n    }),\n  ),\n  personality: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__Personality, Schema.Null]).annotate({\n      description: \"Override the personality for this turn and subsequent turns.\",\n    }),\n  ),\n  sandboxPolicy: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__SandboxPolicy, Schema.Null]).annotate({\n      description: \"Override the sandbox policy for this turn and subsequent turns.\",\n    }),\n  ),\n  serviceTier: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Override the service tier for this turn and subsequent turns.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  summary: Schema.optionalKey(\n    Schema.Union([V2TurnStartParams__ReasoningSummary, Schema.Null]).annotate({\n      description: \"Override the reasoning summary for this turn and subsequent turns.\",\n    }),\n  ),\n  threadId: Schema.String,\n}).annotate({ title: \"TurnStartParams\" });\n\nexport type V2TurnStartParams__AdditionalContextEntry = {\n  readonly kind: V2TurnStartParams__AdditionalContextKind;\n  readonly value: string;\n};\nexport const V2TurnStartParams__AdditionalContextEntry = Schema.Struct({\n  kind: V2TurnStartParams__AdditionalContextKind,\n  value: Schema.String,\n});\n\nexport type V2TurnStartParams__ByteRange = { readonly end: number; readonly start: number };\nexport const V2TurnStartParams__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnStartParams__CollaborationMode = {\n  readonly mode: V2TurnStartParams__ModeKind;\n  readonly settings: V2TurnStartParams__Settings;\n};\nexport const V2TurnStartParams__CollaborationMode = Schema.Struct({\n  mode: V2TurnStartParams__ModeKind,\n  settings: V2TurnStartParams__Settings,\n}).annotate({ description: \"Collaboration mode for a Codex session.\" });\n\nexport type V2TurnStartParams__MultiAgentMode =\n  | \"explicitRequestOnly\"\n  | \"proactive\"\n  | { readonly custom: string };\nexport const V2TurnStartParams__MultiAgentMode = Schema.Union(\n  [\n    Schema.Literals([\"explicitRequestOnly\", \"proactive\"]),\n    Schema.Struct({ custom: Schema.String }).annotate({ title: \"CustomMultiAgentMode\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Controls the effective multi-agent delegation instructions for a turn. `custom` means the configured mode hint defines the policy instead of a built-in policy.\",\n});\n\nexport type V2TurnStartParams__NetworkAccess = \"restricted\" | \"enabled\";\nexport const V2TurnStartParams__NetworkAccess = Schema.Literals([\"restricted\", \"enabled\"]);\n\nexport type V2TurnStartParams__TurnEnvironmentParams = {\n  readonly cwd: V2TurnStartParams__LegacyAppPathString;\n  readonly environmentId: string;\n  readonly runtimeWorkspaceRoots?: ReadonlyArray<V2TurnStartParams__LegacyAppPathString> | null;\n};\nexport const V2TurnStartParams__TurnEnvironmentParams = Schema.Struct({\n  cwd: V2TurnStartParams__LegacyAppPathString,\n  environmentId: Schema.String,\n  runtimeWorkspaceRoots: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(V2TurnStartParams__LegacyAppPathString).annotate({\n        description: \"Environment-native runtime workspace roots. Omitted defaults to `cwd`.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type V2TurnStartResponse = { readonly turn: V2TurnStartResponse__Turn };\nexport const V2TurnStartResponse = Schema.Struct({ turn: V2TurnStartResponse__Turn }).annotate({\n  title: \"TurnStartResponse\",\n});\n\nexport type V2TurnStartResponse__ByteRange = { readonly end: number; readonly start: number };\nexport const V2TurnStartResponse__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnStartResponse__CollabAgentTool =\n  | \"spawnAgent\"\n  | \"sendInput\"\n  | \"resumeAgent\"\n  | \"wait\"\n  | \"closeAgent\";\nexport const V2TurnStartResponse__CollabAgentTool = Schema.Literals([\n  \"spawnAgent\",\n  \"sendInput\",\n  \"resumeAgent\",\n  \"wait\",\n  \"closeAgent\",\n]);\n\nexport type V2TurnStartResponse__CollabAgentToolCallStatus = \"inProgress\" | \"completed\" | \"failed\";\nexport const V2TurnStartResponse__CollabAgentToolCallStatus = Schema.Literals([\n  \"inProgress\",\n  \"completed\",\n  \"failed\",\n]);\n\nexport type V2TurnStartResponse__CommandExecutionSource =\n  | \"agent\"\n  | \"userShell\"\n  | \"unifiedExecStartup\"\n  | \"unifiedExecInteraction\";\nexport const V2TurnStartResponse__CommandExecutionSource = Schema.Literals([\n  \"agent\",\n  \"userShell\",\n  \"unifiedExecStartup\",\n  \"unifiedExecInteraction\",\n]);\n\nexport type V2TurnStartResponse__TurnItemsView = \"notLoaded\" | \"summary\" | \"full\";\nexport const V2TurnStartResponse__TurnItemsView = Schema.Literals([\"notLoaded\", \"summary\", \"full\"]);\n\nexport type V2TurnSteerParams = {\n  readonly clientUserMessageId?: string | null;\n  readonly expectedTurnId: string;\n  readonly input: ReadonlyArray<V2TurnSteerParams__UserInput>;\n  readonly threadId: string;\n};\nexport const V2TurnSteerParams = Schema.Struct({\n  clientUserMessageId: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  expectedTurnId: Schema.String.annotate({\n    description:\n      \"Required active turn id precondition. The request fails when it does not match the currently active turn.\",\n  }),\n  input: Schema.Array(V2TurnSteerParams__UserInput),\n  threadId: Schema.String,\n}).annotate({ title: \"TurnSteerParams\" });\n\nexport type V2TurnSteerParams__AdditionalContextEntry = {\n  readonly kind: V2TurnSteerParams__AdditionalContextKind;\n  readonly value: string;\n};\nexport const V2TurnSteerParams__AdditionalContextEntry = Schema.Struct({\n  kind: V2TurnSteerParams__AdditionalContextKind,\n  value: Schema.String,\n});\n\nexport type V2TurnSteerParams__ByteRange = { readonly end: number; readonly start: number };\nexport const V2TurnSteerParams__ByteRange = Schema.Struct({\n  end: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  start: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n});\n\nexport type V2TurnSteerResponse = { readonly turnId: string };\nexport const V2TurnSteerResponse = Schema.Struct({ turnId: Schema.String }).annotate({\n  title: \"TurnSteerResponse\",\n});\n\nexport type V2WarningNotification = { readonly message: string; readonly threadId?: string | null };\nexport const V2WarningNotification = Schema.Struct({\n  message: Schema.String.annotate({ description: \"Concise warning message for the user.\" }),\n  threadId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional thread target when the warning applies to a specific thread.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ title: \"WarningNotification\" });\n\nexport type V2WindowsSandboxReadinessResponse = {\n  readonly status: V2WindowsSandboxReadinessResponse__WindowsSandboxReadiness;\n};\nexport const V2WindowsSandboxReadinessResponse = Schema.Struct({\n  status: V2WindowsSandboxReadinessResponse__WindowsSandboxReadiness,\n}).annotate({ title: \"WindowsSandboxReadinessResponse\" });\n\nexport type V2WindowsSandboxSetupCompletedNotification = {\n  readonly error?: string | null;\n  readonly mode: V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode;\n  readonly success: boolean;\n};\nexport const V2WindowsSandboxSetupCompletedNotification = Schema.Struct({\n  error: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  mode: V2WindowsSandboxSetupCompletedNotification__WindowsSandboxSetupMode,\n  success: Schema.Boolean,\n}).annotate({ title: \"WindowsSandboxSetupCompletedNotification\" });\n\nexport type V2WindowsSandboxSetupStartParams = {\n  readonly cwd?: V2WindowsSandboxSetupStartParams__AbsolutePathBuf | null;\n  readonly mode: V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode;\n};\nexport const V2WindowsSandboxSetupStartParams = Schema.Struct({\n  cwd: Schema.optionalKey(\n    Schema.Union([V2WindowsSandboxSetupStartParams__AbsolutePathBuf, Schema.Null]),\n  ),\n  mode: V2WindowsSandboxSetupStartParams__WindowsSandboxSetupMode,\n}).annotate({ title: \"WindowsSandboxSetupStartParams\" });\n\nexport type V2WindowsSandboxSetupStartResponse = { readonly started: boolean };\nexport const V2WindowsSandboxSetupStartResponse = Schema.Struct({\n  started: Schema.Boolean,\n}).annotate({ title: \"WindowsSandboxSetupStartResponse\" });\n\nexport type V2WindowsWorldWritableWarningNotification = {\n  readonly extraCount: number;\n  readonly failedScan: boolean;\n  readonly samplePaths: ReadonlyArray<string>;\n};\nexport const V2WindowsWorldWritableWarningNotification = Schema.Struct({\n  extraCount: Schema.Number.annotate({ format: \"uint\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  failedScan: Schema.Boolean,\n  samplePaths: Schema.Array(Schema.String),\n}).annotate({ title: \"WindowsWorldWritableWarningNotification\" });\n","// This file is generated by the effect-codex-app-server package. Do not edit manually.\n// Upstream protocol ref: 678157acaa819d5510adfe359abb5d0392cfe461\n\nimport * as CodexSchema from \"./schema.gen.ts\";\n\nexport const CLIENT_REQUEST_METHODS = {\n  initialize: \"initialize\",\n  \"thread/start\": \"thread/start\",\n  \"thread/resume\": \"thread/resume\",\n  \"thread/fork\": \"thread/fork\",\n  \"thread/archive\": \"thread/archive\",\n  \"thread/delete\": \"thread/delete\",\n  \"thread/unsubscribe\": \"thread/unsubscribe\",\n  \"thread/name/set\": \"thread/name/set\",\n  \"thread/goal/set\": \"thread/goal/set\",\n  \"thread/goal/get\": \"thread/goal/get\",\n  \"thread/goal/clear\": \"thread/goal/clear\",\n  \"thread/metadata/update\": \"thread/metadata/update\",\n  \"thread/unarchive\": \"thread/unarchive\",\n  \"thread/compact/start\": \"thread/compact/start\",\n  \"thread/shellCommand\": \"thread/shellCommand\",\n  \"thread/approveGuardianDeniedAction\": \"thread/approveGuardianDeniedAction\",\n  \"thread/rollback\": \"thread/rollback\",\n  \"thread/list\": \"thread/list\",\n  \"thread/loaded/list\": \"thread/loaded/list\",\n  \"thread/read\": \"thread/read\",\n  \"thread/inject_items\": \"thread/inject_items\",\n  \"skills/list\": \"skills/list\",\n  \"skills/extraRoots/set\": \"skills/extraRoots/set\",\n  \"hooks/list\": \"hooks/list\",\n  \"marketplace/add\": \"marketplace/add\",\n  \"marketplace/remove\": \"marketplace/remove\",\n  \"marketplace/upgrade\": \"marketplace/upgrade\",\n  \"plugin/list\": \"plugin/list\",\n  \"plugin/installed\": \"plugin/installed\",\n  \"plugin/read\": \"plugin/read\",\n  \"plugin/skill/read\": \"plugin/skill/read\",\n  \"plugin/share/save\": \"plugin/share/save\",\n  \"plugin/share/updateTargets\": \"plugin/share/updateTargets\",\n  \"plugin/share/list\": \"plugin/share/list\",\n  \"plugin/share/checkout\": \"plugin/share/checkout\",\n  \"plugin/share/delete\": \"plugin/share/delete\",\n  \"app/read\": \"app/read\",\n  \"app/list\": \"app/list\",\n  \"app/installed\": \"app/installed\",\n  \"fs/readFile\": \"fs/readFile\",\n  \"fs/writeFile\": \"fs/writeFile\",\n  \"fs/createDirectory\": \"fs/createDirectory\",\n  \"fs/getMetadata\": \"fs/getMetadata\",\n  \"fs/readDirectory\": \"fs/readDirectory\",\n  \"fs/remove\": \"fs/remove\",\n  \"fs/copy\": \"fs/copy\",\n  \"fs/watch\": \"fs/watch\",\n  \"fs/unwatch\": \"fs/unwatch\",\n  \"skills/config/write\": \"skills/config/write\",\n  \"plugin/install\": \"plugin/install\",\n  \"plugin/uninstall\": \"plugin/uninstall\",\n  \"turn/start\": \"turn/start\",\n  \"turn/steer\": \"turn/steer\",\n  \"turn/interrupt\": \"turn/interrupt\",\n  \"review/start\": \"review/start\",\n  \"model/list\": \"model/list\",\n  \"modelProvider/capabilities/read\": \"modelProvider/capabilities/read\",\n  \"experimentalFeature/list\": \"experimentalFeature/list\",\n  \"permissionProfile/list\": \"permissionProfile/list\",\n  \"experimentalFeature/enablement/set\": \"experimentalFeature/enablement/set\",\n  \"mcpServer/oauth/login\": \"mcpServer/oauth/login\",\n  \"config/mcpServer/reload\": \"config/mcpServer/reload\",\n  \"mcpServerStatus/list\": \"mcpServerStatus/list\",\n  \"mcpServer/resource/read\": \"mcpServer/resource/read\",\n  \"mcpServer/tool/call\": \"mcpServer/tool/call\",\n  \"windowsSandbox/setupStart\": \"windowsSandbox/setupStart\",\n  \"windowsSandbox/readiness\": \"windowsSandbox/readiness\",\n  \"account/login/start\": \"account/login/start\",\n  \"account/login/cancel\": \"account/login/cancel\",\n  \"account/logout\": \"account/logout\",\n  \"account/rateLimits/read\": \"account/rateLimits/read\",\n  \"account/rateLimitResetCredit/consume\": \"account/rateLimitResetCredit/consume\",\n  \"account/usage/read\": \"account/usage/read\",\n  \"account/workspaceMessages/read\": \"account/workspaceMessages/read\",\n  \"account/sendAddCreditsNudgeEmail\": \"account/sendAddCreditsNudgeEmail\",\n  \"feedback/upload\": \"feedback/upload\",\n  \"command/exec\": \"command/exec\",\n  \"command/exec/write\": \"command/exec/write\",\n  \"command/exec/terminate\": \"command/exec/terminate\",\n  \"command/exec/resize\": \"command/exec/resize\",\n  \"config/read\": \"config/read\",\n  \"externalAgentConfig/detect\": \"externalAgentConfig/detect\",\n  \"externalAgentConfig/import\": \"externalAgentConfig/import\",\n  \"externalAgentConfig/import/readHistories\": \"externalAgentConfig/import/readHistories\",\n  \"config/value/write\": \"config/value/write\",\n  \"config/batchWrite\": \"config/batchWrite\",\n  \"configRequirements/read\": \"configRequirements/read\",\n  \"account/read\": \"account/read\",\n  getConversationSummary: \"getConversationSummary\",\n  gitDiffToRemote: \"gitDiffToRemote\",\n  getAuthStatus: \"getAuthStatus\",\n  fuzzyFileSearch: \"fuzzyFileSearch\",\n} as const;\n\nexport const CLIENT_NOTIFICATION_METHODS = {\n  initialized: \"initialized\",\n} as const;\n\nexport const SERVER_REQUEST_METHODS = {\n  \"item/commandExecution/requestApproval\": \"item/commandExecution/requestApproval\",\n  \"item/fileChange/requestApproval\": \"item/fileChange/requestApproval\",\n  \"item/tool/requestUserInput\": \"item/tool/requestUserInput\",\n  \"mcpServer/elicitation/request\": \"mcpServer/elicitation/request\",\n  \"item/permissions/requestApproval\": \"item/permissions/requestApproval\",\n  \"item/tool/call\": \"item/tool/call\",\n  \"account/chatgptAuthTokens/refresh\": \"account/chatgptAuthTokens/refresh\",\n  \"attestation/generate\": \"attestation/generate\",\n  applyPatchApproval: \"applyPatchApproval\",\n  execCommandApproval: \"execCommandApproval\",\n} as const;\n\nexport const SERVER_NOTIFICATION_METHODS = {\n  error: \"error\",\n  \"thread/started\": \"thread/started\",\n  \"thread/status/changed\": \"thread/status/changed\",\n  \"thread/archived\": \"thread/archived\",\n  \"thread/deleted\": \"thread/deleted\",\n  \"thread/unarchived\": \"thread/unarchived\",\n  \"thread/closed\": \"thread/closed\",\n  \"skills/changed\": \"skills/changed\",\n  \"thread/name/updated\": \"thread/name/updated\",\n  \"thread/goal/updated\": \"thread/goal/updated\",\n  \"thread/goal/cleared\": \"thread/goal/cleared\",\n  \"thread/environment/connected\": \"thread/environment/connected\",\n  \"thread/environment/disconnected\": \"thread/environment/disconnected\",\n  \"thread/settings/updated\": \"thread/settings/updated\",\n  \"thread/tokenUsage/updated\": \"thread/tokenUsage/updated\",\n  \"turn/started\": \"turn/started\",\n  \"hook/started\": \"hook/started\",\n  \"turn/completed\": \"turn/completed\",\n  \"hook/completed\": \"hook/completed\",\n  \"turn/diff/updated\": \"turn/diff/updated\",\n  \"turn/plan/updated\": \"turn/plan/updated\",\n  \"item/started\": \"item/started\",\n  \"item/autoApprovalReview/started\": \"item/autoApprovalReview/started\",\n  \"item/autoApprovalReview/completed\": \"item/autoApprovalReview/completed\",\n  \"item/completed\": \"item/completed\",\n  \"rawResponseItem/completed\": \"rawResponseItem/completed\",\n  \"rawResponse/completed\": \"rawResponse/completed\",\n  \"item/agentMessage/delta\": \"item/agentMessage/delta\",\n  \"item/plan/delta\": \"item/plan/delta\",\n  \"command/exec/outputDelta\": \"command/exec/outputDelta\",\n  \"process/outputDelta\": \"process/outputDelta\",\n  \"process/exited\": \"process/exited\",\n  \"item/commandExecution/outputDelta\": \"item/commandExecution/outputDelta\",\n  \"item/commandExecution/terminalInteraction\": \"item/commandExecution/terminalInteraction\",\n  \"item/fileChange/outputDelta\": \"item/fileChange/outputDelta\",\n  \"item/fileChange/patchUpdated\": \"item/fileChange/patchUpdated\",\n  \"serverRequest/resolved\": \"serverRequest/resolved\",\n  \"item/mcpToolCall/progress\": \"item/mcpToolCall/progress\",\n  \"mcpServer/oauthLogin/completed\": \"mcpServer/oauthLogin/completed\",\n  \"mcpServer/startupStatus/updated\": \"mcpServer/startupStatus/updated\",\n  \"account/updated\": \"account/updated\",\n  \"account/rateLimits/updated\": \"account/rateLimits/updated\",\n  \"app/list/updated\": \"app/list/updated\",\n  \"remoteControl/status/changed\": \"remoteControl/status/changed\",\n  \"externalAgentConfig/import/progress\": \"externalAgentConfig/import/progress\",\n  \"externalAgentConfig/import/completed\": \"externalAgentConfig/import/completed\",\n  \"fs/changed\": \"fs/changed\",\n  \"item/reasoning/summaryTextDelta\": \"item/reasoning/summaryTextDelta\",\n  \"item/reasoning/summaryPartAdded\": \"item/reasoning/summaryPartAdded\",\n  \"item/reasoning/textDelta\": \"item/reasoning/textDelta\",\n  \"thread/compacted\": \"thread/compacted\",\n  \"model/rerouted\": \"model/rerouted\",\n  \"model/verification\": \"model/verification\",\n  \"turn/moderationMetadata\": \"turn/moderationMetadata\",\n  \"model/safetyBuffering/updated\": \"model/safetyBuffering/updated\",\n  warning: \"warning\",\n  guardianWarning: \"guardianWarning\",\n  deprecationNotice: \"deprecationNotice\",\n  configWarning: \"configWarning\",\n  \"fuzzyFileSearch/sessionUpdated\": \"fuzzyFileSearch/sessionUpdated\",\n  \"fuzzyFileSearch/sessionCompleted\": \"fuzzyFileSearch/sessionCompleted\",\n  \"thread/realtime/started\": \"thread/realtime/started\",\n  \"thread/realtime/itemAdded\": \"thread/realtime/itemAdded\",\n  \"thread/realtime/transcript/delta\": \"thread/realtime/transcript/delta\",\n  \"thread/realtime/transcript/done\": \"thread/realtime/transcript/done\",\n  \"thread/realtime/outputAudio/delta\": \"thread/realtime/outputAudio/delta\",\n  \"thread/realtime/sdp\": \"thread/realtime/sdp\",\n  \"thread/realtime/error\": \"thread/realtime/error\",\n  \"thread/realtime/closed\": \"thread/realtime/closed\",\n  \"windows/worldWritableWarning\": \"windows/worldWritableWarning\",\n  \"windowsSandbox/setupCompleted\": \"windowsSandbox/setupCompleted\",\n  \"account/login/completed\": \"account/login/completed\",\n} as const;\n\nexport type ClientRequestMethod = keyof typeof CLIENT_REQUEST_METHODS;\nexport type ClientNotificationMethod = keyof typeof CLIENT_NOTIFICATION_METHODS;\nexport type ServerRequestMethod = keyof typeof SERVER_REQUEST_METHODS;\nexport type ServerNotificationMethod = keyof typeof SERVER_NOTIFICATION_METHODS;\n\nexport interface ClientRequestParamsByMethod {\n  readonly initialize: CodexSchema.V1InitializeParams;\n  readonly \"thread/start\": CodexSchema.V2ThreadStartParams;\n  readonly \"thread/resume\": CodexSchema.V2ThreadResumeParams;\n  readonly \"thread/fork\": CodexSchema.V2ThreadForkParams;\n  readonly \"thread/archive\": CodexSchema.V2ThreadArchiveParams;\n  readonly \"thread/delete\": CodexSchema.V2ThreadDeleteParams;\n  readonly \"thread/unsubscribe\": CodexSchema.V2ThreadUnsubscribeParams;\n  readonly \"thread/name/set\": CodexSchema.V2ThreadSetNameParams;\n  readonly \"thread/goal/set\": CodexSchema.V2ThreadGoalSetParams;\n  readonly \"thread/goal/get\": CodexSchema.V2ThreadGoalGetParams;\n  readonly \"thread/goal/clear\": CodexSchema.V2ThreadGoalClearParams;\n  readonly \"thread/metadata/update\": CodexSchema.V2ThreadMetadataUpdateParams;\n  readonly \"thread/unarchive\": CodexSchema.V2ThreadUnarchiveParams;\n  readonly \"thread/compact/start\": CodexSchema.V2ThreadCompactStartParams;\n  readonly \"thread/shellCommand\": CodexSchema.V2ThreadShellCommandParams;\n  readonly \"thread/approveGuardianDeniedAction\": CodexSchema.V2ThreadApproveGuardianDeniedActionParams;\n  readonly \"thread/rollback\": CodexSchema.V2ThreadRollbackParams;\n  readonly \"thread/list\": CodexSchema.V2ThreadListParams;\n  readonly \"thread/loaded/list\": CodexSchema.V2ThreadLoadedListParams;\n  readonly \"thread/read\": CodexSchema.V2ThreadReadParams;\n  readonly \"thread/inject_items\": CodexSchema.V2ThreadInjectItemsParams;\n  readonly \"skills/list\": CodexSchema.V2SkillsListParams;\n  readonly \"skills/extraRoots/set\": CodexSchema.V2SkillsExtraRootsSetParams;\n  readonly \"hooks/list\": CodexSchema.V2HooksListParams;\n  readonly \"marketplace/add\": CodexSchema.V2MarketplaceAddParams;\n  readonly \"marketplace/remove\": CodexSchema.V2MarketplaceRemoveParams;\n  readonly \"marketplace/upgrade\": CodexSchema.V2MarketplaceUpgradeParams;\n  readonly \"plugin/list\": CodexSchema.V2PluginListParams;\n  readonly \"plugin/installed\": CodexSchema.V2PluginInstalledParams;\n  readonly \"plugin/read\": CodexSchema.V2PluginReadParams;\n  readonly \"plugin/skill/read\": CodexSchema.V2PluginSkillReadParams;\n  readonly \"plugin/share/save\": CodexSchema.V2PluginShareSaveParams;\n  readonly \"plugin/share/updateTargets\": CodexSchema.V2PluginShareUpdateTargetsParams;\n  readonly \"plugin/share/list\": CodexSchema.V2PluginShareListParams;\n  readonly \"plugin/share/checkout\": CodexSchema.V2PluginShareCheckoutParams;\n  readonly \"plugin/share/delete\": CodexSchema.V2PluginShareDeleteParams;\n  readonly \"app/read\": CodexSchema.V2AppsReadParams;\n  readonly \"app/list\": CodexSchema.V2AppsListParams;\n  readonly \"app/installed\": CodexSchema.V2AppsInstalledParams;\n  readonly \"fs/readFile\": CodexSchema.V2FsReadFileParams;\n  readonly \"fs/writeFile\": CodexSchema.V2FsWriteFileParams;\n  readonly \"fs/createDirectory\": CodexSchema.V2FsCreateDirectoryParams;\n  readonly \"fs/getMetadata\": CodexSchema.V2FsGetMetadataParams;\n  readonly \"fs/readDirectory\": CodexSchema.V2FsReadDirectoryParams;\n  readonly \"fs/remove\": CodexSchema.V2FsRemoveParams;\n  readonly \"fs/copy\": CodexSchema.V2FsCopyParams;\n  readonly \"fs/watch\": CodexSchema.V2FsWatchParams;\n  readonly \"fs/unwatch\": CodexSchema.V2FsUnwatchParams;\n  readonly \"skills/config/write\": CodexSchema.V2SkillsConfigWriteParams;\n  readonly \"plugin/install\": CodexSchema.V2PluginInstallParams;\n  readonly \"plugin/uninstall\": CodexSchema.V2PluginUninstallParams;\n  readonly \"turn/start\": CodexSchema.V2TurnStartParams;\n  readonly \"turn/steer\": CodexSchema.V2TurnSteerParams;\n  readonly \"turn/interrupt\": CodexSchema.V2TurnInterruptParams;\n  readonly \"review/start\": CodexSchema.V2ReviewStartParams;\n  readonly \"model/list\": CodexSchema.V2ModelListParams;\n  readonly \"modelProvider/capabilities/read\": CodexSchema.V2ModelProviderCapabilitiesReadParams;\n  readonly \"experimentalFeature/list\": CodexSchema.V2ExperimentalFeatureListParams;\n  readonly \"permissionProfile/list\": CodexSchema.V2PermissionProfileListParams;\n  readonly \"experimentalFeature/enablement/set\": CodexSchema.V2ExperimentalFeatureEnablementSetParams;\n  readonly \"mcpServer/oauth/login\": CodexSchema.V2McpServerOauthLoginParams;\n  readonly \"config/mcpServer/reload\": undefined;\n  readonly \"mcpServerStatus/list\": CodexSchema.V2ListMcpServerStatusParams;\n  readonly \"mcpServer/resource/read\": CodexSchema.V2McpResourceReadParams;\n  readonly \"mcpServer/tool/call\": CodexSchema.V2McpServerToolCallParams;\n  readonly \"windowsSandbox/setupStart\": CodexSchema.V2WindowsSandboxSetupStartParams;\n  readonly \"windowsSandbox/readiness\": undefined;\n  readonly \"account/login/start\": CodexSchema.V2LoginAccountParams;\n  readonly \"account/login/cancel\": CodexSchema.V2CancelLoginAccountParams;\n  readonly \"account/logout\": undefined;\n  readonly \"account/rateLimits/read\": undefined;\n  readonly \"account/rateLimitResetCredit/consume\": CodexSchema.V2ConsumeAccountRateLimitResetCreditParams;\n  readonly \"account/usage/read\": undefined;\n  readonly \"account/workspaceMessages/read\": undefined;\n  readonly \"account/sendAddCreditsNudgeEmail\": CodexSchema.V2SendAddCreditsNudgeEmailParams;\n  readonly \"feedback/upload\": CodexSchema.V2FeedbackUploadParams;\n  readonly \"command/exec\": CodexSchema.V2CommandExecParams;\n  readonly \"command/exec/write\": CodexSchema.V2CommandExecWriteParams;\n  readonly \"command/exec/terminate\": CodexSchema.V2CommandExecTerminateParams;\n  readonly \"command/exec/resize\": CodexSchema.V2CommandExecResizeParams;\n  readonly \"config/read\": CodexSchema.V2ConfigReadParams;\n  readonly \"externalAgentConfig/detect\": CodexSchema.V2ExternalAgentConfigDetectParams;\n  readonly \"externalAgentConfig/import\": CodexSchema.V2ExternalAgentConfigImportParams;\n  readonly \"externalAgentConfig/import/readHistories\": undefined;\n  readonly \"config/value/write\": CodexSchema.V2ConfigValueWriteParams;\n  readonly \"config/batchWrite\": CodexSchema.V2ConfigBatchWriteParams;\n  readonly \"configRequirements/read\": undefined;\n  readonly \"account/read\": CodexSchema.V2GetAccountParams;\n  readonly getConversationSummary: CodexSchema.GetConversationSummaryParams;\n  readonly gitDiffToRemote: CodexSchema.GitDiffToRemoteParams;\n  readonly getAuthStatus: CodexSchema.GetAuthStatusParams;\n  readonly fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams;\n}\n\nexport interface ClientRequestResponsesByMethod {\n  readonly initialize: CodexSchema.V1InitializeResponse;\n  readonly \"thread/start\": CodexSchema.V2ThreadStartResponse;\n  readonly \"thread/resume\": CodexSchema.V2ThreadResumeResponse;\n  readonly \"thread/fork\": CodexSchema.V2ThreadForkResponse;\n  readonly \"thread/archive\": CodexSchema.V2ThreadArchiveResponse;\n  readonly \"thread/delete\": CodexSchema.V2ThreadDeleteResponse;\n  readonly \"thread/unsubscribe\": CodexSchema.V2ThreadUnsubscribeResponse;\n  readonly \"thread/name/set\": CodexSchema.V2ThreadSetNameResponse;\n  readonly \"thread/goal/set\": CodexSchema.V2ThreadGoalSetResponse;\n  readonly \"thread/goal/get\": CodexSchema.V2ThreadGoalGetResponse;\n  readonly \"thread/goal/clear\": CodexSchema.V2ThreadGoalClearResponse;\n  readonly \"thread/metadata/update\": CodexSchema.V2ThreadMetadataUpdateResponse;\n  readonly \"thread/unarchive\": CodexSchema.V2ThreadUnarchiveResponse;\n  readonly \"thread/compact/start\": CodexSchema.V2ThreadCompactStartResponse;\n  readonly \"thread/shellCommand\": CodexSchema.V2ThreadShellCommandResponse;\n  readonly \"thread/approveGuardianDeniedAction\": CodexSchema.V2ThreadApproveGuardianDeniedActionResponse;\n  readonly \"thread/rollback\": CodexSchema.V2ThreadRollbackResponse;\n  readonly \"thread/list\": CodexSchema.V2ThreadListResponse;\n  readonly \"thread/loaded/list\": CodexSchema.V2ThreadLoadedListResponse;\n  readonly \"thread/read\": CodexSchema.V2ThreadReadResponse;\n  readonly \"thread/inject_items\": CodexSchema.V2ThreadInjectItemsResponse;\n  readonly \"skills/list\": CodexSchema.V2SkillsListResponse;\n  readonly \"skills/extraRoots/set\": CodexSchema.V2SkillsExtraRootsSetResponse;\n  readonly \"hooks/list\": CodexSchema.V2HooksListResponse;\n  readonly \"marketplace/add\": CodexSchema.V2MarketplaceAddResponse;\n  readonly \"marketplace/remove\": CodexSchema.V2MarketplaceRemoveResponse;\n  readonly \"marketplace/upgrade\": CodexSchema.V2MarketplaceUpgradeResponse;\n  readonly \"plugin/list\": CodexSchema.V2PluginListResponse;\n  readonly \"plugin/installed\": CodexSchema.V2PluginInstalledResponse;\n  readonly \"plugin/read\": CodexSchema.V2PluginReadResponse;\n  readonly \"plugin/skill/read\": CodexSchema.V2PluginSkillReadResponse;\n  readonly \"plugin/share/save\": CodexSchema.V2PluginShareSaveResponse;\n  readonly \"plugin/share/updateTargets\": CodexSchema.V2PluginShareUpdateTargetsResponse;\n  readonly \"plugin/share/list\": CodexSchema.V2PluginShareListResponse;\n  readonly \"plugin/share/checkout\": CodexSchema.V2PluginShareCheckoutResponse;\n  readonly \"plugin/share/delete\": CodexSchema.V2PluginShareDeleteResponse;\n  readonly \"app/read\": CodexSchema.V2AppsReadResponse;\n  readonly \"app/list\": CodexSchema.V2AppsListResponse;\n  readonly \"app/installed\": CodexSchema.V2AppsInstalledResponse;\n  readonly \"fs/readFile\": CodexSchema.V2FsReadFileResponse;\n  readonly \"fs/writeFile\": CodexSchema.V2FsWriteFileResponse;\n  readonly \"fs/createDirectory\": CodexSchema.V2FsCreateDirectoryResponse;\n  readonly \"fs/getMetadata\": CodexSchema.V2FsGetMetadataResponse;\n  readonly \"fs/readDirectory\": CodexSchema.V2FsReadDirectoryResponse;\n  readonly \"fs/remove\": CodexSchema.V2FsRemoveResponse;\n  readonly \"fs/copy\": CodexSchema.V2FsCopyResponse;\n  readonly \"fs/watch\": CodexSchema.V2FsWatchResponse;\n  readonly \"fs/unwatch\": CodexSchema.V2FsUnwatchResponse;\n  readonly \"skills/config/write\": CodexSchema.V2SkillsConfigWriteResponse;\n  readonly \"plugin/install\": CodexSchema.V2PluginInstallResponse;\n  readonly \"plugin/uninstall\": CodexSchema.V2PluginUninstallResponse;\n  readonly \"turn/start\": CodexSchema.V2TurnStartResponse;\n  readonly \"turn/steer\": CodexSchema.V2TurnSteerResponse;\n  readonly \"turn/interrupt\": CodexSchema.V2TurnInterruptResponse;\n  readonly \"review/start\": CodexSchema.V2ReviewStartResponse;\n  readonly \"model/list\": CodexSchema.V2ModelListResponse;\n  readonly \"modelProvider/capabilities/read\": CodexSchema.V2ModelProviderCapabilitiesReadResponse;\n  readonly \"experimentalFeature/list\": CodexSchema.V2ExperimentalFeatureListResponse;\n  readonly \"permissionProfile/list\": CodexSchema.V2PermissionProfileListResponse;\n  readonly \"experimentalFeature/enablement/set\": CodexSchema.V2ExperimentalFeatureEnablementSetResponse;\n  readonly \"mcpServer/oauth/login\": CodexSchema.V2McpServerOauthLoginResponse;\n  readonly \"config/mcpServer/reload\": CodexSchema.V2McpServerRefreshResponse;\n  readonly \"mcpServerStatus/list\": CodexSchema.V2ListMcpServerStatusResponse;\n  readonly \"mcpServer/resource/read\": CodexSchema.V2McpResourceReadResponse;\n  readonly \"mcpServer/tool/call\": CodexSchema.V2McpServerToolCallResponse;\n  readonly \"windowsSandbox/setupStart\": CodexSchema.V2WindowsSandboxSetupStartResponse;\n  readonly \"windowsSandbox/readiness\": CodexSchema.V2WindowsSandboxReadinessResponse;\n  readonly \"account/login/start\": CodexSchema.V2LoginAccountResponse;\n  readonly \"account/login/cancel\": CodexSchema.V2CancelLoginAccountResponse;\n  readonly \"account/logout\": CodexSchema.V2LogoutAccountResponse;\n  readonly \"account/rateLimits/read\": CodexSchema.V2GetAccountRateLimitsResponse;\n  readonly \"account/rateLimitResetCredit/consume\": CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse;\n  readonly \"account/usage/read\": CodexSchema.V2GetAccountTokenUsageResponse;\n  readonly \"account/workspaceMessages/read\": CodexSchema.V2GetWorkspaceMessagesResponse;\n  readonly \"account/sendAddCreditsNudgeEmail\": CodexSchema.V2SendAddCreditsNudgeEmailResponse;\n  readonly \"feedback/upload\": CodexSchema.V2FeedbackUploadResponse;\n  readonly \"command/exec\": CodexSchema.V2CommandExecResponse;\n  readonly \"command/exec/write\": CodexSchema.V2CommandExecWriteResponse;\n  readonly \"command/exec/terminate\": CodexSchema.V2CommandExecTerminateResponse;\n  readonly \"command/exec/resize\": CodexSchema.V2CommandExecResizeResponse;\n  readonly \"config/read\": CodexSchema.V2ConfigReadResponse;\n  readonly \"externalAgentConfig/detect\": CodexSchema.V2ExternalAgentConfigDetectResponse;\n  readonly \"externalAgentConfig/import\": CodexSchema.V2ExternalAgentConfigImportResponse;\n  readonly \"externalAgentConfig/import/readHistories\": CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse;\n  readonly \"config/value/write\": CodexSchema.V2ConfigWriteResponse;\n  readonly \"config/batchWrite\": CodexSchema.V2ConfigWriteResponse;\n  readonly \"configRequirements/read\": CodexSchema.V2ConfigRequirementsReadResponse;\n  readonly \"account/read\": CodexSchema.V2GetAccountResponse;\n  readonly getConversationSummary: CodexSchema.GetConversationSummaryResponse;\n  readonly gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse;\n  readonly getAuthStatus: CodexSchema.GetAuthStatusResponse;\n  readonly fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse;\n}\n\nexport interface ClientNotificationParamsByMethod {\n  readonly initialized: undefined;\n}\n\nexport interface ServerRequestParamsByMethod {\n  readonly \"item/commandExecution/requestApproval\": CodexSchema.CommandExecutionRequestApprovalParams;\n  readonly \"item/fileChange/requestApproval\": CodexSchema.FileChangeRequestApprovalParams;\n  readonly \"item/tool/requestUserInput\": CodexSchema.ToolRequestUserInputParams;\n  readonly \"mcpServer/elicitation/request\": CodexSchema.McpServerElicitationRequestParams;\n  readonly \"item/permissions/requestApproval\": CodexSchema.PermissionsRequestApprovalParams;\n  readonly \"item/tool/call\": CodexSchema.DynamicToolCallParams;\n  readonly \"account/chatgptAuthTokens/refresh\": CodexSchema.ChatgptAuthTokensRefreshParams;\n  readonly \"attestation/generate\": CodexSchema.AttestationGenerateParams;\n  readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalParams;\n  readonly execCommandApproval: CodexSchema.ExecCommandApprovalParams;\n}\n\nexport interface ServerRequestResponsesByMethod {\n  readonly \"item/commandExecution/requestApproval\": CodexSchema.CommandExecutionRequestApprovalResponse;\n  readonly \"item/fileChange/requestApproval\": CodexSchema.FileChangeRequestApprovalResponse;\n  readonly \"item/tool/requestUserInput\": CodexSchema.ToolRequestUserInputResponse;\n  readonly \"mcpServer/elicitation/request\": CodexSchema.McpServerElicitationRequestResponse;\n  readonly \"item/permissions/requestApproval\": CodexSchema.PermissionsRequestApprovalResponse;\n  readonly \"item/tool/call\": CodexSchema.DynamicToolCallResponse;\n  readonly \"account/chatgptAuthTokens/refresh\": CodexSchema.ChatgptAuthTokensRefreshResponse;\n  readonly \"attestation/generate\": CodexSchema.AttestationGenerateResponse;\n  readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse;\n  readonly execCommandApproval: CodexSchema.ExecCommandApprovalResponse;\n}\n\nexport interface ServerNotificationParamsByMethod {\n  readonly error: CodexSchema.V2ErrorNotification;\n  readonly \"thread/started\": CodexSchema.V2ThreadStartedNotification;\n  readonly \"thread/status/changed\": CodexSchema.V2ThreadStatusChangedNotification;\n  readonly \"thread/archived\": CodexSchema.V2ThreadArchivedNotification;\n  readonly \"thread/deleted\": CodexSchema.V2ThreadDeletedNotification;\n  readonly \"thread/unarchived\": CodexSchema.V2ThreadUnarchivedNotification;\n  readonly \"thread/closed\": CodexSchema.V2ThreadClosedNotification;\n  readonly \"skills/changed\": CodexSchema.V2SkillsChangedNotification;\n  readonly \"thread/name/updated\": CodexSchema.V2ThreadNameUpdatedNotification;\n  readonly \"thread/goal/updated\": CodexSchema.V2ThreadGoalUpdatedNotification;\n  readonly \"thread/goal/cleared\": CodexSchema.V2ThreadGoalClearedNotification;\n  readonly \"thread/environment/connected\": CodexSchema.V2EnvironmentConnectionNotification;\n  readonly \"thread/environment/disconnected\": CodexSchema.V2EnvironmentConnectionNotification;\n  readonly \"thread/settings/updated\": CodexSchema.V2ThreadSettingsUpdatedNotification;\n  readonly \"thread/tokenUsage/updated\": CodexSchema.V2ThreadTokenUsageUpdatedNotification;\n  readonly \"turn/started\": CodexSchema.V2TurnStartedNotification;\n  readonly \"hook/started\": CodexSchema.V2HookStartedNotification;\n  readonly \"turn/completed\": CodexSchema.V2TurnCompletedNotification;\n  readonly \"hook/completed\": CodexSchema.V2HookCompletedNotification;\n  readonly \"turn/diff/updated\": CodexSchema.V2TurnDiffUpdatedNotification;\n  readonly \"turn/plan/updated\": CodexSchema.V2TurnPlanUpdatedNotification;\n  readonly \"item/started\": CodexSchema.V2ItemStartedNotification;\n  readonly \"item/autoApprovalReview/started\": CodexSchema.V2ItemGuardianApprovalReviewStartedNotification;\n  readonly \"item/autoApprovalReview/completed\": CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification;\n  readonly \"item/completed\": CodexSchema.V2ItemCompletedNotification;\n  readonly \"rawResponseItem/completed\": CodexSchema.V2RawResponseItemCompletedNotification;\n  readonly \"rawResponse/completed\": CodexSchema.V2RawResponseCompletedNotification;\n  readonly \"item/agentMessage/delta\": CodexSchema.V2AgentMessageDeltaNotification;\n  readonly \"item/plan/delta\": CodexSchema.V2PlanDeltaNotification;\n  readonly \"command/exec/outputDelta\": CodexSchema.V2CommandExecOutputDeltaNotification;\n  readonly \"process/outputDelta\": CodexSchema.V2ProcessOutputDeltaNotification;\n  readonly \"process/exited\": CodexSchema.V2ProcessExitedNotification;\n  readonly \"item/commandExecution/outputDelta\": CodexSchema.V2CommandExecutionOutputDeltaNotification;\n  readonly \"item/commandExecution/terminalInteraction\": CodexSchema.V2TerminalInteractionNotification;\n  readonly \"item/fileChange/outputDelta\": CodexSchema.V2FileChangeOutputDeltaNotification;\n  readonly \"item/fileChange/patchUpdated\": CodexSchema.V2FileChangePatchUpdatedNotification;\n  readonly \"serverRequest/resolved\": CodexSchema.V2ServerRequestResolvedNotification;\n  readonly \"item/mcpToolCall/progress\": CodexSchema.V2McpToolCallProgressNotification;\n  readonly \"mcpServer/oauthLogin/completed\": CodexSchema.V2McpServerOauthLoginCompletedNotification;\n  readonly \"mcpServer/startupStatus/updated\": CodexSchema.V2McpServerStatusUpdatedNotification;\n  readonly \"account/updated\": CodexSchema.V2AccountUpdatedNotification;\n  readonly \"account/rateLimits/updated\": CodexSchema.V2AccountRateLimitsUpdatedNotification;\n  readonly \"app/list/updated\": CodexSchema.V2AppListUpdatedNotification;\n  readonly \"remoteControl/status/changed\": CodexSchema.V2RemoteControlStatusChangedNotification;\n  readonly \"externalAgentConfig/import/progress\": CodexSchema.V2ExternalAgentConfigImportProgressNotification;\n  readonly \"externalAgentConfig/import/completed\": CodexSchema.V2ExternalAgentConfigImportCompletedNotification;\n  readonly \"fs/changed\": CodexSchema.V2FsChangedNotification;\n  readonly \"item/reasoning/summaryTextDelta\": CodexSchema.V2ReasoningSummaryTextDeltaNotification;\n  readonly \"item/reasoning/summaryPartAdded\": CodexSchema.V2ReasoningSummaryPartAddedNotification;\n  readonly \"item/reasoning/textDelta\": CodexSchema.V2ReasoningTextDeltaNotification;\n  readonly \"thread/compacted\": CodexSchema.V2ContextCompactedNotification;\n  readonly \"model/rerouted\": CodexSchema.V2ModelReroutedNotification;\n  readonly \"model/verification\": CodexSchema.V2ModelVerificationNotification;\n  readonly \"turn/moderationMetadata\": CodexSchema.V2TurnModerationMetadataNotification;\n  readonly \"model/safetyBuffering/updated\": CodexSchema.V2ModelSafetyBufferingUpdatedNotification;\n  readonly warning: CodexSchema.V2WarningNotification;\n  readonly guardianWarning: CodexSchema.V2GuardianWarningNotification;\n  readonly deprecationNotice: CodexSchema.V2DeprecationNoticeNotification;\n  readonly configWarning: CodexSchema.V2ConfigWarningNotification;\n  readonly \"fuzzyFileSearch/sessionUpdated\": CodexSchema.FuzzyFileSearchSessionUpdatedNotification;\n  readonly \"fuzzyFileSearch/sessionCompleted\": CodexSchema.FuzzyFileSearchSessionCompletedNotification;\n  readonly \"thread/realtime/started\": CodexSchema.V2ThreadRealtimeStartedNotification;\n  readonly \"thread/realtime/itemAdded\": CodexSchema.V2ThreadRealtimeItemAddedNotification;\n  readonly \"thread/realtime/transcript/delta\": CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification;\n  readonly \"thread/realtime/transcript/done\": CodexSchema.V2ThreadRealtimeTranscriptDoneNotification;\n  readonly \"thread/realtime/outputAudio/delta\": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification;\n  readonly \"thread/realtime/sdp\": CodexSchema.V2ThreadRealtimeSdpNotification;\n  readonly \"thread/realtime/error\": CodexSchema.V2ThreadRealtimeErrorNotification;\n  readonly \"thread/realtime/closed\": CodexSchema.V2ThreadRealtimeClosedNotification;\n  readonly \"windows/worldWritableWarning\": CodexSchema.V2WindowsWorldWritableWarningNotification;\n  readonly \"windowsSandbox/setupCompleted\": CodexSchema.V2WindowsSandboxSetupCompletedNotification;\n  readonly \"account/login/completed\": CodexSchema.V2AccountLoginCompletedNotification;\n}\n\nexport const CLIENT_REQUEST_PARAMS = {\n  initialize: CodexSchema.V1InitializeParams,\n  \"thread/start\": CodexSchema.V2ThreadStartParams,\n  \"thread/resume\": CodexSchema.V2ThreadResumeParams,\n  \"thread/fork\": CodexSchema.V2ThreadForkParams,\n  \"thread/archive\": CodexSchema.V2ThreadArchiveParams,\n  \"thread/delete\": CodexSchema.V2ThreadDeleteParams,\n  \"thread/unsubscribe\": CodexSchema.V2ThreadUnsubscribeParams,\n  \"thread/name/set\": CodexSchema.V2ThreadSetNameParams,\n  \"thread/goal/set\": CodexSchema.V2ThreadGoalSetParams,\n  \"thread/goal/get\": CodexSchema.V2ThreadGoalGetParams,\n  \"thread/goal/clear\": CodexSchema.V2ThreadGoalClearParams,\n  \"thread/metadata/update\": CodexSchema.V2ThreadMetadataUpdateParams,\n  \"thread/unarchive\": CodexSchema.V2ThreadUnarchiveParams,\n  \"thread/compact/start\": CodexSchema.V2ThreadCompactStartParams,\n  \"thread/shellCommand\": CodexSchema.V2ThreadShellCommandParams,\n  \"thread/approveGuardianDeniedAction\": CodexSchema.V2ThreadApproveGuardianDeniedActionParams,\n  \"thread/rollback\": CodexSchema.V2ThreadRollbackParams,\n  \"thread/list\": CodexSchema.V2ThreadListParams,\n  \"thread/loaded/list\": CodexSchema.V2ThreadLoadedListParams,\n  \"thread/read\": CodexSchema.V2ThreadReadParams,\n  \"thread/inject_items\": CodexSchema.V2ThreadInjectItemsParams,\n  \"skills/list\": CodexSchema.V2SkillsListParams,\n  \"skills/extraRoots/set\": CodexSchema.V2SkillsExtraRootsSetParams,\n  \"hooks/list\": CodexSchema.V2HooksListParams,\n  \"marketplace/add\": CodexSchema.V2MarketplaceAddParams,\n  \"marketplace/remove\": CodexSchema.V2MarketplaceRemoveParams,\n  \"marketplace/upgrade\": CodexSchema.V2MarketplaceUpgradeParams,\n  \"plugin/list\": CodexSchema.V2PluginListParams,\n  \"plugin/installed\": CodexSchema.V2PluginInstalledParams,\n  \"plugin/read\": CodexSchema.V2PluginReadParams,\n  \"plugin/skill/read\": CodexSchema.V2PluginSkillReadParams,\n  \"plugin/share/save\": CodexSchema.V2PluginShareSaveParams,\n  \"plugin/share/updateTargets\": CodexSchema.V2PluginShareUpdateTargetsParams,\n  \"plugin/share/list\": CodexSchema.V2PluginShareListParams,\n  \"plugin/share/checkout\": CodexSchema.V2PluginShareCheckoutParams,\n  \"plugin/share/delete\": CodexSchema.V2PluginShareDeleteParams,\n  \"app/read\": CodexSchema.V2AppsReadParams,\n  \"app/list\": CodexSchema.V2AppsListParams,\n  \"app/installed\": CodexSchema.V2AppsInstalledParams,\n  \"fs/readFile\": CodexSchema.V2FsReadFileParams,\n  \"fs/writeFile\": CodexSchema.V2FsWriteFileParams,\n  \"fs/createDirectory\": CodexSchema.V2FsCreateDirectoryParams,\n  \"fs/getMetadata\": CodexSchema.V2FsGetMetadataParams,\n  \"fs/readDirectory\": CodexSchema.V2FsReadDirectoryParams,\n  \"fs/remove\": CodexSchema.V2FsRemoveParams,\n  \"fs/copy\": CodexSchema.V2FsCopyParams,\n  \"fs/watch\": CodexSchema.V2FsWatchParams,\n  \"fs/unwatch\": CodexSchema.V2FsUnwatchParams,\n  \"skills/config/write\": CodexSchema.V2SkillsConfigWriteParams,\n  \"plugin/install\": CodexSchema.V2PluginInstallParams,\n  \"plugin/uninstall\": CodexSchema.V2PluginUninstallParams,\n  \"turn/start\": CodexSchema.V2TurnStartParams,\n  \"turn/steer\": CodexSchema.V2TurnSteerParams,\n  \"turn/interrupt\": CodexSchema.V2TurnInterruptParams,\n  \"review/start\": CodexSchema.V2ReviewStartParams,\n  \"model/list\": CodexSchema.V2ModelListParams,\n  \"modelProvider/capabilities/read\": CodexSchema.V2ModelProviderCapabilitiesReadParams,\n  \"experimentalFeature/list\": CodexSchema.V2ExperimentalFeatureListParams,\n  \"permissionProfile/list\": CodexSchema.V2PermissionProfileListParams,\n  \"experimentalFeature/enablement/set\": CodexSchema.V2ExperimentalFeatureEnablementSetParams,\n  \"mcpServer/oauth/login\": CodexSchema.V2McpServerOauthLoginParams,\n  \"config/mcpServer/reload\": undefined,\n  \"mcpServerStatus/list\": CodexSchema.V2ListMcpServerStatusParams,\n  \"mcpServer/resource/read\": CodexSchema.V2McpResourceReadParams,\n  \"mcpServer/tool/call\": CodexSchema.V2McpServerToolCallParams,\n  \"windowsSandbox/setupStart\": CodexSchema.V2WindowsSandboxSetupStartParams,\n  \"windowsSandbox/readiness\": undefined,\n  \"account/login/start\": CodexSchema.V2LoginAccountParams,\n  \"account/login/cancel\": CodexSchema.V2CancelLoginAccountParams,\n  \"account/logout\": undefined,\n  \"account/rateLimits/read\": undefined,\n  \"account/rateLimitResetCredit/consume\": CodexSchema.V2ConsumeAccountRateLimitResetCreditParams,\n  \"account/usage/read\": undefined,\n  \"account/workspaceMessages/read\": undefined,\n  \"account/sendAddCreditsNudgeEmail\": CodexSchema.V2SendAddCreditsNudgeEmailParams,\n  \"feedback/upload\": CodexSchema.V2FeedbackUploadParams,\n  \"command/exec\": CodexSchema.V2CommandExecParams,\n  \"command/exec/write\": CodexSchema.V2CommandExecWriteParams,\n  \"command/exec/terminate\": CodexSchema.V2CommandExecTerminateParams,\n  \"command/exec/resize\": CodexSchema.V2CommandExecResizeParams,\n  \"config/read\": CodexSchema.V2ConfigReadParams,\n  \"externalAgentConfig/detect\": CodexSchema.V2ExternalAgentConfigDetectParams,\n  \"externalAgentConfig/import\": CodexSchema.V2ExternalAgentConfigImportParams,\n  \"externalAgentConfig/import/readHistories\": undefined,\n  \"config/value/write\": CodexSchema.V2ConfigValueWriteParams,\n  \"config/batchWrite\": CodexSchema.V2ConfigBatchWriteParams,\n  \"configRequirements/read\": undefined,\n  \"account/read\": CodexSchema.V2GetAccountParams,\n  getConversationSummary: CodexSchema.GetConversationSummaryParams,\n  gitDiffToRemote: CodexSchema.GitDiffToRemoteParams,\n  getAuthStatus: CodexSchema.GetAuthStatusParams,\n  fuzzyFileSearch: CodexSchema.FuzzyFileSearchParams,\n} as const;\n\nexport const CLIENT_REQUEST_RESPONSES = {\n  initialize: CodexSchema.V1InitializeResponse,\n  \"thread/start\": CodexSchema.V2ThreadStartResponse,\n  \"thread/resume\": CodexSchema.V2ThreadResumeResponse,\n  \"thread/fork\": CodexSchema.V2ThreadForkResponse,\n  \"thread/archive\": CodexSchema.V2ThreadArchiveResponse,\n  \"thread/delete\": CodexSchema.V2ThreadDeleteResponse,\n  \"thread/unsubscribe\": CodexSchema.V2ThreadUnsubscribeResponse,\n  \"thread/name/set\": CodexSchema.V2ThreadSetNameResponse,\n  \"thread/goal/set\": CodexSchema.V2ThreadGoalSetResponse,\n  \"thread/goal/get\": CodexSchema.V2ThreadGoalGetResponse,\n  \"thread/goal/clear\": CodexSchema.V2ThreadGoalClearResponse,\n  \"thread/metadata/update\": CodexSchema.V2ThreadMetadataUpdateResponse,\n  \"thread/unarchive\": CodexSchema.V2ThreadUnarchiveResponse,\n  \"thread/compact/start\": CodexSchema.V2ThreadCompactStartResponse,\n  \"thread/shellCommand\": CodexSchema.V2ThreadShellCommandResponse,\n  \"thread/approveGuardianDeniedAction\": CodexSchema.V2ThreadApproveGuardianDeniedActionResponse,\n  \"thread/rollback\": CodexSchema.V2ThreadRollbackResponse,\n  \"thread/list\": CodexSchema.V2ThreadListResponse,\n  \"thread/loaded/list\": CodexSchema.V2ThreadLoadedListResponse,\n  \"thread/read\": CodexSchema.V2ThreadReadResponse,\n  \"thread/inject_items\": CodexSchema.V2ThreadInjectItemsResponse,\n  \"skills/list\": CodexSchema.V2SkillsListResponse,\n  \"skills/extraRoots/set\": CodexSchema.V2SkillsExtraRootsSetResponse,\n  \"hooks/list\": CodexSchema.V2HooksListResponse,\n  \"marketplace/add\": CodexSchema.V2MarketplaceAddResponse,\n  \"marketplace/remove\": CodexSchema.V2MarketplaceRemoveResponse,\n  \"marketplace/upgrade\": CodexSchema.V2MarketplaceUpgradeResponse,\n  \"plugin/list\": CodexSchema.V2PluginListResponse,\n  \"plugin/installed\": CodexSchema.V2PluginInstalledResponse,\n  \"plugin/read\": CodexSchema.V2PluginReadResponse,\n  \"plugin/skill/read\": CodexSchema.V2PluginSkillReadResponse,\n  \"plugin/share/save\": CodexSchema.V2PluginShareSaveResponse,\n  \"plugin/share/updateTargets\": CodexSchema.V2PluginShareUpdateTargetsResponse,\n  \"plugin/share/list\": CodexSchema.V2PluginShareListResponse,\n  \"plugin/share/checkout\": CodexSchema.V2PluginShareCheckoutResponse,\n  \"plugin/share/delete\": CodexSchema.V2PluginShareDeleteResponse,\n  \"app/read\": CodexSchema.V2AppsReadResponse,\n  \"app/list\": CodexSchema.V2AppsListResponse,\n  \"app/installed\": CodexSchema.V2AppsInstalledResponse,\n  \"fs/readFile\": CodexSchema.V2FsReadFileResponse,\n  \"fs/writeFile\": CodexSchema.V2FsWriteFileResponse,\n  \"fs/createDirectory\": CodexSchema.V2FsCreateDirectoryResponse,\n  \"fs/getMetadata\": CodexSchema.V2FsGetMetadataResponse,\n  \"fs/readDirectory\": CodexSchema.V2FsReadDirectoryResponse,\n  \"fs/remove\": CodexSchema.V2FsRemoveResponse,\n  \"fs/copy\": CodexSchema.V2FsCopyResponse,\n  \"fs/watch\": CodexSchema.V2FsWatchResponse,\n  \"fs/unwatch\": CodexSchema.V2FsUnwatchResponse,\n  \"skills/config/write\": CodexSchema.V2SkillsConfigWriteResponse,\n  \"plugin/install\": CodexSchema.V2PluginInstallResponse,\n  \"plugin/uninstall\": CodexSchema.V2PluginUninstallResponse,\n  \"turn/start\": CodexSchema.V2TurnStartResponse,\n  \"turn/steer\": CodexSchema.V2TurnSteerResponse,\n  \"turn/interrupt\": CodexSchema.V2TurnInterruptResponse,\n  \"review/start\": CodexSchema.V2ReviewStartResponse,\n  \"model/list\": CodexSchema.V2ModelListResponse,\n  \"modelProvider/capabilities/read\": CodexSchema.V2ModelProviderCapabilitiesReadResponse,\n  \"experimentalFeature/list\": CodexSchema.V2ExperimentalFeatureListResponse,\n  \"permissionProfile/list\": CodexSchema.V2PermissionProfileListResponse,\n  \"experimentalFeature/enablement/set\": CodexSchema.V2ExperimentalFeatureEnablementSetResponse,\n  \"mcpServer/oauth/login\": CodexSchema.V2McpServerOauthLoginResponse,\n  \"config/mcpServer/reload\": CodexSchema.V2McpServerRefreshResponse,\n  \"mcpServerStatus/list\": CodexSchema.V2ListMcpServerStatusResponse,\n  \"mcpServer/resource/read\": CodexSchema.V2McpResourceReadResponse,\n  \"mcpServer/tool/call\": CodexSchema.V2McpServerToolCallResponse,\n  \"windowsSandbox/setupStart\": CodexSchema.V2WindowsSandboxSetupStartResponse,\n  \"windowsSandbox/readiness\": CodexSchema.V2WindowsSandboxReadinessResponse,\n  \"account/login/start\": CodexSchema.V2LoginAccountResponse,\n  \"account/login/cancel\": CodexSchema.V2CancelLoginAccountResponse,\n  \"account/logout\": CodexSchema.V2LogoutAccountResponse,\n  \"account/rateLimits/read\": CodexSchema.V2GetAccountRateLimitsResponse,\n  \"account/rateLimitResetCredit/consume\": CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse,\n  \"account/usage/read\": CodexSchema.V2GetAccountTokenUsageResponse,\n  \"account/workspaceMessages/read\": CodexSchema.V2GetWorkspaceMessagesResponse,\n  \"account/sendAddCreditsNudgeEmail\": CodexSchema.V2SendAddCreditsNudgeEmailResponse,\n  \"feedback/upload\": CodexSchema.V2FeedbackUploadResponse,\n  \"command/exec\": CodexSchema.V2CommandExecResponse,\n  \"command/exec/write\": CodexSchema.V2CommandExecWriteResponse,\n  \"command/exec/terminate\": CodexSchema.V2CommandExecTerminateResponse,\n  \"command/exec/resize\": CodexSchema.V2CommandExecResizeResponse,\n  \"config/read\": CodexSchema.V2ConfigReadResponse,\n  \"externalAgentConfig/detect\": CodexSchema.V2ExternalAgentConfigDetectResponse,\n  \"externalAgentConfig/import\": CodexSchema.V2ExternalAgentConfigImportResponse,\n  \"externalAgentConfig/import/readHistories\":\n    CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse,\n  \"config/value/write\": CodexSchema.V2ConfigWriteResponse,\n  \"config/batchWrite\": CodexSchema.V2ConfigWriteResponse,\n  \"configRequirements/read\": CodexSchema.V2ConfigRequirementsReadResponse,\n  \"account/read\": CodexSchema.V2GetAccountResponse,\n  getConversationSummary: CodexSchema.GetConversationSummaryResponse,\n  gitDiffToRemote: CodexSchema.GitDiffToRemoteResponse,\n  getAuthStatus: CodexSchema.GetAuthStatusResponse,\n  fuzzyFileSearch: CodexSchema.FuzzyFileSearchResponse,\n} as const;\n\nexport const CLIENT_NOTIFICATION_PARAMS = {\n  initialized: undefined,\n} as const;\n\nexport const SERVER_REQUEST_PARAMS = {\n  \"item/commandExecution/requestApproval\": CodexSchema.CommandExecutionRequestApprovalParams,\n  \"item/fileChange/requestApproval\": CodexSchema.FileChangeRequestApprovalParams,\n  \"item/tool/requestUserInput\": CodexSchema.ToolRequestUserInputParams,\n  \"mcpServer/elicitation/request\": CodexSchema.McpServerElicitationRequestParams,\n  \"item/permissions/requestApproval\": CodexSchema.PermissionsRequestApprovalParams,\n  \"item/tool/call\": CodexSchema.DynamicToolCallParams,\n  \"account/chatgptAuthTokens/refresh\": CodexSchema.ChatgptAuthTokensRefreshParams,\n  \"attestation/generate\": CodexSchema.AttestationGenerateParams,\n  applyPatchApproval: CodexSchema.ApplyPatchApprovalParams,\n  execCommandApproval: CodexSchema.ExecCommandApprovalParams,\n} as const;\n\nexport const SERVER_REQUEST_RESPONSES = {\n  \"item/commandExecution/requestApproval\": CodexSchema.CommandExecutionRequestApprovalResponse,\n  \"item/fileChange/requestApproval\": CodexSchema.FileChangeRequestApprovalResponse,\n  \"item/tool/requestUserInput\": CodexSchema.ToolRequestUserInputResponse,\n  \"mcpServer/elicitation/request\": CodexSchema.McpServerElicitationRequestResponse,\n  \"item/permissions/requestApproval\": CodexSchema.PermissionsRequestApprovalResponse,\n  \"item/tool/call\": CodexSchema.DynamicToolCallResponse,\n  \"account/chatgptAuthTokens/refresh\": CodexSchema.ChatgptAuthTokensRefreshResponse,\n  \"attestation/generate\": CodexSchema.AttestationGenerateResponse,\n  applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse,\n  execCommandApproval: CodexSchema.ExecCommandApprovalResponse,\n} as const;\n\nexport const SERVER_NOTIFICATION_PARAMS = {\n  error: CodexSchema.V2ErrorNotification,\n  \"thread/started\": CodexSchema.V2ThreadStartedNotification,\n  \"thread/status/changed\": CodexSchema.V2ThreadStatusChangedNotification,\n  \"thread/archived\": CodexSchema.V2ThreadArchivedNotification,\n  \"thread/deleted\": CodexSchema.V2ThreadDeletedNotification,\n  \"thread/unarchived\": CodexSchema.V2ThreadUnarchivedNotification,\n  \"thread/closed\": CodexSchema.V2ThreadClosedNotification,\n  \"skills/changed\": CodexSchema.V2SkillsChangedNotification,\n  \"thread/name/updated\": CodexSchema.V2ThreadNameUpdatedNotification,\n  \"thread/goal/updated\": CodexSchema.V2ThreadGoalUpdatedNotification,\n  \"thread/goal/cleared\": CodexSchema.V2ThreadGoalClearedNotification,\n  \"thread/environment/connected\": CodexSchema.V2EnvironmentConnectionNotification,\n  \"thread/environment/disconnected\": CodexSchema.V2EnvironmentConnectionNotification,\n  \"thread/settings/updated\": CodexSchema.V2ThreadSettingsUpdatedNotification,\n  \"thread/tokenUsage/updated\": CodexSchema.V2ThreadTokenUsageUpdatedNotification,\n  \"turn/started\": CodexSchema.V2TurnStartedNotification,\n  \"hook/started\": CodexSchema.V2HookStartedNotification,\n  \"turn/completed\": CodexSchema.V2TurnCompletedNotification,\n  \"hook/completed\": CodexSchema.V2HookCompletedNotification,\n  \"turn/diff/updated\": CodexSchema.V2TurnDiffUpdatedNotification,\n  \"turn/plan/updated\": CodexSchema.V2TurnPlanUpdatedNotification,\n  \"item/started\": CodexSchema.V2ItemStartedNotification,\n  \"item/autoApprovalReview/started\": CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,\n  \"item/autoApprovalReview/completed\":\n    CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,\n  \"item/completed\": CodexSchema.V2ItemCompletedNotification,\n  \"rawResponseItem/completed\": CodexSchema.V2RawResponseItemCompletedNotification,\n  \"rawResponse/completed\": CodexSchema.V2RawResponseCompletedNotification,\n  \"item/agentMessage/delta\": CodexSchema.V2AgentMessageDeltaNotification,\n  \"item/plan/delta\": CodexSchema.V2PlanDeltaNotification,\n  \"command/exec/outputDelta\": CodexSchema.V2CommandExecOutputDeltaNotification,\n  \"process/outputDelta\": CodexSchema.V2ProcessOutputDeltaNotification,\n  \"process/exited\": CodexSchema.V2ProcessExitedNotification,\n  \"item/commandExecution/outputDelta\": CodexSchema.V2CommandExecutionOutputDeltaNotification,\n  \"item/commandExecution/terminalInteraction\": CodexSchema.V2TerminalInteractionNotification,\n  \"item/fileChange/outputDelta\": CodexSchema.V2FileChangeOutputDeltaNotification,\n  \"item/fileChange/patchUpdated\": CodexSchema.V2FileChangePatchUpdatedNotification,\n  \"serverRequest/resolved\": CodexSchema.V2ServerRequestResolvedNotification,\n  \"item/mcpToolCall/progress\": CodexSchema.V2McpToolCallProgressNotification,\n  \"mcpServer/oauthLogin/completed\": CodexSchema.V2McpServerOauthLoginCompletedNotification,\n  \"mcpServer/startupStatus/updated\": CodexSchema.V2McpServerStatusUpdatedNotification,\n  \"account/updated\": CodexSchema.V2AccountUpdatedNotification,\n  \"account/rateLimits/updated\": CodexSchema.V2AccountRateLimitsUpdatedNotification,\n  \"app/list/updated\": CodexSchema.V2AppListUpdatedNotification,\n  \"remoteControl/status/changed\": CodexSchema.V2RemoteControlStatusChangedNotification,\n  \"externalAgentConfig/import/progress\":\n    CodexSchema.V2ExternalAgentConfigImportProgressNotification,\n  \"externalAgentConfig/import/completed\":\n    CodexSchema.V2ExternalAgentConfigImportCompletedNotification,\n  \"fs/changed\": CodexSchema.V2FsChangedNotification,\n  \"item/reasoning/summaryTextDelta\": CodexSchema.V2ReasoningSummaryTextDeltaNotification,\n  \"item/reasoning/summaryPartAdded\": CodexSchema.V2ReasoningSummaryPartAddedNotification,\n  \"item/reasoning/textDelta\": CodexSchema.V2ReasoningTextDeltaNotification,\n  \"thread/compacted\": CodexSchema.V2ContextCompactedNotification,\n  \"model/rerouted\": CodexSchema.V2ModelReroutedNotification,\n  \"model/verification\": CodexSchema.V2ModelVerificationNotification,\n  \"turn/moderationMetadata\": CodexSchema.V2TurnModerationMetadataNotification,\n  \"model/safetyBuffering/updated\": CodexSchema.V2ModelSafetyBufferingUpdatedNotification,\n  warning: CodexSchema.V2WarningNotification,\n  guardianWarning: CodexSchema.V2GuardianWarningNotification,\n  deprecationNotice: CodexSchema.V2DeprecationNoticeNotification,\n  configWarning: CodexSchema.V2ConfigWarningNotification,\n  \"fuzzyFileSearch/sessionUpdated\": CodexSchema.FuzzyFileSearchSessionUpdatedNotification,\n  \"fuzzyFileSearch/sessionCompleted\": CodexSchema.FuzzyFileSearchSessionCompletedNotification,\n  \"thread/realtime/started\": CodexSchema.V2ThreadRealtimeStartedNotification,\n  \"thread/realtime/itemAdded\": CodexSchema.V2ThreadRealtimeItemAddedNotification,\n  \"thread/realtime/transcript/delta\": CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification,\n  \"thread/realtime/transcript/done\": CodexSchema.V2ThreadRealtimeTranscriptDoneNotification,\n  \"thread/realtime/outputAudio/delta\": CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,\n  \"thread/realtime/sdp\": CodexSchema.V2ThreadRealtimeSdpNotification,\n  \"thread/realtime/error\": CodexSchema.V2ThreadRealtimeErrorNotification,\n  \"thread/realtime/closed\": CodexSchema.V2ThreadRealtimeClosedNotification,\n  \"windows/worldWritableWarning\": CodexSchema.V2WindowsWorldWritableWarningNotification,\n  \"windowsSandbox/setupCompleted\": CodexSchema.V2WindowsSandboxSetupCompletedNotification,\n  \"account/login/completed\": CodexSchema.V2AccountLoginCompletedNotification,\n} as const;\n","// This file is generated by the effect-codex-app-server package. Do not edit manually.\n// Upstream protocol ref: 678157acaa819d5510adfe359abb5d0392cfe461\n\nimport * as CodexSchema from \"./schema.gen.ts\";\n\nexport const v1 = {\n  InitializeParams: CodexSchema.V1InitializeParams,\n  InitializeResponse: CodexSchema.V1InitializeResponse,\n} as const;\n\nexport const v2 = {\n  AccountLoginCompletedNotification: CodexSchema.V2AccountLoginCompletedNotification,\n  AccountRateLimitsUpdatedNotification: CodexSchema.V2AccountRateLimitsUpdatedNotification,\n  AccountUpdatedNotification: CodexSchema.V2AccountUpdatedNotification,\n  AgentMessageDeltaNotification: CodexSchema.V2AgentMessageDeltaNotification,\n  AppListUpdatedNotification: CodexSchema.V2AppListUpdatedNotification,\n  AppsInstalledParams: CodexSchema.V2AppsInstalledParams,\n  AppsInstalledResponse: CodexSchema.V2AppsInstalledResponse,\n  AppsListParams: CodexSchema.V2AppsListParams,\n  AppsListResponse: CodexSchema.V2AppsListResponse,\n  AppsReadParams: CodexSchema.V2AppsReadParams,\n  AppsReadResponse: CodexSchema.V2AppsReadResponse,\n  CancelLoginAccountParams: CodexSchema.V2CancelLoginAccountParams,\n  CancelLoginAccountResponse: CodexSchema.V2CancelLoginAccountResponse,\n  CommandExecOutputDeltaNotification: CodexSchema.V2CommandExecOutputDeltaNotification,\n  CommandExecParams: CodexSchema.V2CommandExecParams,\n  CommandExecResizeParams: CodexSchema.V2CommandExecResizeParams,\n  CommandExecResizeResponse: CodexSchema.V2CommandExecResizeResponse,\n  CommandExecResponse: CodexSchema.V2CommandExecResponse,\n  CommandExecTerminateParams: CodexSchema.V2CommandExecTerminateParams,\n  CommandExecTerminateResponse: CodexSchema.V2CommandExecTerminateResponse,\n  CommandExecutionOutputDeltaNotification: CodexSchema.V2CommandExecutionOutputDeltaNotification,\n  CommandExecWriteParams: CodexSchema.V2CommandExecWriteParams,\n  CommandExecWriteResponse: CodexSchema.V2CommandExecWriteResponse,\n  ConfigBatchWriteParams: CodexSchema.V2ConfigBatchWriteParams,\n  ConfigReadParams: CodexSchema.V2ConfigReadParams,\n  ConfigReadResponse: CodexSchema.V2ConfigReadResponse,\n  ConfigRequirementsReadResponse: CodexSchema.V2ConfigRequirementsReadResponse,\n  ConfigValueWriteParams: CodexSchema.V2ConfigValueWriteParams,\n  ConfigWarningNotification: CodexSchema.V2ConfigWarningNotification,\n  ConfigWriteResponse: CodexSchema.V2ConfigWriteResponse,\n  ConsumeAccountRateLimitResetCreditParams: CodexSchema.V2ConsumeAccountRateLimitResetCreditParams,\n  ConsumeAccountRateLimitResetCreditResponse:\n    CodexSchema.V2ConsumeAccountRateLimitResetCreditResponse,\n  ContextCompactedNotification: CodexSchema.V2ContextCompactedNotification,\n  DeprecationNoticeNotification: CodexSchema.V2DeprecationNoticeNotification,\n  EnvironmentConnectionNotification: CodexSchema.V2EnvironmentConnectionNotification,\n  ErrorNotification: CodexSchema.V2ErrorNotification,\n  ExperimentalFeatureEnablementSetParams: CodexSchema.V2ExperimentalFeatureEnablementSetParams,\n  ExperimentalFeatureEnablementSetResponse: CodexSchema.V2ExperimentalFeatureEnablementSetResponse,\n  ExperimentalFeatureListParams: CodexSchema.V2ExperimentalFeatureListParams,\n  ExperimentalFeatureListResponse: CodexSchema.V2ExperimentalFeatureListResponse,\n  ExternalAgentConfigDetectParams: CodexSchema.V2ExternalAgentConfigDetectParams,\n  ExternalAgentConfigDetectResponse: CodexSchema.V2ExternalAgentConfigDetectResponse,\n  ExternalAgentConfigImportCompletedNotification:\n    CodexSchema.V2ExternalAgentConfigImportCompletedNotification,\n  ExternalAgentConfigImportHistoriesReadResponse:\n    CodexSchema.V2ExternalAgentConfigImportHistoriesReadResponse,\n  ExternalAgentConfigImportParams: CodexSchema.V2ExternalAgentConfigImportParams,\n  ExternalAgentConfigImportProgressNotification:\n    CodexSchema.V2ExternalAgentConfigImportProgressNotification,\n  ExternalAgentConfigImportResponse: CodexSchema.V2ExternalAgentConfigImportResponse,\n  FeedbackUploadParams: CodexSchema.V2FeedbackUploadParams,\n  FeedbackUploadResponse: CodexSchema.V2FeedbackUploadResponse,\n  FileChangeOutputDeltaNotification: CodexSchema.V2FileChangeOutputDeltaNotification,\n  FileChangePatchUpdatedNotification: CodexSchema.V2FileChangePatchUpdatedNotification,\n  FsChangedNotification: CodexSchema.V2FsChangedNotification,\n  FsCopyParams: CodexSchema.V2FsCopyParams,\n  FsCopyResponse: CodexSchema.V2FsCopyResponse,\n  FsCreateDirectoryParams: CodexSchema.V2FsCreateDirectoryParams,\n  FsCreateDirectoryResponse: CodexSchema.V2FsCreateDirectoryResponse,\n  FsGetMetadataParams: CodexSchema.V2FsGetMetadataParams,\n  FsGetMetadataResponse: CodexSchema.V2FsGetMetadataResponse,\n  FsReadDirectoryParams: CodexSchema.V2FsReadDirectoryParams,\n  FsReadDirectoryResponse: CodexSchema.V2FsReadDirectoryResponse,\n  FsReadFileParams: CodexSchema.V2FsReadFileParams,\n  FsReadFileResponse: CodexSchema.V2FsReadFileResponse,\n  FsRemoveParams: CodexSchema.V2FsRemoveParams,\n  FsRemoveResponse: CodexSchema.V2FsRemoveResponse,\n  FsUnwatchParams: CodexSchema.V2FsUnwatchParams,\n  FsUnwatchResponse: CodexSchema.V2FsUnwatchResponse,\n  FsWatchParams: CodexSchema.V2FsWatchParams,\n  FsWatchResponse: CodexSchema.V2FsWatchResponse,\n  FsWriteFileParams: CodexSchema.V2FsWriteFileParams,\n  FsWriteFileResponse: CodexSchema.V2FsWriteFileResponse,\n  GetAccountParams: CodexSchema.V2GetAccountParams,\n  GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse,\n  GetAccountResponse: CodexSchema.V2GetAccountResponse,\n  GetAccountTokenUsageResponse: CodexSchema.V2GetAccountTokenUsageResponse,\n  GetWorkspaceMessagesResponse: CodexSchema.V2GetWorkspaceMessagesResponse,\n  GuardianWarningNotification: CodexSchema.V2GuardianWarningNotification,\n  HookCompletedNotification: CodexSchema.V2HookCompletedNotification,\n  HooksListParams: CodexSchema.V2HooksListParams,\n  HooksListResponse: CodexSchema.V2HooksListResponse,\n  HookStartedNotification: CodexSchema.V2HookStartedNotification,\n  ItemCompletedNotification: CodexSchema.V2ItemCompletedNotification,\n  ItemGuardianApprovalReviewCompletedNotification:\n    CodexSchema.V2ItemGuardianApprovalReviewCompletedNotification,\n  ItemGuardianApprovalReviewStartedNotification:\n    CodexSchema.V2ItemGuardianApprovalReviewStartedNotification,\n  ItemStartedNotification: CodexSchema.V2ItemStartedNotification,\n  ListMcpServerStatusParams: CodexSchema.V2ListMcpServerStatusParams,\n  ListMcpServerStatusResponse: CodexSchema.V2ListMcpServerStatusResponse,\n  LoginAccountParams: CodexSchema.V2LoginAccountParams,\n  LoginAccountResponse: CodexSchema.V2LoginAccountResponse,\n  LogoutAccountResponse: CodexSchema.V2LogoutAccountResponse,\n  MarketplaceAddParams: CodexSchema.V2MarketplaceAddParams,\n  MarketplaceAddResponse: CodexSchema.V2MarketplaceAddResponse,\n  MarketplaceRemoveParams: CodexSchema.V2MarketplaceRemoveParams,\n  MarketplaceRemoveResponse: CodexSchema.V2MarketplaceRemoveResponse,\n  MarketplaceUpgradeParams: CodexSchema.V2MarketplaceUpgradeParams,\n  MarketplaceUpgradeResponse: CodexSchema.V2MarketplaceUpgradeResponse,\n  McpResourceReadParams: CodexSchema.V2McpResourceReadParams,\n  McpResourceReadResponse: CodexSchema.V2McpResourceReadResponse,\n  McpServerOauthLoginCompletedNotification: CodexSchema.V2McpServerOauthLoginCompletedNotification,\n  McpServerOauthLoginParams: CodexSchema.V2McpServerOauthLoginParams,\n  McpServerOauthLoginResponse: CodexSchema.V2McpServerOauthLoginResponse,\n  McpServerRefreshResponse: CodexSchema.V2McpServerRefreshResponse,\n  McpServerStatusUpdatedNotification: CodexSchema.V2McpServerStatusUpdatedNotification,\n  McpServerToolCallParams: CodexSchema.V2McpServerToolCallParams,\n  McpServerToolCallResponse: CodexSchema.V2McpServerToolCallResponse,\n  McpToolCallProgressNotification: CodexSchema.V2McpToolCallProgressNotification,\n  ModelListParams: CodexSchema.V2ModelListParams,\n  ModelListResponse: CodexSchema.V2ModelListResponse,\n  ModelProviderCapabilitiesReadParams: CodexSchema.V2ModelProviderCapabilitiesReadParams,\n  ModelProviderCapabilitiesReadResponse: CodexSchema.V2ModelProviderCapabilitiesReadResponse,\n  ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification,\n  ModelSafetyBufferingUpdatedNotification: CodexSchema.V2ModelSafetyBufferingUpdatedNotification,\n  ModelVerificationNotification: CodexSchema.V2ModelVerificationNotification,\n  PermissionProfileListParams: CodexSchema.V2PermissionProfileListParams,\n  PermissionProfileListResponse: CodexSchema.V2PermissionProfileListResponse,\n  PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification,\n  PluginInstalledParams: CodexSchema.V2PluginInstalledParams,\n  PluginInstalledResponse: CodexSchema.V2PluginInstalledResponse,\n  PluginInstallParams: CodexSchema.V2PluginInstallParams,\n  PluginInstallResponse: CodexSchema.V2PluginInstallResponse,\n  PluginListParams: CodexSchema.V2PluginListParams,\n  PluginListResponse: CodexSchema.V2PluginListResponse,\n  PluginReadParams: CodexSchema.V2PluginReadParams,\n  PluginReadResponse: CodexSchema.V2PluginReadResponse,\n  PluginShareCheckoutParams: CodexSchema.V2PluginShareCheckoutParams,\n  PluginShareCheckoutResponse: CodexSchema.V2PluginShareCheckoutResponse,\n  PluginShareDeleteParams: CodexSchema.V2PluginShareDeleteParams,\n  PluginShareDeleteResponse: CodexSchema.V2PluginShareDeleteResponse,\n  PluginShareListParams: CodexSchema.V2PluginShareListParams,\n  PluginShareListResponse: CodexSchema.V2PluginShareListResponse,\n  PluginShareSaveParams: CodexSchema.V2PluginShareSaveParams,\n  PluginShareSaveResponse: CodexSchema.V2PluginShareSaveResponse,\n  PluginShareUpdateTargetsParams: CodexSchema.V2PluginShareUpdateTargetsParams,\n  PluginShareUpdateTargetsResponse: CodexSchema.V2PluginShareUpdateTargetsResponse,\n  PluginSkillReadParams: CodexSchema.V2PluginSkillReadParams,\n  PluginSkillReadResponse: CodexSchema.V2PluginSkillReadResponse,\n  PluginUninstallParams: CodexSchema.V2PluginUninstallParams,\n  PluginUninstallResponse: CodexSchema.V2PluginUninstallResponse,\n  ProcessExitedNotification: CodexSchema.V2ProcessExitedNotification,\n  ProcessOutputDeltaNotification: CodexSchema.V2ProcessOutputDeltaNotification,\n  RawResponseCompletedNotification: CodexSchema.V2RawResponseCompletedNotification,\n  RawResponseItemCompletedNotification: CodexSchema.V2RawResponseItemCompletedNotification,\n  ReasoningSummaryPartAddedNotification: CodexSchema.V2ReasoningSummaryPartAddedNotification,\n  ReasoningSummaryTextDeltaNotification: CodexSchema.V2ReasoningSummaryTextDeltaNotification,\n  ReasoningTextDeltaNotification: CodexSchema.V2ReasoningTextDeltaNotification,\n  RemoteControlStatusChangedNotification: CodexSchema.V2RemoteControlStatusChangedNotification,\n  ReviewStartParams: CodexSchema.V2ReviewStartParams,\n  ReviewStartResponse: CodexSchema.V2ReviewStartResponse,\n  SendAddCreditsNudgeEmailParams: CodexSchema.V2SendAddCreditsNudgeEmailParams,\n  SendAddCreditsNudgeEmailResponse: CodexSchema.V2SendAddCreditsNudgeEmailResponse,\n  ServerRequestResolvedNotification: CodexSchema.V2ServerRequestResolvedNotification,\n  SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification,\n  SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams,\n  SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse,\n  SkillsExtraRootsSetParams: CodexSchema.V2SkillsExtraRootsSetParams,\n  SkillsExtraRootsSetResponse: CodexSchema.V2SkillsExtraRootsSetResponse,\n  SkillsListParams: CodexSchema.V2SkillsListParams,\n  SkillsListResponse: CodexSchema.V2SkillsListResponse,\n  TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification,\n  ThreadApproveGuardianDeniedActionParams: CodexSchema.V2ThreadApproveGuardianDeniedActionParams,\n  ThreadApproveGuardianDeniedActionResponse:\n    CodexSchema.V2ThreadApproveGuardianDeniedActionResponse,\n  ThreadArchivedNotification: CodexSchema.V2ThreadArchivedNotification,\n  ThreadArchiveParams: CodexSchema.V2ThreadArchiveParams,\n  ThreadArchiveResponse: CodexSchema.V2ThreadArchiveResponse,\n  ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification,\n  ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams,\n  ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse,\n  ThreadDeletedNotification: CodexSchema.V2ThreadDeletedNotification,\n  ThreadDeleteParams: CodexSchema.V2ThreadDeleteParams,\n  ThreadDeleteResponse: CodexSchema.V2ThreadDeleteResponse,\n  ThreadForkParams: CodexSchema.V2ThreadForkParams,\n  ThreadForkResponse: CodexSchema.V2ThreadForkResponse,\n  ThreadGoalClearedNotification: CodexSchema.V2ThreadGoalClearedNotification,\n  ThreadGoalClearParams: CodexSchema.V2ThreadGoalClearParams,\n  ThreadGoalClearResponse: CodexSchema.V2ThreadGoalClearResponse,\n  ThreadGoalGetParams: CodexSchema.V2ThreadGoalGetParams,\n  ThreadGoalGetResponse: CodexSchema.V2ThreadGoalGetResponse,\n  ThreadGoalSetParams: CodexSchema.V2ThreadGoalSetParams,\n  ThreadGoalSetResponse: CodexSchema.V2ThreadGoalSetResponse,\n  ThreadGoalUpdatedNotification: CodexSchema.V2ThreadGoalUpdatedNotification,\n  ThreadInjectItemsParams: CodexSchema.V2ThreadInjectItemsParams,\n  ThreadInjectItemsResponse: CodexSchema.V2ThreadInjectItemsResponse,\n  ThreadListParams: CodexSchema.V2ThreadListParams,\n  ThreadListResponse: CodexSchema.V2ThreadListResponse,\n  ThreadLoadedListParams: CodexSchema.V2ThreadLoadedListParams,\n  ThreadLoadedListResponse: CodexSchema.V2ThreadLoadedListResponse,\n  ThreadMetadataUpdateParams: CodexSchema.V2ThreadMetadataUpdateParams,\n  ThreadMetadataUpdateResponse: CodexSchema.V2ThreadMetadataUpdateResponse,\n  ThreadNameUpdatedNotification: CodexSchema.V2ThreadNameUpdatedNotification,\n  ThreadReadParams: CodexSchema.V2ThreadReadParams,\n  ThreadReadResponse: CodexSchema.V2ThreadReadResponse,\n  ThreadRealtimeClosedNotification: CodexSchema.V2ThreadRealtimeClosedNotification,\n  ThreadRealtimeErrorNotification: CodexSchema.V2ThreadRealtimeErrorNotification,\n  ThreadRealtimeItemAddedNotification: CodexSchema.V2ThreadRealtimeItemAddedNotification,\n  ThreadRealtimeOutputAudioDeltaNotification:\n    CodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,\n  ThreadRealtimeSdpNotification: CodexSchema.V2ThreadRealtimeSdpNotification,\n  ThreadRealtimeStartedNotification: CodexSchema.V2ThreadRealtimeStartedNotification,\n  ThreadRealtimeTranscriptDeltaNotification:\n    CodexSchema.V2ThreadRealtimeTranscriptDeltaNotification,\n  ThreadRealtimeTranscriptDoneNotification: CodexSchema.V2ThreadRealtimeTranscriptDoneNotification,\n  ThreadResumeParams: CodexSchema.V2ThreadResumeParams,\n  ThreadResumeResponse: CodexSchema.V2ThreadResumeResponse,\n  ThreadRollbackParams: CodexSchema.V2ThreadRollbackParams,\n  ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse,\n  ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams,\n  ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse,\n  ThreadSettingsUpdatedNotification: CodexSchema.V2ThreadSettingsUpdatedNotification,\n  ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams,\n  ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse,\n  ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification,\n  ThreadStartParams: CodexSchema.V2ThreadStartParams,\n  ThreadStartResponse: CodexSchema.V2ThreadStartResponse,\n  ThreadStatusChangedNotification: CodexSchema.V2ThreadStatusChangedNotification,\n  ThreadTokenUsageUpdatedNotification: CodexSchema.V2ThreadTokenUsageUpdatedNotification,\n  ThreadUnarchivedNotification: CodexSchema.V2ThreadUnarchivedNotification,\n  ThreadUnarchiveParams: CodexSchema.V2ThreadUnarchiveParams,\n  ThreadUnarchiveResponse: CodexSchema.V2ThreadUnarchiveResponse,\n  ThreadUnsubscribeParams: CodexSchema.V2ThreadUnsubscribeParams,\n  ThreadUnsubscribeResponse: CodexSchema.V2ThreadUnsubscribeResponse,\n  TurnCompletedNotification: CodexSchema.V2TurnCompletedNotification,\n  TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification,\n  TurnInterruptParams: CodexSchema.V2TurnInterruptParams,\n  TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse,\n  TurnModerationMetadataNotification: CodexSchema.V2TurnModerationMetadataNotification,\n  TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification,\n  TurnStartedNotification: CodexSchema.V2TurnStartedNotification,\n  TurnStartParams: CodexSchema.V2TurnStartParams,\n  TurnStartResponse: CodexSchema.V2TurnStartResponse,\n  TurnSteerParams: CodexSchema.V2TurnSteerParams,\n  TurnSteerResponse: CodexSchema.V2TurnSteerResponse,\n  WarningNotification: CodexSchema.V2WarningNotification,\n  WindowsSandboxReadinessResponse: CodexSchema.V2WindowsSandboxReadinessResponse,\n  WindowsSandboxSetupCompletedNotification: CodexSchema.V2WindowsSandboxSetupCompletedNotification,\n  WindowsSandboxSetupStartParams: CodexSchema.V2WindowsSandboxSetupStartParams,\n  WindowsSandboxSetupStartResponse: CodexSchema.V2WindowsSandboxSetupStartResponse,\n  WindowsWorldWritableWarningNotification: CodexSchema.V2WindowsWorldWritableWarningNotification,\n} as const;\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as CodexError from \"../errors.ts\";\n\nexport const JsonRpcId = Schema.Union([Schema.Number, Schema.String]);\n\nexport const JsonRpcError = Schema.Struct({\n  code: Schema.Number,\n  message: Schema.String,\n  data: Schema.optional(Schema.Unknown),\n});\n\nexport const JsonRpcResponseEnvelope = Schema.Struct({\n  id: JsonRpcId,\n  result: Schema.optional(Schema.Unknown),\n  error: Schema.optional(JsonRpcError),\n});\n\nexport const decodeOptionalPayload = <A, I>(\n  method: string,\n  schema: Schema.Codec<A, I> | undefined,\n  raw: unknown,\n): Effect.Effect<A, CodexError.CodexAppServerRequestError> => {\n  if (!schema) {\n    if (raw === undefined) {\n      return Effect.sync(() => undefined as A);\n    }\n    return Effect.fail(\n      CodexError.CodexAppServerRequestError.unexpectedPayload(method, \"decode-payload\", raw),\n    );\n  }\n\n  return Schema.decodeUnknownEffect(schema)(raw).pipe(\n    Effect.mapError((error) =>\n      CodexError.CodexAppServerRequestError.invalidPayload(method, \"decode-payload\", error),\n    ),\n  );\n};\n\nexport const encodeOptionalPayload = <A, I>(\n  method: string,\n  schema: Schema.Codec<A, I> | undefined,\n  payload: A,\n): Effect.Effect<I | undefined, CodexError.CodexAppServerRequestError> => {\n  if (!schema) {\n    if (payload === undefined) {\n      return Effect.sync(() => undefined);\n    }\n    return Effect.fail(\n      CodexError.CodexAppServerRequestError.unexpectedPayload(method, \"encode-payload\", payload),\n    );\n  }\n\n  return Schema.encodeEffect(schema)(payload).pipe(\n    Effect.mapError((error) =>\n      CodexError.CodexAppServerRequestError.invalidPayload(method, \"encode-payload\", error),\n    ),\n  );\n};\n\nexport const decodeNotificationPayload = <A, I>(\n  method: string,\n  schema: Schema.Codec<A, I> | undefined,\n  raw: unknown,\n): Effect.Effect<A, CodexError.CodexAppServerProtocolParseError> =>\n  decodeOptionalPayload(method, schema, raw).pipe(\n    Effect.mapError((error) =>\n      CodexError.CodexAppServerProtocolParseError.fromRequestError(\n        \"decode-notification-payload\",\n        method,\n        error,\n      ),\n    ),\n  );\n\nexport const runHandler = Effect.fnUntraced(function* <A, B>(\n  handler: ((payload: A) => Effect.Effect<B, CodexError.CodexAppServerError>) | undefined,\n  payload: A,\n  method: string,\n) {\n  if (!handler) {\n    return yield* CodexError.CodexAppServerRequestError.methodNotFound(method);\n  }\n\n  return yield* handler(payload).pipe(\n    Effect.mapError((error) =>\n      CodexError.CodexAppServerRequestError.fromAppServerError(error, method),\n    ),\n  );\n});\n","import * as Cause from \"effect/Cause\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\n\nimport * as CodexError from \"./errors.ts\";\nimport { JsonRpcId, JsonRpcResponseEnvelope } from \"./_internal/shared.ts\";\nconst isJsonRpcId = Schema.is(JsonRpcId);\nconst isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope);\nconst isCodexAppServerError = Schema.is(CodexError.CodexAppServerError);\n\nexport interface CodexAppServerProtocolLogEvent {\n  readonly direction: \"incoming\" | \"outgoing\";\n  readonly stage: \"raw\" | \"decoded\" | \"decode_failed\";\n  readonly payload: unknown;\n}\n\nexport interface CodexAppServerIncomingNotification {\n  readonly method: string;\n  readonly params?: unknown;\n}\n\nexport interface CodexAppServerIncomingRequest {\n  readonly id: string | number;\n  readonly method: string;\n  readonly params?: unknown;\n}\n\nexport interface CodexAppServerPatchedProtocolOptions {\n  readonly stdio: Stdio.Stdio;\n  readonly terminationError?: Effect.Effect<CodexError.CodexAppServerError>;\n  readonly logIncoming?: boolean;\n  readonly logOutgoing?: boolean;\n  readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect<void, never>;\n  readonly onNotification?: (\n    notification: CodexAppServerIncomingNotification,\n  ) => Effect.Effect<void, never>;\n  readonly onRequest?: (\n    request: CodexAppServerIncomingRequest,\n  ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;\n  readonly onTermination?: (error: CodexError.CodexAppServerError) => Effect.Effect<void, never>;\n}\n\nexport interface CodexAppServerPatchedProtocol {\n  readonly incomingNotifications: Stream.Stream<CodexAppServerIncomingNotification>;\n  readonly incomingRequests: Stream.Stream<CodexAppServerIncomingRequest>;\n  readonly request: (\n    method: string,\n    payload?: unknown,\n  ) => Effect.Effect<unknown, CodexError.CodexAppServerError>;\n  readonly notify: (\n    method: string,\n    payload?: unknown,\n  ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n  readonly respond: (\n    requestId: string | number,\n    result: unknown,\n  ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n  readonly respondError: (\n    requestId: string | number,\n    error: CodexError.CodexAppServerRequestError,\n  ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n}\n\ninterface CodexAppServerPendingRequest {\n  readonly deferred: Deferred.Deferred<unknown, CodexError.CodexAppServerError>;\n  readonly method: string;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null;\n}\n\nfunction isIncomingRequest(value: unknown): value is CodexAppServerIncomingRequest {\n  if (!isObject(value) || typeof value.method !== \"string\") {\n    return false;\n  }\n  return isJsonRpcId(value.id);\n}\n\nfunction isIncomingNotification(value: unknown): value is CodexAppServerIncomingNotification {\n  return isObject(value) && typeof value.method === \"string\" && !(\"id\" in value);\n}\n\nfunction isIncomingResponse(value: unknown): value is typeof JsonRpcResponseEnvelope.Type {\n  return isJsonRpcResponseEnvelope(value);\n}\n\nconst encodeJsonString = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\nconst decodeJsonString = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));\n\nconst encodeWireMessage = (\n  message: Record<string, unknown>,\n): Effect.Effect<string, CodexError.CodexAppServerProtocolParseError> =>\n  encodeJsonString(message).pipe(\n    Effect.map((encoded) => `${encoded}\\n`),\n    Effect.mapError((cause) => {\n      const method = typeof message.method === \"string\" ? message.method : undefined;\n      const requestId =\n        typeof message.id === \"string\" || typeof message.id === \"number\"\n          ? String(message.id)\n          : undefined;\n      return CodexError.CodexAppServerProtocolParseError.fromSchemaError(\n        \"encode-wire-message\",\n        cause,\n        {\n          ...(method === undefined ? {} : { method }),\n          ...(requestId === undefined ? {} : { requestId }),\n        },\n      );\n    }),\n  );\n\nconst decodeWireMessage = (\n  line: string,\n): Effect.Effect<unknown, CodexError.CodexAppServerProtocolParseError> =>\n  decodeJsonString(line).pipe(\n    Effect.mapError((cause) =>\n      CodexError.CodexAppServerProtocolParseError.fromSchemaError(\"decode-wire-message\", cause),\n    ),\n  );\n\nconst normalizeIncomingError = (\n  error: unknown,\n  operation: CodexError.CodexAppServerTransportOperation,\n): CodexError.CodexAppServerError =>\n  isCodexAppServerError(error)\n    ? error\n    : new CodexError.CodexAppServerTransportError({\n        operation,\n        cause: error,\n      });\n\nconst toProtocolMessage = (\n  requestId: string | number,\n  fields: {\n    readonly result?: unknown;\n    readonly error?: CodexError.CodexAppServerProtocolErrorShape;\n  },\n): { readonly [key: string]: unknown } => ({\n  id: requestId,\n  ...(fields.result !== undefined ? { result: fields.result } : {}),\n  ...(fields.error !== undefined ? { error: fields.error } : {}),\n});\n\nexport const makeCodexAppServerPatchedProtocol = Effect.fn(\"makeCodexAppServerPatchedProtocol\")(\n  function* (\n    options: CodexAppServerPatchedProtocolOptions,\n  ): Effect.fn.Return<CodexAppServerPatchedProtocol, never, Scope.Scope> {\n    const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();\n    const incomingNotifications = yield* Queue.unbounded<CodexAppServerIncomingNotification>();\n    const incomingRequests = yield* Queue.unbounded<CodexAppServerIncomingRequest>();\n    const pending = yield* Ref.make(new Map<string, CodexAppServerPendingRequest>());\n    const nextRequestId = yield* Ref.make(1);\n    const remainder = yield* Ref.make(\"\");\n    const terminationHandled = yield* Ref.make(false);\n\n    const logProtocol = (event: CodexAppServerProtocolLogEvent) => {\n      if (event.direction === \"incoming\" && !options.logIncoming) {\n        return Effect.void;\n      }\n      if (event.direction === \"outgoing\" && !options.logOutgoing) {\n        return Effect.void;\n      }\n      return (\n        options.logger?.(event) ??\n        Effect.logDebug(\"Codex App Server protocol event\").pipe(Effect.annotateLogs({ event }))\n      );\n    };\n\n    const failAllPending = (error: CodexError.CodexAppServerError) =>\n      Ref.get(pending).pipe(\n        Effect.flatMap((current) =>\n          Effect.forEach([...current.values()], ({ deferred }) => Deferred.fail(deferred, error), {\n            discard: true,\n          }),\n        ),\n        Effect.andThen(Ref.set(pending, new Map())),\n      );\n\n    const handleTermination = (classify: () => Effect.Effect<CodexError.CodexAppServerError>) =>\n      Ref.modify(terminationHandled, (handled) => {\n        if (handled) {\n          return [Effect.void, true] as const;\n        }\n        return [\n          Effect.gen(function* () {\n            const error = yield* classify();\n            yield* failAllPending(error);\n            yield* Queue.end(outgoing);\n            if (options.onTermination) {\n              yield* options.onTermination(error);\n            }\n          }),\n          true,\n        ] as const;\n      }).pipe(Effect.flatten);\n\n    const offerOutgoing = (message: Record<string, unknown>) =>\n      Effect.gen(function* () {\n        yield* logProtocol({\n          direction: \"outgoing\",\n          stage: \"decoded\",\n          payload: message,\n        });\n        const encoded = yield* encodeWireMessage(message);\n        yield* logProtocol({\n          direction: \"outgoing\",\n          stage: \"raw\",\n          payload: encoded,\n        });\n        yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);\n      });\n\n    const removePending = (requestId: string) =>\n      Ref.update(pending, (current) => {\n        if (!current.has(requestId)) {\n          return current;\n        }\n        const next = new Map(current);\n        next.delete(requestId);\n        return next;\n      });\n\n    const resolvePending = (\n      requestId: string,\n      handler: (pendingRequest: CodexAppServerPendingRequest) => Effect.Effect<void>,\n    ) =>\n      Ref.modify(pending, (current) => {\n        const pendingRequest = current.get(requestId);\n        if (!pendingRequest) {\n          return [Effect.void, current] as const;\n        }\n        const next = new Map(current);\n        next.delete(requestId);\n        return [handler(pendingRequest), next] as const;\n      }).pipe(Effect.flatten);\n\n    const respond = (requestId: string | number, result: unknown) =>\n      offerOutgoing(toProtocolMessage(requestId, { result }));\n\n    const respondError = (\n      requestId: string | number,\n      error: CodexError.CodexAppServerRequestError,\n    ) => offerOutgoing(toProtocolMessage(requestId, { error: error.toProtocolError() }));\n\n    const handleResponse = (response: typeof JsonRpcResponseEnvelope.Type) => {\n      const requestId = String(response.id);\n      const protocolError = response.error;\n      if (protocolError !== undefined) {\n        return resolvePending(requestId, ({ deferred, method }) =>\n          Deferred.fail(\n            deferred,\n            CodexError.CodexAppServerRequestError.fromProtocolError(\n              protocolError,\n              method,\n              requestId,\n            ),\n          ),\n        );\n      }\n      return resolvePending(requestId, ({ deferred }) =>\n        Deferred.succeed(deferred, response.result),\n      );\n    };\n\n    const handleRequest = (request: CodexAppServerIncomingRequest) =>\n      Queue.offer(incomingRequests, request).pipe(\n        Effect.andThen(\n          options.onRequest\n            ? options.onRequest(request).pipe(\n                Effect.matchEffect({\n                  onFailure: (error) =>\n                    respondError(\n                      request.id,\n                      CodexError.CodexAppServerRequestError.fromAppServerError(\n                        error,\n                        request.method,\n                      ),\n                    ),\n                  onSuccess: (result) => respond(request.id, result),\n                }),\n              )\n            : Effect.void,\n        ),\n        Effect.asVoid,\n      );\n\n    const handleNotification = (notification: CodexAppServerIncomingNotification) =>\n      Queue.offer(incomingNotifications, notification).pipe(\n        Effect.andThen(options.onNotification ? options.onNotification(notification) : Effect.void),\n        Effect.asVoid,\n      );\n\n    const routeMessage = (\n      message: unknown,\n    ): Effect.Effect<void, CodexError.CodexAppServerError> => {\n      if (isIncomingRequest(message)) {\n        return handleRequest(message);\n      }\n      if (isIncomingNotification(message)) {\n        return handleNotification(message);\n      }\n      if (isIncomingResponse(message)) {\n        return handleResponse(message);\n      }\n      return Effect.fail(\n        CodexError.CodexAppServerProtocolParseError.fromUnroutableMessage(message),\n      );\n    };\n\n    const handleLine = (line: string): Effect.Effect<void, CodexError.CodexAppServerError> => {\n      if (line.trim().length === 0) {\n        return Effect.void;\n      }\n      return logProtocol({\n        direction: \"incoming\",\n        stage: \"raw\",\n        payload: line,\n      }).pipe(\n        Effect.flatMap(() => decodeWireMessage(line)),\n        Effect.tap((decoded) =>\n          logProtocol({\n            direction: \"incoming\",\n            stage: \"decoded\",\n            payload: decoded,\n          }),\n        ),\n        Effect.tapErrorTag(\"CodexAppServerProtocolParseError\", (error) =>\n          logProtocol({\n            direction: \"incoming\",\n            stage: \"decode_failed\",\n            payload: {\n              operation: error.operation,\n              ...(error.method === undefined ? {} : { method: error.method }),\n              ...(error.requestId === undefined ? {} : { requestId: error.requestId }),\n              ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),\n              ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),\n              ...(error.maximumPathDepth === undefined\n                ? {}\n                : { maximumPathDepth: error.maximumPathDepth }),\n            },\n          }),\n        ),\n        Effect.flatMap(routeMessage),\n      );\n    };\n\n    yield* options.stdio.stdin.pipe(\n      Stream.decodeText(),\n      Stream.runForEach((chunk) =>\n        Ref.modify(remainder, (current) => {\n          const combined = current + chunk;\n          const lines = combined.split(\"\\n\");\n          const nextRemainder = lines.pop() ?? \"\";\n          return [lines.map((line) => line.replace(/\\r$/, \"\")), nextRemainder] as const;\n        }).pipe(Effect.flatMap((lines) => Effect.forEach(lines, handleLine, { discard: true }))),\n      ),\n      Effect.matchEffect({\n        onFailure: (error) =>\n          handleTermination(() =>\n            Effect.succeed(normalizeIncomingError(error, \"read-input-stream\")),\n          ),\n        onSuccess: () =>\n          Ref.get(remainder).pipe(\n            Effect.flatMap((line) => (line.trim().length === 0 ? Effect.void : handleLine(line))),\n            Effect.matchEffect({\n              onFailure: (error) => handleTermination(() => Effect.succeed(error)),\n              onSuccess: () =>\n                handleTermination(\n                  () =>\n                    options.terminationError ??\n                    Effect.succeed(new CodexError.CodexAppServerInputStreamEndedError({})),\n                ),\n            }),\n          ),\n      }),\n      Effect.forkScoped,\n    );\n\n    yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);\n\n    const request = (method: string, payload?: unknown) =>\n      Effect.gen(function* () {\n        const requestId = yield* Ref.modify(\n          nextRequestId,\n          (current) => [current, current + 1] as const,\n        );\n        const deferred = yield* Deferred.make<unknown, CodexError.CodexAppServerError>();\n        yield* Ref.update(pending, (current) =>\n          new Map(current).set(String(requestId), { deferred, method }),\n        );\n        yield* offerOutgoing({\n          id: requestId,\n          method,\n          ...(payload !== undefined ? { params: payload } : {}),\n        }).pipe(Effect.tapError(() => removePending(String(requestId))));\n        return yield* Deferred.await(deferred).pipe(\n          Effect.onInterrupt(() => removePending(String(requestId))),\n        );\n      });\n\n    const notify = (method: string, payload?: unknown) =>\n      offerOutgoing({\n        method,\n        ...(payload !== undefined ? { params: payload } : {}),\n      });\n\n    return {\n      incomingNotifications: Stream.fromQueue(incomingNotifications),\n      incomingRequests: Stream.fromQueue(incomingRequests),\n      request,\n      notify,\n      respond,\n      respondError,\n    } satisfies CodexAppServerPatchedProtocol;\n  },\n);\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Queue from \"effect/Queue\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport * as CodexError from \"../errors.ts\";\n\nconst encoder = new TextEncoder();\n\nexport const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>\n  Stdio.make({\n    args: Effect.succeed([]),\n    stdin: handle.stdout,\n    stdout: () =>\n      Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>\n        typeof chunk === \"string\" ? encoder.encode(chunk) : chunk,\n      ),\n    stderr: () => Sink.drain,\n  });\n\nexport const makeInMemoryStdio = Effect.fn(\"makeInMemoryStdio\")(function* () {\n  const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();\n  const output = yield* Queue.unbounded<string>();\n  const decoder = new TextDecoder();\n\n  return {\n    stdio: Stdio.make({\n      args: Effect.succeed([]),\n      stdin: Stream.fromQueue(input),\n      stdout: () =>\n        Sink.forEach((chunk: string | Uint8Array) =>\n          Queue.offer(\n            output,\n            typeof chunk === \"string\" ? chunk : decoder.decode(chunk, { stream: true }),\n          ),\n        ),\n      stderr: () => Sink.drain,\n    }),\n    input,\n    output,\n  };\n});\n\ntype ChildProcessTerminationHandle = Pick<\n  ChildProcessSpawner.ChildProcessHandle,\n  \"exitCode\" | \"pid\"\n>;\n\nexport const makeTerminationError = (\n  handle: ChildProcessTerminationHandle,\n): Effect.Effect<CodexError.CodexAppServerError> =>\n  Effect.match(handle.exitCode, {\n    onFailure: (cause) =>\n      new CodexError.CodexAppServerTransportError({\n        operation: \"read-process-exit-status\",\n        pid: handle.pid,\n        cause,\n      }),\n    onSuccess: (code) => new CodexError.CodexAppServerProcessExitedError({ code, pid: handle.pid }),\n  });\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\n\nimport * as CodexRpc from \"./_generated/meta.gen.ts\";\nimport * as CodexError from \"./errors.ts\";\nimport * as CodexProtocol from \"./protocol.ts\";\nimport {\n  decodeNotificationPayload,\n  decodeOptionalPayload,\n  encodeOptionalPayload,\n  runHandler,\n} from \"./_internal/shared.ts\";\nimport { makeChildStdio, makeTerminationError } from \"./_internal/stdio.ts\";\n\nexport interface CodexAppServerClientOptions {\n  readonly logIncoming?: boolean;\n  readonly logOutgoing?: boolean;\n  readonly logger?: (\n    event: CodexProtocol.CodexAppServerProtocolLogEvent,\n  ) => Effect.Effect<void, never>;\n}\n\ninterface CodexAppServerClientRaw {\n  readonly notifications: CodexProtocol.CodexAppServerPatchedProtocol[\"incomingNotifications\"];\n  readonly requests: CodexProtocol.CodexAppServerPatchedProtocol[\"incomingRequests\"];\n  readonly request: CodexProtocol.CodexAppServerPatchedProtocol[\"request\"];\n  readonly notify: CodexProtocol.CodexAppServerPatchedProtocol[\"notify\"];\n  readonly respond: CodexProtocol.CodexAppServerPatchedProtocol[\"respond\"];\n  readonly respondError: CodexProtocol.CodexAppServerPatchedProtocol[\"respondError\"];\n}\n\nexport class CodexAppServerClient extends Context.Service<\n  CodexAppServerClient,\n  {\n    readonly raw: CodexAppServerClientRaw;\n    readonly request: <M extends CodexRpc.ClientRequestMethod>(\n      method: M,\n      payload: CodexRpc.ClientRequestParamsByMethod[M],\n    ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError>;\n    readonly notify: <M extends CodexRpc.ClientNotificationMethod>(\n      method: M,\n      payload: CodexRpc.ClientNotificationParamsByMethod[M],\n    ) => Effect.Effect<void, CodexError.CodexAppServerError>;\n    readonly handleServerRequest: <M extends CodexRpc.ServerRequestMethod>(\n      method: M,\n      handler: (\n        payload: CodexRpc.ServerRequestParamsByMethod[M],\n      ) => Effect.Effect<\n        CodexRpc.ServerRequestResponsesByMethod[M],\n        CodexError.CodexAppServerError\n      >,\n    ) => Effect.Effect<void>;\n    readonly handleServerNotification: <M extends CodexRpc.ServerNotificationMethod>(\n      method: M,\n      handler: (\n        payload: CodexRpc.ServerNotificationParamsByMethod[M],\n      ) => Effect.Effect<void, CodexError.CodexAppServerError>,\n    ) => Effect.Effect<void>;\n    readonly handleUnknownServerRequest: (\n      handler: (\n        method: string,\n        params: unknown,\n      ) => Effect.Effect<unknown, CodexError.CodexAppServerError>,\n    ) => Effect.Effect<void>;\n    readonly handleUnknownServerNotification: (\n      handler: (\n        method: string,\n        params: unknown,\n      ) => Effect.Effect<void, CodexError.CodexAppServerError>,\n    ) => Effect.Effect<void>;\n  }\n>()(\"effect-codex-app-server/client/CodexAppServerClient\") {}\n\ntype ServerRequestHandler = (\n  payload: unknown,\n) => Effect.Effect<unknown, CodexError.CodexAppServerError>;\ntype ServerNotificationHandler = (\n  payload: unknown,\n) => Effect.Effect<void, CodexError.CodexAppServerError>;\n\nexport const make = Effect.fn(\"effect-codex-app-server/CodexAppServerClient.make\")(function* (\n  stdio: Stdio.Stdio,\n  options: CodexAppServerClientOptions = {},\n  terminationError?: Effect.Effect<CodexError.CodexAppServerError>,\n): Effect.fn.Return<CodexAppServerClient[\"Service\"], never, Scope.Scope> {\n  const requestHandlers = new Map<string, ServerRequestHandler>();\n  const notificationHandlers = new Map<string, Array<ServerNotificationHandler>>();\n  let unknownRequestHandler:\n    | ((method: string, params: unknown) => Effect.Effect<unknown, CodexError.CodexAppServerError>)\n    | undefined;\n  let unknownNotificationHandler:\n    | ((method: string, params: unknown) => Effect.Effect<void, CodexError.CodexAppServerError>)\n    | undefined;\n\n  const getServerRequestParamSchema = <M extends CodexRpc.ServerRequestMethod>(\n    method: M,\n  ):\n    | Schema.Codec<CodexRpc.ServerRequestParamsByMethod[M], CodexRpc.ServerRequestParamsByMethod[M]>\n    | undefined => CodexRpc.SERVER_REQUEST_PARAMS[method] as never;\n\n  const getServerRequestResponseSchema = <M extends CodexRpc.ServerRequestMethod>(\n    method: M,\n  ):\n    | Schema.Codec<\n        CodexRpc.ServerRequestResponsesByMethod[M],\n        CodexRpc.ServerRequestResponsesByMethod[M]\n      >\n    | undefined => CodexRpc.SERVER_REQUEST_RESPONSES[method] as never;\n\n  const getClientRequestParamSchema = <M extends CodexRpc.ClientRequestMethod>(\n    method: M,\n  ):\n    | Schema.Codec<CodexRpc.ClientRequestParamsByMethod[M], CodexRpc.ClientRequestParamsByMethod[M]>\n    | undefined => CodexRpc.CLIENT_REQUEST_PARAMS[method] as never;\n\n  const getClientRequestResponseSchema = <M extends CodexRpc.ClientRequestMethod>(\n    method: M,\n  ):\n    | Schema.Codec<\n        CodexRpc.ClientRequestResponsesByMethod[M],\n        CodexRpc.ClientRequestResponsesByMethod[M]\n      >\n    | undefined => CodexRpc.CLIENT_REQUEST_RESPONSES[method] as never;\n\n  const getClientNotificationParamSchema = <M extends CodexRpc.ClientNotificationMethod>(\n    method: M,\n  ):\n    | Schema.Codec<\n        CodexRpc.ClientNotificationParamsByMethod[M],\n        CodexRpc.ClientNotificationParamsByMethod[M]\n      >\n    | undefined => CodexRpc.CLIENT_NOTIFICATION_PARAMS[method] as never;\n\n  const dispatchNotification = (\n    notification: CodexProtocol.CodexAppServerIncomingNotification,\n  ): Effect.Effect<void, never> => {\n    const schema =\n      notification.method in CodexRpc.SERVER_NOTIFICATION_PARAMS\n        ? CodexRpc.SERVER_NOTIFICATION_PARAMS[\n            notification.method as CodexRpc.ServerNotificationMethod\n          ]\n        : undefined;\n    const handlers = notificationHandlers.get(notification.method) ?? [];\n\n    if (schema) {\n      return decodeNotificationPayload(notification.method, schema, notification.params).pipe(\n        Effect.flatMap((decoded) =>\n          Effect.forEach(handlers, (handler) => handler(decoded), { discard: true }),\n        ),\n        Effect.catch(() => Effect.void),\n      );\n    }\n\n    return unknownNotificationHandler\n      ? unknownNotificationHandler(notification.method, notification.params).pipe(\n          Effect.catch(() => Effect.void),\n        )\n      : Effect.void;\n  };\n\n  const dispatchRequest = (\n    request: CodexProtocol.CodexAppServerIncomingRequest,\n  ): Effect.Effect<unknown, CodexError.CodexAppServerError> => {\n    if (request.method in CodexRpc.SERVER_REQUEST_PARAMS) {\n      const method = request.method as CodexRpc.ServerRequestMethod;\n      const payloadSchema = getServerRequestParamSchema(method);\n      const responseSchema = getServerRequestResponseSchema(method);\n      const handler = requestHandlers.get(method);\n\n      return decodeOptionalPayload(method, payloadSchema, request.params).pipe(\n        Effect.flatMap((decoded) => runHandler(handler, decoded, method)),\n        Effect.flatMap((result) => encodeOptionalPayload(method, responseSchema, result)),\n      );\n    }\n\n    return unknownRequestHandler\n      ? unknownRequestHandler(request.method, request.params)\n      : Effect.fail(CodexError.CodexAppServerRequestError.methodNotFound(request.method));\n  };\n\n  const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({\n    stdio,\n    ...(terminationError ? { terminationError } : {}),\n    ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),\n    ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),\n    ...(options.logger ? { logger: options.logger } : {}),\n    onNotification: dispatchNotification,\n    onRequest: dispatchRequest,\n  });\n\n  const request = <M extends CodexRpc.ClientRequestMethod>(\n    method: M,\n    payload: CodexRpc.ClientRequestParamsByMethod[M],\n  ): Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexError.CodexAppServerError> =>\n    encodeOptionalPayload(method, getClientRequestParamSchema(method), payload).pipe(\n      Effect.flatMap((encoded) => transport.request(method, encoded)),\n      Effect.flatMap(\n        (\n          raw,\n        ): Effect.Effect<\n          CodexRpc.ClientRequestResponsesByMethod[M],\n          CodexError.CodexAppServerError\n        > => decodeOptionalPayload(method, getClientRequestResponseSchema(method), raw),\n      ),\n    );\n\n  const notify = <M extends CodexRpc.ClientNotificationMethod>(\n    method: M,\n    payload: CodexRpc.ClientNotificationParamsByMethod[M],\n  ) =>\n    encodeOptionalPayload(method, getClientNotificationParamSchema(method), payload).pipe(\n      Effect.flatMap((encoded) => transport.notify(method, encoded)),\n    );\n\n  return CodexAppServerClient.of({\n    raw: {\n      notifications: transport.incomingNotifications,\n      requests: transport.incomingRequests,\n      request: transport.request,\n      notify: transport.notify,\n      respond: transport.respond,\n      respondError: transport.respondError,\n    },\n    request,\n    notify,\n    handleServerRequest: (method, handler) =>\n      Effect.sync(() => {\n        requestHandlers.set(method, handler as ServerRequestHandler);\n      }),\n    handleServerNotification: (method, handler) =>\n      Effect.sync(() => {\n        const current = notificationHandlers.get(method) ?? [];\n        current.push(handler as ServerNotificationHandler);\n        notificationHandlers.set(method, current);\n      }),\n    handleUnknownServerRequest: (handler) =>\n      Effect.sync(() => {\n        unknownRequestHandler = handler;\n      }),\n    handleUnknownServerNotification: (handler) =>\n      Effect.sync(() => {\n        unknownNotificationHandler = handler;\n      }),\n  });\n});\n\nexport const layer = (\n  stdio: Stdio.Stdio,\n  options: CodexAppServerClientOptions = {},\n): Layer.Layer<CodexAppServerClient> => Layer.effect(CodexAppServerClient, make(stdio, options));\n\nexport const layerChildProcess = (\n  handle: ChildProcessSpawner.ChildProcessHandle,\n  options: CodexAppServerClientOptions = {},\n): Layer.Layer<CodexAppServerClient> =>\n  Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));\n\nconst makeChildProcessClient = Effect.fn(\n  \"effect-codex-app-server/CodexAppServerClient.makeChildProcessClient\",\n)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {\n  yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);\n  return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));\n});\n","import * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Types from \"effect/Types\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as CodexClient from \"effect-codex-app-server/client\";\nimport * as CodexSchema from \"effect-codex-app-server/schema\";\nimport * as CodexErrors from \"effect-codex-app-server/errors\";\n\nimport type {\n  CodexSettings,\n  ServerProvider,\n  ServerProviderState,\n  ModelCapabilities,\n  ProviderOptionDescriptor,\n  ServerProviderModel,\n  ServerProviderSkill,\n} from \"@t3tools/contracts\";\nimport { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from \"@t3tools/contracts\";\n\nimport { createModelCapabilities } from \"@t3tools/shared/model\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport { codexAppServerArgs, resolveCodexLaunchArgs } from \"./codexLaunchArgs.ts\";\nimport {\n  AUTH_PROBE_TIMEOUT_MS,\n  buildServerProvider,\n  type ServerProviderDraft,\n} from \"../providerSnapshot.ts\";\nimport { expandHomePath } from \"../../pathExpansion.ts\";\nimport packageJson from \"../../../package.json\" with { type: \"json\" };\nconst isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);\n\nconst CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER = \"2 seconds\" as const;\n\nconst CODEX_PRESENTATION = {\n  displayName: \"Codex\",\n  showInteractionModeToggle: true,\n} as const;\n\nexport interface CodexAppServerProviderSnapshot {\n  readonly account: CodexSchema.V2GetAccountResponse;\n  readonly version: string | undefined;\n  readonly models: ReadonlyArray<ServerProviderModel>;\n  readonly skills: ReadonlyArray<ServerProviderSkill>;\n}\n\nconst REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {\n  none: \"None\",\n  minimal: \"Minimal\",\n  low: \"Low\",\n  medium: \"Medium\",\n  high: \"High\",\n  xhigh: \"Extra High\",\n  max: \"Max\",\n  ultra: \"Ultra\",\n};\n\nconst DEFAULT_SERVICE_TIER_ID = \"default\";\nconst CURRENT_CODEX_MODELS = new Set([\"gpt-5.6-luna\", \"gpt-5.6-terra\", \"gpt-5.6-sol\"]);\n\nexport function isLegacyCodexModel(model: string): boolean {\n  return !CURRENT_CODEX_MODELS.has(model);\n}\n\nfunction reasoningEffortLabel(reasoningEffort: string): string {\n  return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;\n}\n\nfunction codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse[\"account\"]) {\n  if (!account) return undefined;\n  if (account.type === \"apiKey\") return \"OpenAI API Key\";\n  if (account.type === \"amazonBedrock\") return \"Amazon Bedrock\";\n  if (account.type !== \"chatgpt\") return undefined;\n\n  switch (account.planType) {\n    case \"free\":\n      return \"ChatGPT Free Subscription\";\n    case \"go\":\n      return \"ChatGPT Go Subscription\";\n    case \"plus\":\n      return \"ChatGPT Plus Subscription\";\n    case \"pro\":\n      return \"ChatGPT Pro 20x Subscription\";\n    case \"prolite\":\n      return \"ChatGPT Pro 5x Subscription\";\n    case \"team\":\n      return \"ChatGPT Team Subscription\";\n    case \"self_serve_business_usage_based\":\n    case \"business\":\n      return \"ChatGPT Business Subscription\";\n    case \"enterprise_cbp_usage_based\":\n    case \"enterprise\":\n      return \"ChatGPT Enterprise Subscription\";\n    case \"edu\":\n      return \"ChatGPT Edu Subscription\";\n    case \"unknown\":\n      return \"ChatGPT Subscription\";\n    default:\n      account.planType satisfies never;\n      return undefined;\n  }\n}\n\nfunction codexAccountEmail(account: CodexSchema.V2GetAccountResponse[\"account\"]) {\n  if (!account || account.type !== \"chatgpt\") return undefined;\n  return account.email;\n}\n\nexport function mapCodexModelCapabilities(\n  model: CodexSchema.V2ModelListResponse__Model,\n): ModelCapabilities {\n  const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>\n    reasoningEffort === model.defaultReasoningEffort\n      ? {\n          id: reasoningEffort,\n          label: reasoningEffortLabel(reasoningEffort),\n          isDefault: true,\n        }\n      : {\n          id: reasoningEffort,\n          label: reasoningEffortLabel(reasoningEffort),\n        },\n  );\n  const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;\n  const serviceTiers =\n    model.serviceTiers && model.serviceTiers.length > 0\n      ? model.serviceTiers\n      : (model.additionalSpeedTiers ?? []).map((id) => ({\n          id,\n          name: id === \"fast\" ? \"Fast\" : id,\n          description: \"\",\n        }));\n  const catalogDefaultServiceTier = serviceTiers.some(\n    (tier) => tier.id === model.defaultServiceTier,\n  )\n    ? model.defaultServiceTier\n    : null;\n  const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;\n  const optionDescriptors: ProviderOptionDescriptor[] = [];\n\n  if (reasoningOptions.length > 0) {\n    optionDescriptors.push({\n      id: \"reasoningEffort\",\n      label: \"Reasoning\",\n      type: \"select\",\n      options: reasoningOptions,\n      ...(defaultReasoning ? { currentValue: defaultReasoning } : {}),\n    });\n  }\n  if (serviceTiers.length > 0) {\n    optionDescriptors.push({\n      id: \"serviceTier\",\n      label: \"Service Tier\",\n      type: \"select\",\n      options: [\n        {\n          id: DEFAULT_SERVICE_TIER_ID,\n          label: \"Standard\",\n          ...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),\n        },\n        ...serviceTiers.map((tier) => ({\n          id: tier.id,\n          label: tier.name,\n          ...(tier.description ? { description: tier.description } : {}),\n          ...(defaultServiceTier === tier.id ? { isDefault: true } : {}),\n        })),\n      ],\n      currentValue: defaultServiceTier,\n    });\n  }\n\n  return createModelCapabilities({\n    optionDescriptors,\n  });\n}\n\nconst toDisplayName = (model: CodexSchema.V2ModelListResponse__Model): string => {\n  // Capitalize 'gpt' to 'GPT-' and capitalize any letter following a dash\n  return model.displayName\n    .replace(/^gpt/i, \"GPT\") // Handle start with 'gpt' or 'GPT'\n    .replace(/-([a-z])/g, (_, c) => \"-\" + c.toUpperCase());\n};\n\nfunction parseCodexModelListResponse(\n  response: CodexSchema.V2ModelListResponse,\n): ReadonlyArray<ServerProviderModel> {\n  return response.data.map((model) => ({\n    slug: model.model,\n    name: toDisplayName(model),\n    isCustom: false,\n    ...(model.isDefault ? { isDefault: true } : {}),\n    ...(isLegacyCodexModel(model.model) ? { isLegacy: true } : {}),\n    capabilities: mapCodexModelCapabilities(model),\n  }));\n}\n\n/**\n * Prefer our own default-model ranking when one of the preferred slugs is in\n * the live catalog; otherwise keep whatever Codex itself flagged as default.\n */\nexport function applyPreferredCodexDefaultModel(\n  models: ReadonlyArray<ServerProviderModel>,\n): ReadonlyArray<ServerProviderModel> {\n  const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>\n    models.some((model) => model.slug === slug && !model.isCustom),\n  );\n  if (!preferredSlug) {\n    return models;\n  }\n  return models.map((model) => {\n    if (model.slug === preferredSlug) {\n      return model.isDefault ? model : { ...model, isDefault: true };\n    }\n    if (!model.isDefault) {\n      return model;\n    }\n    const { isDefault: _isDefault, ...rest } = model;\n    return rest;\n  });\n}\n\nfunction appendCustomCodexModels(\n  models: ReadonlyArray<ServerProviderModel>,\n  customModels: ReadonlyArray<string>,\n): ReadonlyArray<ServerProviderModel> {\n  if (customModels.length === 0) {\n    return models;\n  }\n\n  const seen = new Set(models.map((model) => model.slug));\n  const fallbackCapabilities = models.find((model) => model.capabilities)?.capabilities ?? null;\n  const customEntries: ServerProviderModel[] = [];\n  for (const rawModel of customModels) {\n    const slug = rawModel.trim();\n    if (!slug || seen.has(slug)) {\n      continue;\n    }\n    seen.add(slug);\n    customEntries.push({\n      slug,\n      name: slug,\n      isCustom: true,\n      capabilities: fallbackCapabilities,\n    });\n  }\n  return customEntries.length === 0 ? models : [...models, ...customEntries];\n}\n\nfunction parseCodexSkillsListResponse(\n  response: CodexSchema.V2SkillsListResponse,\n  cwd: string,\n): ReadonlyArray<ServerProviderSkill> {\n  const matchingEntry = response.data.find((entry) => entry.cwd === cwd);\n  const skills = matchingEntry\n    ? matchingEntry.skills\n    : response.data.flatMap((entry) => entry.skills);\n\n  return skills.map((skill) => {\n    const shortDescription =\n      skill.shortDescription ?? skill.interface?.shortDescription ?? undefined;\n\n    const parsedSkill: Types.Mutable<ServerProviderSkill> = {\n      name: skill.name,\n      path: skill.path,\n      enabled: skill.enabled,\n    };\n\n    if (skill.description) {\n      parsedSkill.description = skill.description;\n    }\n    if (skill.scope) {\n      parsedSkill.scope = skill.scope;\n    }\n    if (skill.interface?.displayName) {\n      parsedSkill.displayName = skill.interface.displayName;\n    }\n    if (shortDescription) {\n      parsedSkill.shortDescription = shortDescription;\n    }\n\n    return parsedSkill;\n  });\n}\n\nconst requestAllCodexModels = Effect.fn(\"requestAllCodexModels\")(function* (\n  client: CodexClient.CodexAppServerClient[\"Service\"],\n) {\n  const models: ServerProviderModel[] = [];\n  let cursor: string | null | undefined = undefined;\n\n  do {\n    const response: CodexSchema.V2ModelListResponse = yield* client.request(\n      \"model/list\",\n      cursor ? { cursor } : {},\n    );\n    models.push(...parseCodexModelListResponse(response));\n    cursor = response.nextCursor;\n  } while (cursor);\n\n  return models;\n});\n\nexport function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {\n  return {\n    clientInfo: {\n      name: \"t3code_desktop\",\n      title: \"Synaptic Code Desktop\",\n      version: packageJson.version,\n    },\n    capabilities: {\n      experimentalApi: true,\n    },\n  };\n}\n\nconst probeCodexAppServerProvider = Effect.fn(\"probeCodexAppServerProvider\")(function* (input: {\n  readonly binaryPath: string;\n  readonly homePath?: string;\n  readonly launchArgs?: string;\n  readonly cwd: string;\n  readonly customModels?: ReadonlyArray<string>;\n  readonly environment?: NodeJS.ProcessEnv;\n}) {\n  // `~` is not shell-expanded when env vars are set via `child_process.spawn`,\n  // so `CODEX_HOME=~/.codex_work` would reach codex verbatim and trip\n  // \"CODEX_HOME points to '~/.codex_work', but that path does not exist\".\n  // Expand here for parity with `CodexTextGeneration`/`CodexSessionRuntime`.\n  const resolvedHomePath = input.homePath ? expandHomePath(input.homePath) : undefined;\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const environment = {\n    ...input.environment,\n    ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),\n  };\n  const spawnCommand = yield* resolveSpawnCommand(\n    input.binaryPath,\n    codexAppServerArgs(input.launchArgs),\n    {\n      env: environment,\n      extendEnv: true,\n    },\n  );\n  const child = yield* spawner\n    .spawn(\n      ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        cwd: input.cwd,\n        env: environment,\n        extendEnv: true,\n        forceKillAfter: CODEX_APP_SERVER_PROBE_FORCE_KILL_AFTER,\n        shell: spawnCommand.shell,\n      }),\n    )\n    .pipe(\n      Effect.mapError(\n        (cause) =>\n          new CodexErrors.CodexAppServerSpawnError({\n            command: `${input.binaryPath} app-server`,\n            cause,\n          }),\n      ),\n    );\n  const clientContext = yield* Layer.build(CodexClient.layerChildProcess(child));\n  const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(\n    Effect.provide(clientContext),\n  );\n\n  const initialize = yield* client.request(\"initialize\", {\n    clientInfo: {\n      name: \"t3code_desktop\",\n      title: \"Synaptic Code Desktop\",\n      version: \"0.1.0\",\n    },\n    capabilities: {\n      experimentalApi: true,\n    },\n  });\n  yield* client.notify(\"initialized\", undefined);\n\n  // Extract the version string after the first '/' in userAgent, up to the next space or the end\n  const versionMatch = initialize.userAgent.match(/\\/([^\\s]+)/);\n  const version = versionMatch ? versionMatch[1] : undefined;\n\n  const accountResponse = yield* client.request(\"account/read\", {});\n  if (!accountResponse.account && accountResponse.requiresOpenaiAuth) {\n    return {\n      account: accountResponse,\n      version,\n      models: appendCustomCodexModels([], input.customModels ?? []),\n      skills: [],\n    } satisfies CodexAppServerProviderSnapshot;\n  }\n\n  const [skillsResponse, models] = yield* Effect.all(\n    [\n      client.request(\"skills/list\", {\n        cwds: [input.cwd],\n      }),\n      requestAllCodexModels(client),\n    ],\n    { concurrency: \"unbounded\" },\n  );\n\n  return {\n    account: accountResponse,\n    version,\n    models: applyPreferredCodexDefaultModel(\n      appendCustomCodexModels(models, input.customModels ?? []),\n    ),\n    skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),\n  } satisfies CodexAppServerProviderSnapshot;\n});\n\nconst emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider[\"models\"] => {\n  const models = new Set<string>();\n  for (const model of codexSettings.customModels) {\n    const trimmed = model.trim();\n    if (trimmed.length > 0) {\n      models.add(trimmed);\n    }\n  }\n  return Array.from(models, (model) => ({\n    slug: model,\n    name: model,\n    isCustom: true,\n    capabilities: null,\n  }));\n};\n\nconst makePendingCodexProvider = (\n  codexSettings: CodexSettings,\n): Effect.Effect<ServerProviderDraft> =>\n  Effect.gen(function* () {\n    const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);\n    const models = emptyCodexModelsFromSettings(codexSettings);\n\n    if (!codexSettings.enabled) {\n      return buildServerProvider({\n        presentation: CODEX_PRESENTATION,\n        enabled: false,\n        checkedAt,\n        models,\n        skills: [],\n        probe: {\n          installed: false,\n          version: null,\n          status: \"warning\",\n          auth: { status: \"unknown\" },\n          message: \"Codex is disabled in Synaptic Code settings.\",\n        },\n      });\n    }\n\n    return buildServerProvider({\n      presentation: CODEX_PRESENTATION,\n      enabled: true,\n      checkedAt,\n      models,\n      skills: [],\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Codex provider status has not been checked in this session yet.\",\n      },\n    });\n  });\n\nfunction accountProbeStatus(account: CodexAppServerProviderSnapshot[\"account\"]): {\n  readonly status: Exclude<ServerProviderState, \"disabled\">;\n  readonly auth: ServerProvider[\"auth\"];\n  readonly message?: string;\n} {\n  const authLabel = codexAccountAuthLabel(account.account);\n  const authEmail = codexAccountEmail(account.account);\n  const auth = {\n    status: account.account ? (\"authenticated\" as const) : (\"unknown\" as const),\n    ...(account.account?.type ? { type: account.account?.type } : {}),\n    ...(authLabel ? { label: authLabel } : {}),\n    ...(authEmail ? { email: authEmail } : {}),\n  } satisfies ServerProvider[\"auth\"];\n\n  if (account.account) {\n    return { status: \"ready\", auth };\n  }\n\n  if (account.requiresOpenaiAuth) {\n    return {\n      status: \"error\",\n      auth: { status: \"unauthenticated\" },\n      message: \"Codex CLI is not authenticated. Run `codex login` and try again.\",\n    };\n  }\n\n  return { status: \"ready\", auth };\n}\n\nexport const checkCodexProviderStatus = Effect.fn(\"checkCodexProviderStatus\")(function* (\n  codexSettings: CodexSettings,\n  probe: (input: {\n    readonly binaryPath: string;\n    readonly homePath?: string;\n    readonly launchArgs?: string;\n    readonly cwd: string;\n    readonly customModels: ReadonlyArray<string>;\n    readonly environment?: NodeJS.ProcessEnv;\n  }) => Effect.Effect<\n    CodexAppServerProviderSnapshot,\n    CodexErrors.CodexAppServerError,\n    ChildProcessSpawner.ChildProcessSpawner | Scope.Scope\n  > = probeCodexAppServerProvider,\n  environment?: NodeJS.ProcessEnv,\n): Effect.fn.Return<\n  ServerProviderDraft,\n  ServerSettingsError,\n  ChildProcessSpawner.ChildProcessSpawner\n> {\n  const resolvedEnvironment = environment ?? process.env;\n  const checkedAt = DateTime.formatIso(yield* DateTime.now);\n  const emptyModels = emptyCodexModelsFromSettings(codexSettings);\n\n  if (!codexSettings.enabled) {\n    return buildServerProvider({\n      presentation: CODEX_PRESENTATION,\n      enabled: false,\n      checkedAt,\n      models: emptyModels,\n      skills: [],\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Codex is disabled in Synaptic Code settings.\",\n      },\n    });\n  }\n\n  const probeResult = yield* probe({\n    binaryPath: codexSettings.binaryPath,\n    homePath: codexSettings.homePath,\n    launchArgs: resolveCodexLaunchArgs(codexSettings.launchArgs, resolvedEnvironment),\n    cwd: process.cwd(),\n    customModels: codexSettings.customModels,\n    environment: resolvedEnvironment,\n  }).pipe(\n    Effect.scoped,\n    Effect.timeoutOption(Duration.millis(AUTH_PROBE_TIMEOUT_MS)),\n    Effect.result,\n  );\n\n  if (Result.isFailure(probeResult)) {\n    const error = probeResult.failure;\n    const installed = !isCodexAppServerSpawnError(error);\n    return buildServerProvider({\n      presentation: CODEX_PRESENTATION,\n      enabled: codexSettings.enabled,\n      checkedAt,\n      models: emptyModels,\n      skills: [],\n      probe: {\n        installed,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: installed\n          ? `Codex app-server provider probe failed: ${error.message}.`\n          : \"Codex CLI (`codex`) is not installed or not on PATH.\",\n      },\n    });\n  }\n\n  if (Option.isNone(probeResult.success)) {\n    return buildServerProvider({\n      presentation: CODEX_PRESENTATION,\n      enabled: codexSettings.enabled,\n      checkedAt,\n      models: emptyModels,\n      skills: [],\n      probe: {\n        installed: true,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: \"Timed out while checking Codex app-server provider status.\",\n      },\n    });\n  }\n\n  const snapshot = probeResult.success.value;\n  const accountStatus = accountProbeStatus(snapshot.account);\n\n  return buildServerProvider({\n    presentation: CODEX_PRESENTATION,\n    enabled: codexSettings.enabled,\n    checkedAt,\n    models: snapshot.models,\n    skills: snapshot.skills,\n    probe: {\n      installed: true,\n      version: snapshot.version ?? null,\n      status: accountStatus.status,\n      auth: accountStatus.auth,\n      ...(accountStatus.message ? { message: accountStatus.message } : {}),\n    },\n  });\n});\n\n// NOTE: the singleton `CodexProviderLive` Layer has been removed as part of\n// the per-instance-driver refactor. `CodexDriver.create()` builds a managed\n// snapshot per instance (each with its own `CodexSettings`) and hands the\n// resulting `ServerProviderShape` back as `ProviderInstance.snapshot`.\n//\n// The `makePendingCodexProvider` and `checkCodexProviderStatus` helpers are\n// re-exported for use by `CodexDriver`.\nexport { makePendingCodexProvider };\n","import type { ProviderInteractionMode } from \"@t3tools/contracts\";\n\nconst SYNAPTIC_CODE_BROWSER_TOOL_INSTRUCTIONS = `\n\n## Synaptic Code collaborative browser\n\nYou are running inside Synaptic Code. The \\`synaptic-code\\` MCP server is the product-native collaborative browser shared with the user. When it exposes \\`preview_*\\` tools, prefer those tools for browser navigation, inspection, interaction, screenshots, and recordings.\n\nFor browser work, first call \\`preview_status\\`. If no automation-capable preview is attached, call \\`preview_open\\` before concluding that the browser is unavailable. Then use \\`preview_navigate\\`, \\`preview_snapshot\\`, and the focused interaction tools. Prefer snapshot-provided locators over coordinates.\n\nDo not switch to global browser skills, Chrome, Node REPL browser automation, standalone Playwright, or agent-browser merely because the preview is initially closed or a first call fails. Use an alternative browser system only when the T3 preview tools are absent, the user explicitly requests another browser, or \\`preview_open\\` returns an explicit unsupported/unavailable error. A failed T3 preview tool call should be inspected and retried with corrected arguments when the error is actionable.\n`;\n\nexport const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)\n\nYou work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.\n\n## Mode rules (strict)\n\nYou are in **Plan Mode** until a developer message explicitly ends it.\n\nPlan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.\n\n## Plan Mode vs update_plan tool\n\nPlan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \\`<proposed_plan>\\` block.\n\nSeparately, \\`update_plan\\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \\`update_plan\\` in Plan mode, it will return an error.\n\n## Execution vs. mutation in Plan Mode\n\nYou may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.\n\n### Allowed (non-mutating, plan-improving)\n\nActions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:\n\n* Reading or searching files, configs, schemas, types, manifests, and docs\n* Static analysis, inspection, and repo exploration\n* Dry-run style commands when they do not edit repo-tracked files\n* Tests, builds, or checks that may write to caches or build artifacts (for example, \\`target/\\`, \\`.cache/\\`, or snapshots) so long as they do not edit repo-tracked files\n\n### Not allowed (mutating, plan-executing)\n\nActions that implement the plan or change repo-tracked state. Examples:\n\n* Editing or writing files\n* Running formatters or linters that rewrite files\n* Applying patches, migrations, or codegen that updates repo-tracked files\n* Side-effectful commands whose purpose is to carry out the plan rather than refine it\n\nWhen in doubt: if the action would reasonably be described as \"doing the work\" rather than \"planning the work,\" do not do it.\n\n## PHASE 1 - Ground in the environment (explore first, ask second)\n\nBegin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.\n\nBefore asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.\n\nException: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.\n\nDo not ask questions that can be answered from the repo or system (for example, \"where is this struct?\" or \"which UI component should we use?\" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.\n\n## PHASE 2 - Intent chat (what they actually want)\n\n* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.\n* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.\n\n## PHASE 3 - Implementation chat (what/how we'll build)\n\n* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.\n\n## Asking questions\n\nCritical rules:\n\n* Strongly prefer using the \\`request_user_input\\` tool to ask any questions.\n* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.\n* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.\n\nYou SHOULD ask many questions, but each question must:\n\n* materially change the spec/plan, OR\n* confirm/lock an assumption, OR\n* choose between meaningful tradeoffs.\n* not be answerable by non-mutating commands.\n\nUse the \\`request_user_input\\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.\n\n## Two kinds of unknowns (treat differently)\n\n1. **Discoverable facts** (repo/system truth): explore first.\n\n   * Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).\n   * Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.\n   * If asking, present concrete candidates (paths/service names) + recommend one.\n   * Never ask questions you can answer from your environment (e.g., \"where is this struct\").\n\n2. **Preferences/tradeoffs** (not discoverable): ask early.\n\n   * These are intent or implementation preferences that cannot be derived from exploration.\n   * Provide 2-4 mutually exclusive options + a recommended default.\n   * If unanswered, proceed with the recommended option and record it as an assumption in the final plan.\n\n## Finalization rule\n\nOnly output the final plan when it is decision complete and leaves no decisions to the implementer.\n\nWhen you present the official plan, wrap it in a \\`<proposed_plan>\\` block so the client can render it specially:\n\n1) The opening tag must be on its own line.\n2) Start the plan content on the next line (no text on the same line as the tag).\n3) The closing tag must be on its own line.\n4) Use Markdown inside the block.\n5) Keep the tags exactly as \\`<proposed_plan>\\` and \\`</proposed_plan>\\` (do not translate or rename them), even if the plan content is in another language.\n\nExample:\n\n<proposed_plan>\nplan content\n</proposed_plan>\n\nplan content should be human and agent digestible. The final plan must be plan-only and include:\n\n* A clear title\n* A brief summary section\n* Important changes or additions to public APIs/interfaces/types\n* Test cases and scenarios\n* Explicit assumptions and defaults chosen where needed\n\nDo not ask \"should I proceed?\" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \\`<proposed_plan>\\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.\n\nOnly produce at most one \\`<proposed_plan>\\` block per turn, and only when you are presenting a complete spec.\n${SYNAPTIC_CODE_BROWSER_TOOL_INSTRUCTIONS}\n</collaboration_mode>`;\n\nexport const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default\n\nYou are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.\n\nYour active mode changes only when new developer instructions with a different \\`<collaboration_mode>...</collaboration_mode>\\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.\n\n## request_user_input availability\n\nThe \\`request_user_input\\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.\n\nIn Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.\n${SYNAPTIC_CODE_BROWSER_TOOL_INSTRUCTIONS}\n</collaboration_mode>`;\n\nexport interface CodexRuntimeInfo {\n  readonly model: string;\n  readonly reasoningEffort: string;\n}\n\n// Values come from trusted config, but keep the block single-line regardless.\nfunction toSingleLine(value: string): string {\n  return value.replaceAll(/\\s+/g, \" \").trim();\n}\n\nexport function buildCodexDeveloperInstructions(\n  interactionMode: ProviderInteractionMode,\n  runtime: CodexRuntimeInfo,\n): string {\n  const base =\n    interactionMode === \"plan\"\n      ? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS\n      : CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS;\n  return `${base}\n\n<runtime_info>In case you're asked: you are running in Synaptic Code through the Codex harness, as ${toSingleLine(runtime.model)} with ${toSingleLine(runtime.reasoningEffort)} reasoning effort. No need to mention this otherwise.</runtime_info>`;\n}\n","import {\n  ApprovalRequestId,\n  DEFAULT_MODEL,\n  EventId,\n  ProviderDriverKind,\n  ProviderItemId,\n  type ProviderInstanceId,\n  type ProviderApprovalDecision,\n  type ProviderEvent,\n  type ProviderInteractionMode,\n  type ProviderRequestKind,\n  type ProviderSession,\n  type ProviderTurnStartResult,\n  type ProviderUserInputAnswers,\n  RuntimeMode,\n  ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\nimport { normalizeModelSlug } from \"@t3tools/shared/model\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport * as CodexClient from \"effect-codex-app-server/client\";\nimport * as CodexErrors from \"effect-codex-app-server/errors\";\nimport * as CodexRpc from \"effect-codex-app-server/rpc\";\nimport * as EffectCodexSchema from \"effect-codex-app-server/schema\";\n\nimport { buildCodexInitializeParams } from \"./CodexProvider.ts\";\nimport { codexSessionAppServerArgs } from \"./codexLaunchArgs.ts\";\nimport { expandHomePath } from \"../../pathExpansion.ts\";\nimport { buildCodexDeveloperInstructions } from \"../CodexDeveloperInstructions.ts\";\nconst decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse);\n\nconst PROVIDER = ProviderDriverKind.make(\"codex\");\n\nconst ANSI_ESCAPE_CHAR = String.fromCharCode(27);\nconst ANSI_ESCAPE_REGEX = new RegExp(`${ANSI_ESCAPE_CHAR}\\\\[[0-9;]*m`, \"g\");\nconst CODEX_STDERR_LOG_REGEX =\n  /^\\d{4}-\\d{2}-\\d{2}T\\S+\\s+(TRACE|DEBUG|INFO|WARN|ERROR)\\s+\\S+:\\s+(.*)$/;\nconst BENIGN_ERROR_LOG_SNIPPETS = [\n  \"state db missing rollout path for thread\",\n  \"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back\",\n];\nconst CODEX_APP_SERVER_FORCE_KILL_AFTER = \"2 seconds\" as const;\nconst RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [\n  \"not found\",\n  \"missing thread\",\n  \"no such thread\",\n  \"unknown thread\",\n  \"does not exist\",\n];\n\nexport function hasConfiguredMcpServer(appServerArgs: ReadonlyArray<string> | undefined): boolean {\n  return appServerArgs?.some((argument) => argument.includes(\"mcp_servers.\")) === true;\n}\n\nexport const CodexResumeCursorSchema = Schema.Struct({\n  threadId: Schema.String,\n});\nconst CodexUserInputAnswerObject = Schema.Struct({\n  answers: Schema.Array(Schema.String),\n});\nconst isCodexResumeCursorSchema = Schema.is(CodexResumeCursorSchema);\nconst isCodexUserInputAnswerObject = Schema.is(CodexUserInputAnswerObject);\n\n// TODO: Verify `packages/effect-codex-app-server/scripts/generate.ts` so the generated\n// `V2TurnStartParams` schema includes `collaborationMode` directly.\nconst CodexTurnStartParamsWithCollaborationMode = EffectCodexSchema.V2TurnStartParams.pipe(\n  Schema.fieldsAssign({\n    collaborationMode: Schema.optionalKey(EffectCodexSchema.V2TurnStartParams__CollaborationMode),\n  }),\n);\nconst decodeCodexTurnStartParamsWithCollaborationMode = Schema.decodeUnknownEffect(\n  CodexTurnStartParamsWithCollaborationMode,\n);\n\nexport type CodexTurnStartParamsWithCollaborationMode =\n  typeof CodexTurnStartParamsWithCollaborationMode.Type;\n\nexport type CodexResumeCursor = typeof CodexResumeCursorSchema.Type;\ntype CodexServiceTier = NonNullable<EffectCodexSchema.V2ThreadStartParams[\"serviceTier\"]>;\ntype CodexThreadItem =\n  | EffectCodexSchema.V2ThreadReadResponse[\"thread\"][\"turns\"][number][\"items\"][number]\n  | EffectCodexSchema.V2ThreadRollbackResponse[\"thread\"][\"turns\"][number][\"items\"][number];\n\nexport interface CodexSessionRuntimeOptions {\n  readonly threadId: ThreadId;\n  readonly providerInstanceId?: ProviderInstanceId;\n  readonly binaryPath: string;\n  readonly homePath?: string;\n  readonly launchArgs?: string;\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly cwd: string;\n  readonly runtimeMode: RuntimeMode;\n  readonly model?: string;\n  readonly serviceTier?: CodexServiceTier | undefined;\n  readonly resumeCursor?: CodexResumeCursor;\n  readonly appServerArgs?: ReadonlyArray<string>;\n}\n\nexport interface CodexSessionRuntimeSendTurnInput {\n  readonly input?: string;\n  readonly attachments?: ReadonlyArray<{\n    readonly type: \"image\";\n    readonly url: string;\n  }>;\n  readonly model?: string;\n  readonly serviceTier?: CodexServiceTier | undefined;\n  readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort | undefined;\n  readonly interactionMode?: ProviderInteractionMode;\n}\n\nexport interface CodexThreadTurnSnapshot {\n  readonly id: TurnId;\n  readonly items: ReadonlyArray<CodexThreadItem>;\n}\n\nexport interface CodexThreadSnapshot {\n  readonly threadId: string;\n  readonly turns: ReadonlyArray<CodexThreadTurnSnapshot>;\n}\n\nexport interface CodexSessionRuntimeShape {\n  readonly start: () => Effect.Effect<ProviderSession, CodexSessionRuntimeError>;\n  readonly getSession: Effect.Effect<ProviderSession>;\n  readonly sendTurn: (\n    input: CodexSessionRuntimeSendTurnInput,\n  ) => Effect.Effect<ProviderTurnStartResult, CodexSessionRuntimeError>;\n  readonly interruptTurn: (turnId?: TurnId) => Effect.Effect<void, CodexSessionRuntimeError>;\n  readonly readThread: Effect.Effect<CodexThreadSnapshot, CodexSessionRuntimeError>;\n  readonly rollbackThread: (\n    numTurns: number,\n  ) => Effect.Effect<CodexThreadSnapshot, CodexSessionRuntimeError>;\n  readonly respondToRequest: (\n    requestId: ApprovalRequestId,\n    decision: ProviderApprovalDecision,\n  ) => Effect.Effect<void, CodexSessionRuntimeError>;\n  readonly respondToUserInput: (\n    requestId: ApprovalRequestId,\n    answers: ProviderUserInputAnswers,\n  ) => Effect.Effect<void, CodexSessionRuntimeError>;\n  readonly events: Stream.Stream<ProviderEvent, never>;\n  readonly close: Effect.Effect<void>;\n}\n\nexport type CodexSessionRuntimeError =\n  | CodexErrors.CodexAppServerError\n  | CodexSessionRuntimePendingApprovalNotFoundError\n  | CodexSessionRuntimePendingUserInputNotFoundError\n  | CodexSessionRuntimeInvalidUserInputAnswersError\n  | CodexSessionRuntimeThreadIdMissingError;\n\nexport class CodexSessionRuntimePendingApprovalNotFoundError extends Schema.TaggedErrorClass<CodexSessionRuntimePendingApprovalNotFoundError>()(\n  \"CodexSessionRuntimePendingApprovalNotFoundError\",\n  {\n    requestId: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Unknown pending Codex approval request: ${this.requestId}`;\n  }\n}\n\nexport class CodexSessionRuntimePendingUserInputNotFoundError extends Schema.TaggedErrorClass<CodexSessionRuntimePendingUserInputNotFoundError>()(\n  \"CodexSessionRuntimePendingUserInputNotFoundError\",\n  {\n    requestId: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Unknown pending Codex user input request: ${this.requestId}`;\n  }\n}\n\nexport class CodexSessionRuntimeInvalidUserInputAnswersError extends Schema.TaggedErrorClass<CodexSessionRuntimeInvalidUserInputAnswersError>()(\n  \"CodexSessionRuntimeInvalidUserInputAnswersError\",\n  {\n    questionId: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Invalid Codex user input answers for question '${this.questionId}'`;\n  }\n}\n\nexport class CodexSessionRuntimeThreadIdMissingError extends Schema.TaggedErrorClass<CodexSessionRuntimeThreadIdMissingError>()(\n  \"CodexSessionRuntimeThreadIdMissingError\",\n  {\n    threadId: Schema.String,\n  },\n) {\n  override get message(): string {\n    return `Codex session is missing a provider thread id for ${this.threadId}`;\n  }\n}\n\ninterface PendingApproval {\n  readonly requestId: ApprovalRequestId;\n  readonly jsonRpcId: string;\n  readonly requestKind: ProviderRequestKind;\n  readonly turnId: TurnId | undefined;\n  readonly itemId: ProviderItemId | undefined;\n  readonly decision: Deferred.Deferred<ProviderApprovalDecision>;\n}\n\ninterface ApprovalCorrelation {\n  readonly requestId: ApprovalRequestId;\n  readonly requestKind: ProviderRequestKind;\n  readonly turnId: TurnId | undefined;\n  readonly itemId: ProviderItemId | undefined;\n}\n\ninterface PendingUserInput {\n  readonly requestId: ApprovalRequestId;\n  readonly turnId: TurnId | undefined;\n  readonly itemId: ProviderItemId | undefined;\n  readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;\n}\n\ntype CodexServerNotification = {\n  readonly [M in CodexRpc.ServerNotificationMethod]: {\n    readonly method: M;\n    readonly params: CodexRpc.ServerNotificationParamsByMethod[M];\n  };\n}[CodexRpc.ServerNotificationMethod];\n\nfunction makeCodexServerNotification<M extends CodexRpc.ServerNotificationMethod>(\n  method: M,\n  params: CodexRpc.ServerNotificationParamsByMethod[M],\n): CodexServerNotification {\n  return { method, params } as CodexServerNotification;\n}\n\nfunction normalizeCodexModelSlug(\n  model: string | undefined | null,\n  preferredId?: string,\n): string | undefined {\n  const normalized = normalizeModelSlug(model);\n  if (!normalized) {\n    return undefined;\n  }\n  if (preferredId?.endsWith(\"-codex\") && preferredId !== normalized) {\n    return preferredId;\n  }\n  return normalized;\n}\n\nfunction readResumeCursorThreadId(\n  resumeCursor: ProviderSession[\"resumeCursor\"],\n): string | undefined {\n  return isCodexResumeCursorSchema(resumeCursor) ? resumeCursor.threadId : undefined;\n}\n\nfunction runtimeModeToThreadConfig(input: RuntimeMode): {\n  readonly approvalPolicy: EffectCodexSchema.V2ThreadStartParams__AskForApproval;\n  readonly sandbox: EffectCodexSchema.V2ThreadStartParams__SandboxMode;\n  // Always explicit: omitting the field on resume keeps the thread's previous\n  // reviewer, which would leave auto_review sticky after switching modes.\n  readonly approvalsReviewer: EffectCodexSchema.V2ThreadStartParams__ApprovalsReviewer;\n} {\n  switch (input) {\n    case \"approval-required\":\n      return {\n        approvalPolicy: \"untrusted\",\n        sandbox: \"read-only\",\n        approvalsReviewer: \"user\",\n      };\n    case \"auto-accept-edits\":\n      return {\n        approvalPolicy: \"on-request\",\n        sandbox: \"workspace-write\",\n        approvalsReviewer: \"user\",\n      };\n    case \"auto\":\n      return {\n        approvalPolicy: \"on-request\",\n        sandbox: \"workspace-write\",\n        approvalsReviewer: \"auto_review\",\n      };\n    case \"full-access\":\n    default:\n      return {\n        approvalPolicy: \"never\",\n        sandbox: \"danger-full-access\",\n        approvalsReviewer: \"user\",\n      };\n  }\n}\n\nfunction buildThreadStartParams(input: {\n  readonly cwd: string;\n  readonly runtimeMode: RuntimeMode;\n  readonly model: string | undefined;\n  readonly serviceTier: CodexServiceTier | undefined;\n}): EffectCodexSchema.V2ThreadStartParams {\n  const config = runtimeModeToThreadConfig(input.runtimeMode);\n  return {\n    cwd: input.cwd,\n    approvalPolicy: config.approvalPolicy,\n    sandbox: config.sandbox,\n    approvalsReviewer: config.approvalsReviewer,\n    ...(input.model ? { model: input.model } : {}),\n    ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),\n  };\n}\n\nfunction runtimeModeToTurnSandboxPolicy(\n  input: RuntimeMode,\n): EffectCodexSchema.V2TurnStartParams__SandboxPolicy {\n  switch (input) {\n    case \"approval-required\":\n      return {\n        type: \"readOnly\",\n      };\n    case \"auto-accept-edits\":\n    case \"auto\":\n      return {\n        type: \"workspaceWrite\",\n      };\n    case \"full-access\":\n    default:\n      return {\n        type: \"dangerFullAccess\",\n      };\n  }\n}\n\nfunction buildCodexCollaborationMode(input: {\n  readonly interactionMode?: ProviderInteractionMode;\n  readonly model?: string;\n  readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;\n}): EffectCodexSchema.V2TurnStartParams__CollaborationMode | undefined {\n  if (input.interactionMode === undefined) {\n    return undefined;\n  }\n  const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL;\n  const reasoningEffort = input.effort ?? \"medium\";\n  return {\n    mode: input.interactionMode,\n    settings: {\n      model,\n      reasoning_effort: reasoningEffort,\n      developer_instructions: buildCodexDeveloperInstructions(input.interactionMode, {\n        model,\n        reasoningEffort,\n      }),\n    },\n  };\n}\n\nexport function buildTurnStartParams(input: {\n  readonly threadId: string;\n  readonly runtimeMode: RuntimeMode;\n  readonly prompt?: string;\n  readonly attachments?: ReadonlyArray<{\n    readonly type: \"image\";\n    readonly url: string;\n  }>;\n  readonly model?: string;\n  readonly serviceTier?: CodexServiceTier;\n  readonly effort?: EffectCodexSchema.V2TurnStartParams__ReasoningEffort;\n  readonly interactionMode?: ProviderInteractionMode;\n}): Effect.Effect<\n  CodexTurnStartParamsWithCollaborationMode,\n  CodexErrors.CodexAppServerProtocolParseError\n> {\n  const turnInput: Array<EffectCodexSchema.V2TurnStartParams__UserInput> = [];\n  if (input.prompt) {\n    turnInput.push({\n      type: \"text\",\n      text: input.prompt,\n    });\n  }\n  for (const attachment of input.attachments ?? []) {\n    turnInput.push(attachment);\n  }\n\n  const config = runtimeModeToThreadConfig(input.runtimeMode);\n  const collaborationMode = buildCodexCollaborationMode({\n    ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),\n    ...(input.model ? { model: input.model } : {}),\n    ...(input.effort ? { effort: input.effort } : {}),\n  });\n\n  return decodeCodexTurnStartParamsWithCollaborationMode({\n    threadId: input.threadId,\n    input: turnInput,\n    approvalPolicy: config.approvalPolicy,\n    approvalsReviewer: config.approvalsReviewer,\n    sandboxPolicy: runtimeModeToTurnSandboxPolicy(input.runtimeMode),\n    ...(input.model ? { model: input.model } : {}),\n    ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),\n    ...(input.effort ? { effort: input.effort } : {}),\n    ...(collaborationMode ? { collaborationMode } : {}),\n  }).pipe(\n    Effect.mapError((cause) =>\n      CodexErrors.CodexAppServerProtocolParseError.fromSchemaError(\n        \"decode-request-payload\",\n        cause,\n        { method: \"turn/start\" },\n      ),\n    ),\n  );\n}\n\nfunction classifyCodexStderrLine(rawLine: string): { readonly message: string } | null {\n  const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, \"\").trim();\n  if (!line) {\n    return null;\n  }\n\n  const match = line.match(CODEX_STDERR_LOG_REGEX);\n  if (match) {\n    const level = match[1];\n    if (level && level !== \"ERROR\") {\n      return null;\n    }\n    if (BENIGN_ERROR_LOG_SNIPPETS.some((snippet) => line.includes(snippet))) {\n      return null;\n    }\n  }\n\n  return { message: line };\n}\n\nexport function isRecoverableThreadResumeError(error: unknown): boolean {\n  const message = (error instanceof Error ? error.message : String(error)).toLowerCase();\n  if (!message.includes(\"thread\")) {\n    return false;\n  }\n  return RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS.some((snippet) => message.includes(snippet));\n}\n\ntype CodexThreadOpenResponse =\n  | CodexRpc.ClientRequestResponsesByMethod[\"thread/start\"]\n  | CodexRpc.ClientRequestResponsesByMethod[\"thread/resume\"];\n\ntype CodexThreadOpenMethod = \"thread/start\" | \"thread/resume\";\n\ninterface CodexThreadOpenClient {\n  readonly request: <M extends CodexThreadOpenMethod>(\n    method: M,\n    payload: CodexRpc.ClientRequestParamsByMethod[M],\n  ) => Effect.Effect<CodexRpc.ClientRequestResponsesByMethod[M], CodexErrors.CodexAppServerError>;\n}\n\nexport const openCodexThread = (input: {\n  readonly client: CodexThreadOpenClient;\n  readonly threadId: ThreadId;\n  readonly runtimeMode: RuntimeMode;\n  readonly cwd: string;\n  readonly requestedModel: string | undefined;\n  readonly serviceTier: CodexServiceTier | undefined;\n  readonly resumeThreadId: string | undefined;\n}): Effect.Effect<CodexThreadOpenResponse, CodexErrors.CodexAppServerError> => {\n  const resumeThreadId = input.resumeThreadId;\n  const startParams = buildThreadStartParams({\n    cwd: input.cwd,\n    runtimeMode: input.runtimeMode,\n    model: input.requestedModel,\n    serviceTier: input.serviceTier,\n  });\n\n  if (resumeThreadId === undefined) {\n    return input.client.request(\"thread/start\", startParams);\n  }\n\n  return input.client\n    .request(\"thread/resume\", {\n      threadId: resumeThreadId,\n      ...startParams,\n    })\n    .pipe(\n      Effect.catchIf(isRecoverableThreadResumeError, (error) =>\n        Effect.logWarning(\"codex app-server thread resume fell back to fresh start\", {\n          threadId: input.threadId,\n          requestedRuntimeMode: input.runtimeMode,\n          resumeThreadId,\n          recoverable: true,\n          cause: error,\n        }).pipe(Effect.andThen(input.client.request(\"thread/start\", startParams))),\n      ),\n    );\n};\n\nfunction readNotificationThreadId(notification: CodexServerNotification): string | undefined {\n  switch (notification.method) {\n    case \"thread/started\":\n      return notification.params.thread.id;\n    case \"error\":\n    case \"thread/status/changed\":\n    case \"thread/archived\":\n    case \"thread/unarchived\":\n    case \"thread/closed\":\n    case \"thread/name/updated\":\n    case \"thread/tokenUsage/updated\":\n    case \"turn/started\":\n    case \"hook/started\":\n    case \"turn/completed\":\n    case \"hook/completed\":\n    case \"turn/diff/updated\":\n    case \"turn/plan/updated\":\n    case \"item/started\":\n    case \"item/autoApprovalReview/started\":\n    case \"item/autoApprovalReview/completed\":\n    case \"item/completed\":\n    case \"rawResponseItem/completed\":\n    case \"item/agentMessage/delta\":\n    case \"item/plan/delta\":\n    case \"item/commandExecution/outputDelta\":\n    case \"item/commandExecution/terminalInteraction\":\n    case \"item/fileChange/outputDelta\":\n    case \"item/fileChange/patchUpdated\":\n    case \"serverRequest/resolved\":\n    case \"item/mcpToolCall/progress\":\n    case \"item/reasoning/summaryTextDelta\":\n    case \"item/reasoning/summaryPartAdded\":\n    case \"item/reasoning/textDelta\":\n    case \"thread/compacted\":\n    case \"thread/realtime/started\":\n    case \"thread/realtime/itemAdded\":\n    case \"thread/realtime/transcript/delta\":\n    case \"thread/realtime/transcript/done\":\n    case \"thread/realtime/outputAudio/delta\":\n    case \"thread/realtime/sdp\":\n    case \"thread/realtime/error\":\n    case \"thread/realtime/closed\":\n      return notification.params.threadId;\n    default:\n      return undefined;\n  }\n}\n\nfunction readRouteFields(notification: CodexServerNotification): {\n  readonly turnId: TurnId | undefined;\n  readonly itemId: ProviderItemId | undefined;\n} {\n  switch (notification.method) {\n    case \"thread/started\":\n      return {\n        turnId: undefined,\n        itemId: undefined,\n      };\n    case \"turn/started\":\n    case \"turn/completed\":\n      return {\n        turnId: TurnId.make(notification.params.turn.id),\n        itemId: undefined,\n      };\n    case \"error\":\n      return {\n        turnId: TurnId.make(notification.params.turnId),\n        itemId: undefined,\n      };\n    case \"turn/diff/updated\":\n    case \"turn/plan/updated\":\n      return {\n        turnId: TurnId.make(notification.params.turnId),\n        itemId: undefined,\n      };\n    case \"serverRequest/resolved\":\n      return {\n        turnId: undefined,\n        itemId: undefined,\n      };\n    case \"item/started\":\n    case \"item/completed\":\n      return {\n        turnId: TurnId.make(notification.params.turnId),\n        itemId: ProviderItemId.make(notification.params.item.id),\n      };\n    case \"item/agentMessage/delta\":\n    case \"item/plan/delta\":\n    case \"item/commandExecution/outputDelta\":\n    case \"item/commandExecution/terminalInteraction\":\n    case \"item/fileChange/outputDelta\":\n    case \"item/fileChange/patchUpdated\":\n    case \"item/reasoning/summaryTextDelta\":\n    case \"item/reasoning/summaryPartAdded\":\n    case \"item/reasoning/textDelta\":\n      return {\n        turnId: TurnId.make(notification.params.turnId),\n        itemId: ProviderItemId.make(notification.params.itemId),\n      };\n    default:\n      return {\n        turnId: undefined,\n        itemId: undefined,\n      };\n  }\n}\n\n/**\n * Native collab child-agent tracking (multi-agent v2). Under v2 subagents are\n * full app-server threads: identity arrives on `thread/started` with\n * source.subAgent.thread_spawn, lifecycle on `subAgentActivity` items and the\n * child thread's own turn/status/tokenUsage notifications. The runtime\n * registers children from those explicit signals, intercepts their\n * notifications before parent-timeline mapping, and re-emits them as\n * synthetic `collabAgent/*` provider events the adapter turns into task.*\n * runtime events (timelineBypass keeps them out of the parent chat).\n *\n * WIP, probe-gated: registration is deliberately explicit-signals-only. The\n * spec's \"provisionally treat unknown foreign thread ids as v2 children\" rule\n * needs a live wire capture of the packaged binary before it lands — blind\n * capture risks eating unrelated traffic. Until then a child whose first\n * notification precedes registration passes through as today (no regression\n * vs main, which passes everything through).\n */\ninterface CollabChildAgentState {\n  readonly agentThreadId: string;\n  readonly nickname: string | undefined;\n  readonly role: string | undefined;\n  readonly agentPath: string | undefined;\n  readonly depth: number | undefined;\n  readonly parentThreadId: string | undefined;\n  /**\n   * Parent canonical turn active when the child registered. Stamped on every\n   * synthetic collabAgent/* event so clients can batch a fleet by its spawn\n   * turn — without it, separate fleets in one thread collapsed into a single\n   * \"direct:no-turn\" CTA (review finding).\n   */\n  readonly spawnTurnId: TurnId | undefined;\n}\n\nfunction readThreadSpawnSource(thread: { readonly source: unknown }):\n  | {\n      nickname: string | undefined;\n      role: string | undefined;\n      agentPath: string | undefined;\n      depth: number | undefined;\n      parentThreadId: string | undefined;\n    }\n  | undefined {\n  const source = thread.source;\n  if (typeof source !== \"object\" || source === null || !(\"subAgent\" in source)) {\n    return undefined;\n  }\n  const subAgent = (source as { subAgent: unknown }).subAgent;\n  if (typeof subAgent !== \"object\" || subAgent === null || !(\"thread_spawn\" in subAgent)) {\n    return undefined;\n  }\n  const spawn = (subAgent as { thread_spawn: unknown }).thread_spawn;\n  if (typeof spawn !== \"object\" || spawn === null) {\n    return undefined;\n  }\n  const record = spawn as Record<string, unknown>;\n  return {\n    nickname: typeof record.agent_nickname === \"string\" ? record.agent_nickname : undefined,\n    role: typeof record.agent_role === \"string\" ? record.agent_role : undefined,\n    agentPath: typeof record.agent_path === \"string\" ? record.agent_path : undefined,\n    depth: typeof record.depth === \"number\" ? record.depth : undefined,\n    parentThreadId:\n      typeof record.parent_thread_id === \"string\" ? record.parent_thread_id : undefined,\n  };\n}\n\nfunction rememberCollabReceiverTurns(\n  collabReceiverTurns: Map<string, TurnId>,\n  notification: CodexServerNotification,\n  parentTurnId: TurnId | undefined,\n): void {\n  if (!parentTurnId) {\n    return;\n  }\n\n  if (notification.method !== \"item/started\" && notification.method !== \"item/completed\") {\n    return;\n  }\n\n  if (notification.params.item.type !== \"collabAgentToolCall\") {\n    return;\n  }\n\n  for (const receiverThreadId of notification.params.item.receiverThreadIds) {\n    collabReceiverTurns.set(receiverThreadId, parentTurnId);\n  }\n}\n\nfunction shouldSuppressChildConversationNotification(\n  method: CodexRpc.ServerNotificationMethod,\n): boolean {\n  return (\n    method === \"thread/started\" ||\n    method === \"thread/status/changed\" ||\n    method === \"thread/archived\" ||\n    method === \"thread/unarchived\" ||\n    method === \"thread/closed\" ||\n    method === \"thread/compacted\" ||\n    method === \"thread/name/updated\" ||\n    method === \"thread/tokenUsage/updated\" ||\n    method === \"turn/started\" ||\n    method === \"turn/completed\" ||\n    method === \"turn/plan/updated\" ||\n    method === \"item/plan/delta\"\n  );\n}\n\n/**\n * How a notification addressed to a REGISTERED child thread is handled.\n *\n * Exported and pure so the routing table can be asserted against captured\n * wire traces (see codexMultiAgentWire.json) rather than only read.\n *\n * - \"agent-event\": map to a synthetic collabAgent/* event (Agents surface).\n * - \"parent\": pass through to the parent path — it carries state the parent\n *   still owns (approval correlation cleanup).\n * - \"drop\": genuine child chatter with no parent meaning (deltas, name and\n *   plan updates).\n *\n * Default is \"drop\" ONLY for the enumerated chatter; anything unrecognized\n * routes to \"parent\" so new wire methods surface instead of vanishing\n * (two shipped bugs came from a catch-all that swallowed everything).\n */\nexport type CodexChildNotificationRoute = \"agent-event\" | \"parent\" | \"drop\";\n\nconst CHILD_AGENT_EVENT_METHODS: ReadonlySet<string> = new Set([\n  \"turn/started\",\n  \"turn/completed\",\n  \"thread/status/changed\",\n  \"thread/tokenUsage/updated\",\n  \"item/started\",\n  \"item/completed\",\n  \"thread/closed\",\n  \"error\",\n]);\n\nconst CHILD_CHATTER_METHODS: ReadonlySet<string> = new Set([\n  \"item/agentMessage/delta\",\n  \"item/reasoning/textDelta\",\n  \"item/reasoning/summaryTextDelta\",\n  \"item/reasoning/summaryPartAdded\",\n  \"item/commandExecution/outputDelta\",\n  \"item/fileChange/outputDelta\",\n  \"item/fileChange/patchUpdated\",\n  \"item/plan/delta\",\n  \"turn/plan/updated\",\n  \"turn/diff/updated\",\n  \"thread/name/updated\",\n  \"thread/settings/updated\",\n  \"rawResponseItem/completed\",\n  // Child-owned thread lifecycle: the parent adapter maps these onto the\n  // PARENT thread (archived/compacted state), so a child compacting would\n  // rewrite the parent. Mirrors the v1 suppressor list — dropping them is\n  // the pre-existing behavior for collab children (review finding).\n  \"thread/archived\",\n  \"thread/unarchived\",\n  \"thread/compacted\",\n  // Registration path 1 handles a child's first thread/started; a repeat\n  // must not reach the parent (it would restart the parent's thread state).\n  \"thread/started\",\n]);\n\nexport function routeCodexChildNotification(method: string): CodexChildNotificationRoute {\n  if (CHILD_AGENT_EVENT_METHODS.has(method)) {\n    return \"agent-event\";\n  }\n  if (CHILD_CHATTER_METHODS.has(method)) {\n    return \"drop\";\n  }\n  // Unknown or parent-owned (serverRequest/resolved, approvals, …).\n  return \"parent\";\n}\n\nfunction toCodexUserInputAnswer(\n  questionId: string,\n  value: ProviderUserInputAnswers[string],\n): Effect.Effect<\n  EffectCodexSchema.ToolRequestUserInputResponse__ToolRequestUserInputAnswer,\n  CodexSessionRuntimeInvalidUserInputAnswersError\n> {\n  if (typeof value === \"string\") {\n    return Effect.succeed({ answers: [value] });\n  }\n  if (Array.isArray(value)) {\n    const answers = value.filter((entry): entry is string => typeof entry === \"string\");\n    return Effect.succeed({ answers });\n  }\n  if (isCodexUserInputAnswerObject(value)) {\n    return Effect.succeed({ answers: value.answers });\n  }\n  return Effect.fail(new CodexSessionRuntimeInvalidUserInputAnswersError({ questionId }));\n}\n\nfunction toCodexUserInputAnswers(\n  answers: ProviderUserInputAnswers,\n): Effect.Effect<\n  EffectCodexSchema.ToolRequestUserInputResponse[\"answers\"],\n  CodexSessionRuntimeInvalidUserInputAnswersError\n> {\n  return Effect.forEach(\n    Object.entries(answers),\n    ([questionId, value]) =>\n      toCodexUserInputAnswer(questionId, value).pipe(\n        Effect.map((answer) => [questionId, answer] as const),\n      ),\n    { concurrency: 1 },\n  ).pipe(Effect.map((entries) => Object.fromEntries(entries)));\n}\n\nfunction currentProviderThreadId(session: ProviderSession): string | undefined {\n  return readResumeCursorThreadId(session.resumeCursor);\n}\n\nfunction updateSession(\n  sessionRef: Ref.Ref<ProviderSession>,\n  updates: Partial<ProviderSession>,\n): Effect.Effect<void> {\n  return Effect.gen(function* () {\n    const updatedAt = DateTime.formatIso(yield* DateTime.now);\n    yield* Ref.update(sessionRef, (session) => ({\n      ...session,\n      ...updates,\n      updatedAt,\n    }));\n  });\n}\n\nfunction parseThreadSnapshot(\n  response: EffectCodexSchema.V2ThreadReadResponse | EffectCodexSchema.V2ThreadRollbackResponse,\n): CodexThreadSnapshot {\n  return {\n    threadId: response.thread.id,\n    turns: response.thread.turns.map((turn) => ({\n      id: TurnId.make(turn.id),\n      items: turn.items,\n    })),\n  };\n}\n\nexport const makeCodexSessionRuntime = (\n  options: CodexSessionRuntimeOptions,\n): Effect.Effect<\n  CodexSessionRuntimeShape,\n  CodexErrors.CodexAppServerError,\n  ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope\n> =>\n  Effect.gen(function* () {\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const runtimeScope = yield* Scope.Scope;\n    const crypto = yield* Crypto.Crypto;\n    const events = yield* Queue.unbounded<ProviderEvent>();\n    const pendingApprovalsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingApproval>());\n    const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());\n    const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());\n    const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());\n    const collabChildAgentsRef = yield* Ref.make(new Map<string, CollabChildAgentState>());\n    /** Child provider-thread id → its currently running provider turn id. */\n    const collabChildLiveTurnsRef = yield* Ref.make(new Map<string, string>());\n    const closedRef = yield* Ref.make(false);\n\n    // `~` is not shell-expanded when env vars are set via\n    // `child_process.spawn`; `expandHomePath` lets a configured\n    // `CODEX_HOME=~/.codex_work` reach codex as an absolute path.\n    const resolvedHomePath = options.homePath ? expandHomePath(options.homePath) : undefined;\n    const env = {\n      ...options.environment,\n      ...(resolvedHomePath ? { CODEX_HOME: resolvedHomePath } : {}),\n    };\n    const extendEnv = options.environment === undefined;\n    const appServerArgs = codexSessionAppServerArgs(options.appServerArgs, options.launchArgs);\n    const spawnCommand = yield* resolveSpawnCommand(options.binaryPath, appServerArgs, {\n      env,\n      extendEnv,\n    });\n    const child = yield* spawner\n      .spawn(\n        ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n          cwd: options.cwd,\n          env,\n          extendEnv,\n          forceKillAfter: CODEX_APP_SERVER_FORCE_KILL_AFTER,\n          shell: spawnCommand.shell,\n        }),\n      )\n      .pipe(\n        Effect.provideService(Scope.Scope, runtimeScope),\n        Effect.mapError(\n          (cause) =>\n            new CodexErrors.CodexAppServerSpawnError({\n              command: `${options.binaryPath} app-server`,\n              cause,\n            }),\n        ),\n      );\n\n    const clientContext = yield* CodexClient.layerChildProcess(child).pipe(\n      Layer.build,\n      Effect.provideService(Scope.Scope, runtimeScope),\n    );\n    const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe(\n      Effect.provide(clientContext),\n    );\n    const serverNotifications = yield* Queue.unbounded<CodexServerNotification>();\n    const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n    const randomUUIDv4 = (purpose: CodexErrors.CodexAppServerIdentifierPurpose) =>\n      crypto.randomUUIDv4.pipe(\n        Effect.mapError(\n          (cause) =>\n            new CodexErrors.CodexAppServerIdentifierGenerationError({\n              purpose,\n              cause,\n            }),\n        ),\n      );\n\n    const sessionCreatedAt = yield* nowIso;\n    const initialSession = {\n      provider: PROVIDER,\n      ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),\n      status: \"connecting\",\n      runtimeMode: options.runtimeMode,\n      cwd: options.cwd,\n      ...(options.model ? { model: options.model } : {}),\n      threadId: options.threadId,\n      ...(options.resumeCursor !== undefined ? { resumeCursor: options.resumeCursor } : {}),\n      createdAt: sessionCreatedAt,\n      updatedAt: sessionCreatedAt,\n    } satisfies ProviderSession;\n    const sessionRef = yield* Ref.make<ProviderSession>(initialSession);\n    const offerEvent = (event: ProviderEvent) => Queue.offer(events, event).pipe(Effect.asVoid);\n\n    const emitEvent = (event: Omit<ProviderEvent, \"id\" | \"provider\" | \"createdAt\">) =>\n      Effect.gen(function* () {\n        const id = yield* randomUUIDv4(\"provider-event\");\n        return yield* offerEvent({\n          id: EventId.make(id),\n          provider: PROVIDER,\n          ...(options.providerInstanceId ? { providerInstanceId: options.providerInstanceId } : {}),\n          createdAt: yield* nowIso,\n          ...event,\n        });\n      });\n    const emitSessionEvent = (method: string, message: string) =>\n      emitEvent({\n        kind: \"session\",\n        threadId: options.threadId,\n        method,\n        message,\n      });\n\n    const settlePendingApprovals = (decision: ProviderApprovalDecision) =>\n      Ref.get(pendingApprovalsRef).pipe(\n        Effect.flatMap((pendingApprovals) =>\n          Effect.forEach(\n            Array.from(pendingApprovals.values()),\n            (pendingApproval) =>\n              Deferred.succeed(pendingApproval.decision, decision).pipe(Effect.ignore),\n            { discard: true },\n          ),\n        ),\n      );\n\n    const settlePendingUserInputs = (answers: ProviderUserInputAnswers) =>\n      Ref.get(pendingUserInputsRef).pipe(\n        Effect.flatMap((pendingUserInputs) =>\n          Effect.forEach(\n            Array.from(pendingUserInputs.values()),\n            (pendingUserInput) =>\n              Deferred.succeed(pendingUserInput.answers, answers).pipe(Effect.ignore),\n            { discard: true },\n          ),\n        ),\n      );\n\n    /**\n     * Registers v2 collab children and re-emits their notifications as\n     * synthetic `collabAgent/*` events for the adapter's task.* synthesis.\n     * Returns true when the notification was fully handled (must not reach\n     * parent-timeline mapping).\n     */\n    const interceptCollabChildNotification = (notification: CodexServerNotification) =>\n      Effect.gen(function* () {\n        // Registration path 1: child thread announces itself with a\n        // subAgent thread_spawn source.\n        if (notification.method === \"thread/started\") {\n          const thread = notification.params.thread;\n          const spawn = readThreadSpawnSource(thread);\n          if (!spawn) {\n            return false;\n          }\n          // Merge with any subAgentActivity registration that got here\n          // first. spawnTurnId is REGISTRATION-time-only on both paths: for\n          // an already-known child we keep its value (set or unset) — a\n          // later thread/started during an unrelated parent turn must not\n          // backfill that turn as the spawn batch, which would stamp an old\n          // child onto a new fleet's CTA (review finding). Only a genuinely\n          // new registration captures the current turn.\n          const existingChild = (yield* Ref.get(collabChildAgentsRef)).get(thread.id);\n          const spawnTurnId = existingChild\n            ? existingChild.spawnTurnId\n            : ((yield* Ref.get(sessionRef)).activeTurnId ?? undefined);\n          const state: CollabChildAgentState = {\n            agentThreadId: thread.id,\n            nickname: spawn.nickname ?? thread.agentNickname ?? existingChild?.nickname,\n            role: spawn.role ?? thread.agentRole ?? existingChild?.role,\n            agentPath: spawn.agentPath ?? existingChild?.agentPath,\n            depth: spawn.depth ?? existingChild?.depth,\n            parentThreadId:\n              spawn.parentThreadId ?? thread.parentThreadId ?? existingChild?.parentThreadId,\n            spawnTurnId,\n          };\n          yield* Ref.update(collabChildAgentsRef, (current) => {\n            const next = new Map(current);\n            next.set(thread.id, state);\n            return next;\n          });\n          yield* emitEvent({\n            kind: \"notification\",\n            threadId: options.threadId,\n            method: \"collabAgent/started\",\n            ...(state.spawnTurnId ? { turnId: state.spawnTurnId } : {}),\n            payload: {\n              agentThreadId: state.agentThreadId,\n              ...(state.nickname ? { nickname: state.nickname } : {}),\n              ...(state.role ? { role: state.role } : {}),\n              ...(state.agentPath ? { agentPath: state.agentPath } : {}),\n              ...(state.depth !== undefined ? { depth: state.depth } : {}),\n              ...(state.parentThreadId ? { parentThreadId: state.parentThreadId } : {}),\n            },\n          });\n          return true;\n        }\n\n        // Registration path 2: parent-side subAgentActivity item names the\n        // child thread (may arrive before or after thread/started).\n        if (\n          (notification.method === \"item/started\" || notification.method === \"item/completed\") &&\n          notification.params.item.type === \"subAgentActivity\"\n        ) {\n          const item = notification.params.item;\n          // Never register the session's ROOT thread as its own child. The\n          // wire emits subAgentActivity {agentPath: \"/root\", interacted}\n          // about the root during collab runs; registering it intercepted\n          // every subsequent root notification — including the final\n          // assistant message and turn/completed — so the thread hung\n          // \"working\" after all subagents finished (live-probe finding).\n          const rootProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));\n          if (\n            item.agentThreadId === rootProviderThreadId ||\n            item.agentPath === \"/root\" ||\n            item.agentPath === \"/\"\n          ) {\n            return false;\n          }\n          const activitySpawnTurnId = (yield* Ref.get(sessionRef)).activeTurnId ?? undefined;\n          yield* Ref.update(collabChildAgentsRef, (current) => {\n            const existing = current.get(item.agentThreadId);\n            const next = new Map(current);\n            // Merge-late semantics: when thread/started registered first, a\n            // later subAgentActivity still carries the real agentPath (and a\n            // derived nickname) — fill missing fields, never clobber known\n            // ones. spawnTurnId is registration-time-only: for an already\n            // registered child, a later activity during an UNRELATED turn\n            // must not backfill that turn as the spawn batch (review\n            // finding); an unset spawn turn stays unset.\n            next.set(item.agentThreadId, {\n              agentThreadId: item.agentThreadId,\n              nickname:\n                existing?.nickname ??\n                item.agentPath.split(\"/\").findLast((segment) => segment.length > 0),\n              role: existing?.role,\n              agentPath: existing?.agentPath ?? item.agentPath,\n              depth: existing?.depth,\n              parentThreadId: existing?.parentThreadId,\n              spawnTurnId: existing ? existing.spawnTurnId : activitySpawnTurnId,\n            });\n            return next;\n          });\n          const registeredChild = (yield* Ref.get(collabChildAgentsRef)).get(item.agentThreadId);\n          yield* emitEvent({\n            kind: \"notification\",\n            threadId: options.threadId,\n            method: \"collabAgent/activity\",\n            ...(registeredChild?.spawnTurnId ? { turnId: registeredChild.spawnTurnId } : {}),\n            payload: {\n              agentThreadId: item.agentThreadId,\n              agentPath: item.agentPath,\n              activityKind: item.kind,\n            },\n          });\n          return true;\n        }\n\n        // Interception: notifications addressed to a registered child thread\n        // become agent-scoped synthetic events instead of parent chatter.\n        const providerConversationId = readNotificationThreadId(notification);\n        if (!providerConversationId) {\n          return false;\n        }\n        // Belt-and-braces: the root thread's traffic must never be\n        // intercepted, whatever the registry says.\n        const interceptRootId = currentProviderThreadId(yield* Ref.get(sessionRef));\n        if (providerConversationId === interceptRootId) {\n          return false;\n        }\n        const children = yield* Ref.get(collabChildAgentsRef);\n        const child = children.get(providerConversationId);\n        if (!child) {\n          return false;\n        }\n        const childIdentity = {\n          agentThreadId: child.agentThreadId,\n          ...(child.nickname ? { nickname: child.nickname } : {}),\n          ...(child.role ? { role: child.role } : {}),\n          ...(child.agentPath ? { agentPath: child.agentPath } : {}),\n        };\n        switch (notification.method) {\n          case \"turn/started\": {\n            const childTurnId =\n              typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === \"string\"\n                ? ((notification.params as { turn: { id: string } }).turn.id as string)\n                : undefined;\n            if (childTurnId) {\n              yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n                const next = new Map(current);\n                next.set(child.agentThreadId, childTurnId);\n                return next;\n              });\n            }\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/turnStarted\",\n              payload: childIdentity,\n            });\n            return true;\n          }\n          case \"turn/completed\":\n            yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n              const next = new Map(current);\n              next.delete(child.agentThreadId);\n              return next;\n            });\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/turnCompleted\",\n              payload: {\n                ...childIdentity,\n                turn: notification.params.turn,\n              },\n            });\n            return true;\n          case \"thread/status/changed\":\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/statusChanged\",\n              payload: {\n                ...childIdentity,\n                status: notification.params.status,\n              },\n            });\n            return true;\n          case \"thread/tokenUsage/updated\":\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/tokenUsage\",\n              payload: {\n                ...childIdentity,\n                tokenUsage: notification.params.tokenUsage,\n              },\n            });\n            return true;\n          case \"item/started\":\n          case \"item/completed\":\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/item\",\n              payload: {\n                ...childIdentity,\n                item: notification.params.item,\n              },\n            });\n            return true;\n          case \"thread/closed\":\n            // The child is gone: drop its live-turn entry so a later Stop\n            // doesn't waste a turn/interrupt RPC on a closed thread before\n            // reaching the parent (review finding).\n            yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n              const next = new Map(current);\n              next.delete(child.agentThreadId);\n              return next;\n            });\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/closed\",\n              payload: childIdentity,\n            });\n            return true;\n          case \"error\": {\n            // A child error must surface as a failed agent, not vanish into\n            // the default swallow (review finding: the child stayed\n            // \"running\" forever). Retryable errors (willRetry) keep the\n            // child RUNNING and interruptible — mirroring the root error\n            // handler; settling it would orphan a still-live child from\n            // Stop (review finding). Terminal errors clean up the live turn\n            // like thread/closed and reuse the statusChanged systemError\n            // path.\n            const willRetry = (notification.params as { willRetry?: boolean }).willRetry === true;\n            if (willRetry) {\n              return true;\n            }\n            yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n              const next = new Map(current);\n              next.delete(child.agentThreadId);\n              return next;\n            });\n            yield* emitEvent({\n              kind: \"notification\",\n              threadId: options.threadId,\n              ...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),\n              method: \"collabAgent/statusChanged\",\n              payload: {\n                ...childIdentity,\n                status: { type: \"systemError\" },\n              },\n            });\n            return true;\n          }\n          default:\n            // Routing table decides (single source of truth, asserted\n            // against captured wire traces): enumerated chatter is dropped,\n            // everything else — including methods this build has never seen\n            // — falls through to the parent path rather than vanishing.\n            return routeCodexChildNotification(notification.method) === \"drop\";\n        }\n      });\n\n    const handleRawNotification = (notification: CodexServerNotification) =>\n      Effect.gen(function* () {\n        const payload = notification.params;\n        const route = readRouteFields(notification);\n        const collabReceiverTurns = yield* Ref.get(collabReceiverTurnsRef);\n        const childParentTurnId = (() => {\n          const providerConversationId = readNotificationThreadId(notification);\n          return providerConversationId\n            ? collabReceiverTurns.get(providerConversationId)\n            : undefined;\n        })();\n\n        rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);\n        // Interception FIRST: a registered v2 child is usually also in the\n        // receiver-turn map (collabAgentToolCall.receiverThreadIds), and the\n        // legacy suppressor below would drop its lifecycle before it could\n        // become synthetic collabAgent events (review finding). The\n        // suppressor still covers UNREGISTERED children.\n        if (yield* interceptCollabChildNotification(notification)) {\n          yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);\n          return;\n        }\n\n        // Suppression applies to receiver-map children (v1) AND to any\n        // conversation that is not the root thread. The live capture\n        // (codexMultiAgentWire.json) shows a child's thread/status/changed\n        // arriving BEFORE anything registers the child — pre-registration\n        // lifecycle must not reach the parent path, where the adapter maps\n        // thread/* onto parent session state. Root-id-known guard keeps the\n        // root's own early notifications flowing during session open.\n        const suppressRootId = currentProviderThreadId(yield* Ref.get(sessionRef));\n        const foreignConversation = (() => {\n          const providerConversationId = readNotificationThreadId(notification);\n          return (\n            providerConversationId !== undefined &&\n            suppressRootId !== undefined &&\n            providerConversationId !== suppressRootId\n          );\n        })();\n        if (\n          (childParentTurnId !== undefined || foreignConversation) &&\n          shouldSuppressChildConversationNotification(notification.method)\n        ) {\n          // Stop-everything must not depend on registration timing: a\n          // child's turn/started can arrive before the subAgentActivity that\n          // registers it (captured ordering), and suppressing it without\n          // remembering the live turn would leave that child running after\n          // Stop (review finding). Track live turns for ANY foreign\n          // conversation; interrupts are best-effort per child, so a\n          // false-positive entry costs one ignored RPC at worst.\n          const foreignThreadId = readNotificationThreadId(notification);\n          if (foreignThreadId !== undefined) {\n            if (notification.method === \"turn/started\") {\n              const foreignTurnId =\n                typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === \"string\"\n                  ? (notification.params as { turn: { id: string } }).turn.id\n                  : undefined;\n              if (foreignTurnId) {\n                yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n                  const next = new Map(current);\n                  next.set(foreignThreadId, foreignTurnId);\n                  return next;\n                });\n              }\n            } else if (\n              notification.method === \"turn/completed\" ||\n              notification.method === \"thread/closed\"\n            ) {\n              yield* Ref.update(collabChildLiveTurnsRef, (current) => {\n                const next = new Map(current);\n                next.delete(foreignThreadId);\n                return next;\n              });\n            }\n          }\n          yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);\n          return;\n        }\n\n        let requestId: ApprovalRequestId | undefined;\n        let requestKind: ProviderRequestKind | undefined;\n        let turnId = childParentTurnId ?? route.turnId;\n        let itemId = route.itemId;\n\n        if (notification.method === \"serverRequest/resolved\") {\n          const rawRequestId =\n            typeof notification.params.requestId === \"string\"\n              ? notification.params.requestId\n              : String(notification.params.requestId);\n          const correlation = rawRequestId\n            ? (yield* Ref.get(approvalCorrelationsRef)).get(rawRequestId)\n            : undefined;\n          if (correlation) {\n            requestId = correlation.requestId;\n            requestKind = correlation.requestKind;\n            turnId = correlation.turnId ?? turnId;\n            itemId = correlation.itemId ?? itemId;\n            yield* Ref.update(approvalCorrelationsRef, (current) => {\n              const next = new Map(current);\n              next.delete(rawRequestId);\n              return next;\n            });\n          }\n        }\n\n        yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);\n        yield* emitEvent({\n          kind: \"notification\",\n          threadId: options.threadId,\n          method: notification.method,\n          ...(turnId ? { turnId } : {}),\n          ...(itemId ? { itemId } : {}),\n          ...(requestId ? { requestId } : {}),\n          ...(requestKind ? { requestKind } : {}),\n          ...(notification.method === \"item/agentMessage/delta\"\n            ? { textDelta: notification.params.delta }\n            : {}),\n          ...(payload !== undefined ? { payload } : {}),\n        });\n      });\n\n    const currentSessionProviderThreadId = Effect.map(Ref.get(sessionRef), currentProviderThreadId);\n\n    yield* client.handleServerNotification(\"thread/started\", (payload) =>\n      currentSessionProviderThreadId.pipe(\n        Effect.flatMap((providerThreadId) => {\n          if (providerThreadId && payload.thread.id !== providerThreadId) {\n            return Effect.void;\n          }\n          return updateSession(sessionRef, {\n            resumeCursor: { threadId: payload.thread.id },\n          });\n        }),\n      ),\n    );\n\n    yield* client.handleServerNotification(\"turn/started\", (payload) =>\n      currentSessionProviderThreadId.pipe(\n        Effect.flatMap((providerThreadId) => {\n          if (providerThreadId && payload.threadId !== providerThreadId) {\n            return Effect.void;\n          }\n          return updateSession(sessionRef, {\n            status: \"running\",\n            activeTurnId: TurnId.make(payload.turn.id),\n          });\n        }),\n      ),\n    );\n\n    yield* client.handleServerNotification(\"turn/completed\", (payload) =>\n      currentSessionProviderThreadId.pipe(\n        Effect.flatMap((providerThreadId) => {\n          if (providerThreadId && payload.threadId !== providerThreadId) {\n            return Effect.void;\n          }\n          const lastError =\n            payload.turn.status === \"failed\" && \"error\" in payload.turn && payload.turn.error\n              ? payload.turn.error.message\n              : undefined;\n          return updateSession(sessionRef, {\n            status: payload.turn.status === \"failed\" ? \"error\" : \"ready\",\n            activeTurnId: undefined,\n            ...(lastError ? { lastError } : {}),\n          });\n        }),\n      ),\n    );\n\n    yield* client.handleServerNotification(\"error\", (payload) =>\n      currentSessionProviderThreadId.pipe(\n        Effect.flatMap((providerThreadId) => {\n          const payloadThreadId = payload.threadId;\n          if (providerThreadId && payloadThreadId && payloadThreadId !== providerThreadId) {\n            return Effect.void;\n          }\n          const errorMessage = payload.error.message;\n          const willRetry = payload.willRetry;\n          return updateSession(sessionRef, {\n            status: willRetry ? \"running\" : \"error\",\n            ...(errorMessage ? { lastError: errorMessage } : {}),\n          });\n        }),\n      ),\n    );\n\n    yield* client.handleServerRequest(\"item/commandExecution/requestApproval\", (payload) =>\n      Effect.gen(function* () {\n        const requestId = ApprovalRequestId.make(yield* randomUUIDv4(\"command-approval-request\"));\n        const turnId = TurnId.make(payload.turnId);\n        const itemId = ProviderItemId.make(payload.itemId);\n        const decision = yield* Deferred.make<ProviderApprovalDecision>();\n\n        yield* Ref.update(pendingApprovalsRef, (current) => {\n          const next = new Map(current);\n          next.set(requestId, {\n            requestId,\n            jsonRpcId: payload.approvalId ?? payload.itemId,\n            requestKind: \"command\",\n            turnId,\n            itemId,\n            decision,\n          });\n          return next;\n        });\n        yield* Ref.update(approvalCorrelationsRef, (current) => {\n          const next = new Map(current);\n          next.set(payload.approvalId ?? payload.itemId, {\n            requestId,\n            requestKind: \"command\",\n            turnId,\n            itemId,\n          });\n          return next;\n        });\n\n        yield* emitEvent({\n          kind: \"request\",\n          threadId: options.threadId,\n          method: \"item/commandExecution/requestApproval\",\n          requestId,\n          requestKind: \"command\",\n          ...(turnId ? { turnId } : {}),\n          ...(itemId ? { itemId } : {}),\n          payload,\n        });\n\n        const resolved = yield* Deferred.await(decision).pipe(\n          Effect.ensuring(\n            Ref.update(pendingApprovalsRef, (current) => {\n              const next = new Map(current);\n              next.delete(requestId);\n              return next;\n            }),\n          ),\n        );\n        return {\n          decision: resolved,\n        } satisfies EffectCodexSchema.CommandExecutionRequestApprovalResponse;\n      }),\n    );\n\n    yield* client.handleServerRequest(\"item/fileChange/requestApproval\", (payload) =>\n      Effect.gen(function* () {\n        const requestId = ApprovalRequestId.make(\n          yield* randomUUIDv4(\"file-change-approval-request\"),\n        );\n        const turnId = TurnId.make(payload.turnId);\n        const itemId = ProviderItemId.make(payload.itemId);\n        const decision = yield* Deferred.make<ProviderApprovalDecision>();\n\n        yield* Ref.update(pendingApprovalsRef, (current) => {\n          const next = new Map(current);\n          next.set(requestId, {\n            requestId,\n            jsonRpcId: payload.itemId,\n            requestKind: \"file-change\",\n            turnId,\n            itemId,\n            decision,\n          });\n          return next;\n        });\n        yield* Ref.update(approvalCorrelationsRef, (current) => {\n          const next = new Map(current);\n          next.set(payload.itemId, {\n            requestId,\n            requestKind: \"file-change\",\n            turnId,\n            itemId,\n          });\n          return next;\n        });\n\n        yield* emitEvent({\n          kind: \"request\",\n          threadId: options.threadId,\n          method: \"item/fileChange/requestApproval\",\n          requestId,\n          requestKind: \"file-change\",\n          ...(turnId ? { turnId } : {}),\n          ...(itemId ? { itemId } : {}),\n          payload,\n        });\n\n        const resolved = yield* Deferred.await(decision).pipe(\n          Effect.ensuring(\n            Ref.update(pendingApprovalsRef, (current) => {\n              const next = new Map(current);\n              next.delete(requestId);\n              return next;\n            }),\n          ),\n        );\n        return {\n          decision: resolved,\n        } satisfies EffectCodexSchema.FileChangeRequestApprovalResponse;\n      }),\n    );\n\n    yield* client.handleServerRequest(\"item/tool/requestUserInput\", (payload) =>\n      Effect.gen(function* () {\n        const requestId = ApprovalRequestId.make(yield* randomUUIDv4(\"user-input-request\"));\n        const turnId = TurnId.make(payload.turnId);\n        const itemId = ProviderItemId.make(payload.itemId);\n        const answers = yield* Deferred.make<ProviderUserInputAnswers>();\n\n        yield* Ref.update(pendingUserInputsRef, (current) => {\n          const next = new Map(current);\n          next.set(requestId, {\n            requestId,\n            turnId,\n            itemId,\n            answers,\n          });\n          return next;\n        });\n\n        yield* emitEvent({\n          kind: \"request\",\n          threadId: options.threadId,\n          method: \"item/tool/requestUserInput\",\n          requestId,\n          ...(turnId ? { turnId } : {}),\n          ...(itemId ? { itemId } : {}),\n          payload,\n        });\n\n        const resolvedAnswers = yield* Deferred.await(answers).pipe(\n          Effect.ensuring(\n            Ref.update(pendingUserInputsRef, (current) => {\n              const next = new Map(current);\n              next.delete(requestId);\n              return next;\n            }),\n          ),\n        );\n\n        return {\n          answers: yield* toCodexUserInputAnswers(resolvedAnswers).pipe(\n            Effect.mapError((error) =>\n              CodexErrors.CodexAppServerRequestError.invalidParams(error.message, {\n                questionId: error.questionId,\n              }),\n            ),\n          ),\n        } satisfies EffectCodexSchema.ToolRequestUserInputResponse;\n      }),\n    );\n\n    yield* client.handleUnknownServerRequest((method) =>\n      Effect.fail(CodexErrors.CodexAppServerRequestError.methodNotFound(method)),\n    );\n\n    const registerServerNotification = <M extends CodexRpc.ServerNotificationMethod>(method: M) =>\n      client.handleServerNotification(method, (params) =>\n        Queue.offer(serverNotifications, makeCodexServerNotification(method, params)).pipe(\n          Effect.asVoid,\n        ),\n      );\n\n    yield* Effect.forEach(\n      Object.values(\n        CodexRpc.SERVER_NOTIFICATION_METHODS,\n      ) as ReadonlyArray<CodexRpc.ServerNotificationMethod>,\n      registerServerNotification,\n      { concurrency: 1, discard: true },\n    );\n\n    yield* Stream.fromQueue(serverNotifications).pipe(\n      Stream.runForEach(handleRawNotification),\n      Effect.forkIn(runtimeScope),\n    );\n\n    const stderrRemainderRef = yield* Ref.make(\"\");\n    yield* child.stderr.pipe(\n      Stream.decodeText(),\n      Stream.runForEach((chunk) =>\n        Ref.modify(stderrRemainderRef, (current) => {\n          const combined = current + chunk;\n          const lines = combined.split(\"\\n\");\n          const remainder = lines.pop() ?? \"\";\n          return [lines.map((line) => line.replace(/\\r$/, \"\")), remainder] as const;\n        }).pipe(\n          Effect.flatMap((lines) =>\n            Effect.forEach(\n              lines,\n              (line) => {\n                const classified = classifyCodexStderrLine(line);\n                if (!classified) {\n                  return Effect.void;\n                }\n                return emitEvent({\n                  kind: \"notification\",\n                  threadId: options.threadId,\n                  method: \"process/stderr\",\n                  message: classified.message,\n                });\n              },\n              { discard: true },\n            ),\n          ),\n        ),\n      ),\n      Effect.forkIn(runtimeScope),\n    );\n\n    yield* child.exitCode.pipe(\n      Effect.flatMap((exitCode) =>\n        Ref.get(closedRef).pipe(\n          Effect.flatMap((closed) => {\n            if (closed) {\n              return Effect.void;\n            }\n            const nextStatus = exitCode === 0 ? \"closed\" : \"error\";\n            return updateSession(sessionRef, {\n              status: nextStatus,\n              activeTurnId: undefined,\n            }).pipe(\n              Effect.andThen(\n                emitSessionEvent(\n                  \"session/exited\",\n                  exitCode === 0\n                    ? \"Codex App Server exited.\"\n                    : `Codex App Server exited with code ${exitCode}.`,\n                ),\n              ),\n            );\n          }),\n        ),\n      ),\n      Effect.forkIn(runtimeScope),\n    );\n\n    const start = Effect.fn(\"CodexSessionRuntime.start\")(function* () {\n      yield* emitSessionEvent(\"session/connecting\", \"Starting Codex App Server session.\");\n      yield* client.request(\"initialize\", buildCodexInitializeParams());\n      yield* client.notify(\"initialized\", undefined);\n\n      const requestedModel = normalizeCodexModelSlug(options.model);\n\n      const opened = yield* openCodexThread({\n        client,\n        threadId: options.threadId,\n        runtimeMode: options.runtimeMode,\n        cwd: options.cwd,\n        requestedModel,\n        serviceTier: options.serviceTier,\n        resumeThreadId: readResumeCursorThreadId(options.resumeCursor),\n      });\n\n      const providerThreadId = opened.thread.id;\n      const session = {\n        ...(yield* Ref.get(sessionRef)),\n        status: \"ready\",\n        cwd: opened.cwd,\n        model: opened.model,\n        resumeCursor: { threadId: providerThreadId },\n        updatedAt: yield* nowIso,\n      } satisfies ProviderSession;\n      yield* Ref.set(sessionRef, session);\n      yield* emitSessionEvent(\"session/ready\", \"Codex App Server session ready.\");\n      return session;\n    });\n\n    const readProviderThreadId = Effect.gen(function* () {\n      const providerThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));\n      if (!providerThreadId) {\n        return yield* new CodexSessionRuntimeThreadIdMissingError({\n          threadId: options.threadId,\n        });\n      }\n      return providerThreadId;\n    });\n\n    const close = Effect.gen(function* () {\n      const alreadyClosed = yield* Ref.getAndSet(closedRef, true);\n      if (alreadyClosed) {\n        return;\n      }\n      yield* settlePendingApprovals(\"cancel\");\n      yield* settlePendingUserInputs({});\n      yield* updateSession(sessionRef, {\n        status: \"closed\",\n        activeTurnId: undefined,\n      });\n      yield* emitSessionEvent(\"session/closed\", \"Session stopped\").pipe(\n        Effect.catch((cause) =>\n          Effect.logError(\"Failed to emit Codex session closed event.\", { cause }),\n        ),\n      );\n      yield* Scope.close(runtimeScope, Exit.void);\n      yield* Queue.shutdown(serverNotifications);\n      yield* Queue.shutdown(events);\n    });\n\n    return {\n      start,\n      getSession: Ref.get(sessionRef),\n      sendTurn: (input) =>\n        Effect.gen(function* () {\n          const providerThreadId = yield* readProviderThreadId;\n          if (hasConfiguredMcpServer(options.appServerArgs)) {\n            yield* client.request(\"config/mcpServer/reload\", undefined).pipe(\n              Effect.catch((cause) =>\n                Effect.logWarning(\"Failed to refresh Codex MCP tool catalog before turn.\", {\n                  cause,\n                }),\n              ),\n            );\n          }\n          const normalizedModel = normalizeCodexModelSlug(\n            input.model ?? (yield* Ref.get(sessionRef)).model,\n          );\n          const params = yield* buildTurnStartParams({\n            threadId: providerThreadId,\n            runtimeMode: options.runtimeMode,\n            ...(input.input ? { prompt: input.input } : {}),\n            ...(input.attachments ? { attachments: input.attachments } : {}),\n            ...(normalizedModel ? { model: normalizedModel } : {}),\n            ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}),\n            ...(input.effort ? { effort: input.effort } : {}),\n            ...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),\n          });\n          const rawResponse = yield* client.raw.request(\"turn/start\", params);\n          const response = yield* decodeV2TurnStartResponse(rawResponse).pipe(\n            Effect.mapError((error) =>\n              CodexErrors.CodexAppServerProtocolParseError.fromSchemaError(\n                \"decode-response-payload\",\n                error,\n                { method: \"turn/start\" },\n              ),\n            ),\n          );\n          const turnId = TurnId.make(response.turn.id);\n          yield* updateSession(sessionRef, {\n            status: \"running\",\n            activeTurnId: turnId,\n            ...(normalizedModel ? { model: normalizedModel } : {}),\n          });\n          const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));\n          return {\n            threadId: options.threadId,\n            turnId,\n            ...(resumedProviderThreadId\n              ? { resumeCursor: { threadId: resumedProviderThreadId } }\n              : {}),\n          } satisfies ProviderTurnStartResult;\n        }),\n      interruptTurn: (turnId) =>\n        Effect.gen(function* () {\n          const providerThreadId = yield* readProviderThreadId;\n          const session = yield* Ref.get(sessionRef);\n          // Stop-everything: children are full threads with their own turns;\n          // interrupting only the parent leaves the fleet running. Interrupt\n          // each live child turn first, best-effort per child, BOUNDED: the\n          // transport awaits an unbounded Deferred per request, so a wedged\n          // child would otherwise block the parent interrupt forever —\n          // exactly during the runaway fleet where Stop matters most\n          // (review finding). Per-child and overall deadlines guarantee the\n          // parent interrupt below always runs.\n          const liveChildTurns = yield* Ref.get(collabChildLiveTurnsRef);\n          yield* Effect.forEach(\n            Array.from(liveChildTurns.entries()),\n            ([childThreadId, childTurnId]) =>\n              client\n                .request(\"turn/interrupt\", {\n                  threadId: childThreadId,\n                  turnId: childTurnId,\n                })\n                .pipe(Effect.timeoutOption(\"3 seconds\"), Effect.ignore),\n            { concurrency: 8, discard: true },\n          ).pipe(Effect.timeoutOption(\"10 seconds\"), Effect.ignore);\n          const effectiveTurnId = turnId ?? session.activeTurnId;\n          if (!effectiveTurnId) {\n            return;\n          }\n          yield* client.request(\"turn/interrupt\", {\n            threadId: providerThreadId,\n            turnId: effectiveTurnId,\n          });\n        }),\n      readThread: Effect.gen(function* () {\n        const providerThreadId = yield* readProviderThreadId;\n        const response = yield* client.request(\"thread/read\", {\n          threadId: providerThreadId,\n          includeTurns: true,\n        });\n        return parseThreadSnapshot(response);\n      }),\n      rollbackThread: (numTurns) =>\n        Effect.gen(function* () {\n          const providerThreadId = yield* readProviderThreadId;\n          const response = yield* client.request(\"thread/rollback\", {\n            threadId: providerThreadId,\n            numTurns,\n          });\n          yield* updateSession(sessionRef, {\n            status: \"ready\",\n            activeTurnId: undefined,\n          });\n          return parseThreadSnapshot(response);\n        }),\n      respondToRequest: (requestId, decision) =>\n        Effect.gen(function* () {\n          const pending = (yield* Ref.get(pendingApprovalsRef)).get(requestId);\n          if (!pending) {\n            return yield* new CodexSessionRuntimePendingApprovalNotFoundError({\n              requestId,\n            });\n          }\n          yield* Ref.update(pendingApprovalsRef, (current) => {\n            const next = new Map(current);\n            next.delete(requestId);\n            return next;\n          });\n          yield* Deferred.succeed(pending.decision, decision);\n          yield* emitEvent({\n            kind: \"notification\",\n            threadId: options.threadId,\n            method: \"item/requestApproval/decision\",\n            requestId: pending.requestId,\n            requestKind: pending.requestKind,\n            ...(pending.turnId ? { turnId: pending.turnId } : {}),\n            ...(pending.itemId ? { itemId: pending.itemId } : {}),\n            payload: {\n              requestId: pending.requestId,\n              requestKind: pending.requestKind,\n              decision,\n            },\n          });\n        }),\n      respondToUserInput: (requestId, answers) =>\n        Effect.gen(function* () {\n          const pending = (yield* Ref.get(pendingUserInputsRef)).get(requestId);\n          if (!pending) {\n            return yield* new CodexSessionRuntimePendingUserInputNotFoundError({\n              requestId,\n            });\n          }\n          const codexAnswers = yield* toCodexUserInputAnswers(answers);\n          yield* Ref.update(pendingUserInputsRef, (current) => {\n            const next = new Map(current);\n            next.delete(requestId);\n            return next;\n          });\n          yield* Deferred.succeed(pending.answers, answers);\n          yield* emitEvent({\n            kind: \"notification\",\n            threadId: options.threadId,\n            method: \"item/tool/requestUserInput/answered\",\n            requestId: pending.requestId,\n            ...(pending.turnId ? { turnId: pending.turnId } : {}),\n            ...(pending.itemId ? { itemId: pending.itemId } : {}),\n            payload: {\n              answers: codexAnswers,\n            },\n          });\n        }),\n      events: Stream.fromQueue(events),\n      close,\n    } satisfies CodexSessionRuntimeShape;\n  });\n","/**\n * CodexAdapterLive - Scoped live implementation for the Codex provider adapter.\n *\n * Wraps the typed Codex session runtime behind the `CodexAdapter` service\n * contract and maps runtime failures into the shared `ProviderAdapterError`\n * algebra.\n *\n * @module CodexAdapterLive\n */\nimport {\n  type CanonicalItemType,\n  type CanonicalRequestType,\n  type CodexSettings,\n  ProviderDriverKind,\n  type ProviderEvent,\n  ProviderInstanceId,\n  type ProviderRuntimeEvent,\n  type ProviderRequestKind,\n  type ThreadTokenUsageSnapshot,\n  type ProviderUserInputAnswers,\n  RuntimeItemId,\n  RuntimeRequestId,\n  RuntimeTaskId,\n  type RuntimeTaskUsage,\n  ProviderApprovalDecision,\n  ThreadId,\n  ProviderSendTurnInput,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\nimport * as CodexErrors from \"effect-codex-app-server/errors\";\nimport * as EffectCodexSchema from \"effect-codex-app-server/schema\";\n\nimport { getModelSelectionStringOptionValue } from \"@t3tools/shared/model\";\nimport { getCodexServiceTierOptionValue } from \"../../codexModelOptions.ts\";\nimport * as McpProviderSession from \"../../mcp/McpProviderSession.ts\";\n\nimport {\n  ProviderAdapterRequestError,\n  ProviderAdapterProcessError,\n  ProviderAdapterSessionClosedError,\n  ProviderAdapterSessionNotFoundError,\n  ProviderAdapterValidationError,\n  type ProviderAdapterError,\n} from \"../Errors.ts\";\nimport { type CodexAdapterShape } from \"../Services/CodexAdapter.ts\";\nimport { resolveAttachmentPath } from \"../../attachmentStore.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport {\n  CodexResumeCursorSchema,\n  CodexSessionRuntimeThreadIdMissingError,\n  makeCodexSessionRuntime,\n  type CodexSessionRuntimeError,\n  type CodexSessionRuntimeOptions,\n  type CodexSessionRuntimeShape,\n} from \"./CodexSessionRuntime.ts\";\nimport { type EventNdjsonLogger, makeEventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\nimport { resolveCodexLaunchArgs } from \"./codexLaunchArgs.ts\";\nconst isCodexAppServerProcessExitedError = Schema.is(CodexErrors.CodexAppServerProcessExitedError);\nconst isCodexAppServerTransportError = Schema.is(CodexErrors.CodexAppServerTransportError);\nconst isCodexSessionRuntimeThreadIdMissingError = Schema.is(\n  CodexSessionRuntimeThreadIdMissingError,\n);\nconst isCodexResumeCursorSchema = Schema.is(CodexResumeCursorSchema);\n\nconst PROVIDER = ProviderDriverKind.make(\"codex\");\n\nexport interface CodexAdapterLiveOptions {\n  readonly instanceId?: ProviderInstanceId;\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly makeRuntime?: (\n    options: CodexSessionRuntimeOptions,\n  ) => Effect.Effect<\n    CodexSessionRuntimeShape,\n    CodexSessionRuntimeError,\n    ChildProcessSpawner.ChildProcessSpawner | Scope.Scope\n  >;\n  readonly nativeEventLogPath?: string;\n  readonly nativeEventLogger?: EventNdjsonLogger;\n}\n\ninterface CodexAdapterSessionContext {\n  readonly threadId: ThreadId;\n  readonly scope: Scope.Closeable;\n  readonly runtime: CodexSessionRuntimeShape;\n  readonly eventFiber: Fiber.Fiber<void, never>;\n  stopped: boolean;\n}\n\nfunction mapCodexRuntimeError(\n  threadId: ThreadId,\n  method: string,\n  error: CodexSessionRuntimeError,\n): ProviderAdapterError {\n  if (isCodexAppServerProcessExitedError(error) || isCodexAppServerTransportError(error)) {\n    return new ProviderAdapterSessionClosedError({\n      provider: PROVIDER,\n      threadId,\n      cause: error,\n    });\n  }\n\n  if (isCodexSessionRuntimeThreadIdMissingError(error)) {\n    return new ProviderAdapterSessionNotFoundError({\n      provider: PROVIDER,\n      threadId,\n      cause: error,\n    });\n  }\n\n  return new ProviderAdapterRequestError({\n    provider: PROVIDER,\n    method,\n    detail: error.message,\n    cause: error,\n  });\n}\n\ntype CodexLifecycleItem =\n  | EffectCodexSchema.V2ItemStartedNotification[\"item\"]\n  | EffectCodexSchema.V2ItemCompletedNotification[\"item\"];\n\ntype CodexToolUserInputQuestion =\n  | EffectCodexSchema.ServerRequest__ToolRequestUserInputQuestion\n  | EffectCodexSchema.ToolRequestUserInputParams__ToolRequestUserInputQuestion;\n\nconst ApprovalDecisionPayload = Schema.Struct({\n  decision: ProviderApprovalDecision,\n});\n\nfunction readPayload<A>(\n  schema: Schema.Schema<A>,\n  payload: ProviderEvent[\"payload\"],\n): A | undefined {\n  const isPayload = Schema.is(schema);\n  return isPayload(payload) ? payload : undefined;\n}\n\nfunction trimText(value: string | undefined | null): string | undefined {\n  const trimmed = value?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nconst FATAL_CODEX_STDERR_SNIPPETS = [\"failed to connect to websocket\"];\n\nfunction isFatalCodexProcessStderrMessage(message: string): boolean {\n  const normalized = message.toLowerCase();\n  return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet));\n}\n\nfunction normalizeCodexTokenUsage(\n  usage: EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification[\"tokenUsage\"],\n): ThreadTokenUsageSnapshot | undefined {\n  const totalProcessedTokens = usage.total.totalTokens;\n  const usedTokens = usage.last.totalTokens;\n  if (usedTokens === undefined || usedTokens <= 0) {\n    return undefined;\n  }\n\n  const maxTokens = usage.modelContextWindow ?? undefined;\n  const inputTokens = usage.last.inputTokens;\n  const cachedInputTokens = usage.last.cachedInputTokens;\n  const outputTokens = usage.last.outputTokens;\n  const reasoningOutputTokens = usage.last.reasoningOutputTokens;\n\n  return {\n    usedTokens,\n    ...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens\n      ? { totalProcessedTokens }\n      : {}),\n    ...(maxTokens !== undefined ? { maxTokens } : {}),\n    ...(inputTokens !== undefined ? { inputTokens } : {}),\n    ...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),\n    ...(outputTokens !== undefined ? { outputTokens } : {}),\n    ...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),\n    ...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}),\n    ...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),\n    ...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),\n    ...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),\n    ...(reasoningOutputTokens !== undefined\n      ? { lastReasoningOutputTokens: reasoningOutputTokens }\n      : {}),\n    compactsAutomatically: true,\n  };\n}\n\nfunction toTurnStatus(\n  value: EffectCodexSchema.V2TurnCompletedNotification[\"turn\"][\"status\"] | \"cancelled\",\n): \"completed\" | \"failed\" | \"cancelled\" | \"interrupted\" {\n  switch (value) {\n    case \"completed\":\n    case \"failed\":\n    case \"cancelled\":\n    case \"interrupted\":\n      return value;\n    default:\n      return \"completed\";\n  }\n}\n\nfunction normalizeItemType(raw: string | undefined | null): string {\n  const type = trimText(raw);\n  if (!type) return \"item\";\n  return type\n    .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n    .replace(/[._/-]/g, \" \")\n    .replace(/\\s+/g, \" \")\n    .trim()\n    .toLowerCase();\n}\n\nfunction toCanonicalItemType(raw: string | undefined | null): CanonicalItemType {\n  const type = normalizeItemType(raw);\n  if (type.includes(\"user\")) return \"user_message\";\n  if (type.includes(\"agent message\") || type.includes(\"assistant\")) return \"assistant_message\";\n  if (type.includes(\"reasoning\") || type.includes(\"thought\")) return \"reasoning\";\n  if (type.includes(\"plan\") || type.includes(\"todo\")) return \"plan\";\n  if (type.includes(\"command\")) return \"command_execution\";\n  if (type.includes(\"file change\") || type.includes(\"patch\") || type.includes(\"edit\"))\n    return \"file_change\";\n  if (type.includes(\"mcp\")) return \"mcp_tool_call\";\n  if (type.includes(\"dynamic tool\")) return \"dynamic_tool_call\";\n  if (type.includes(\"collab\")) return \"collab_agent_tool_call\";\n  if (type.includes(\"web search\")) return \"web_search\";\n  if (type.includes(\"image\")) return \"image_view\";\n  if (type.includes(\"review entered\")) return \"review_entered\";\n  if (type.includes(\"review exited\")) return \"review_exited\";\n  if (type.includes(\"compact\")) return \"context_compaction\";\n  if (type.includes(\"error\")) return \"error\";\n  return \"unknown\";\n}\n\nfunction itemTitle(itemType: CanonicalItemType, item?: CodexLifecycleItem): string | undefined {\n  if (itemType === \"mcp_tool_call\" && item?.type === \"mcpToolCall\") {\n    return `${item.server} · ${item.tool}`;\n  }\n  switch (itemType) {\n    case \"assistant_message\":\n      return \"Assistant message\";\n    case \"user_message\":\n      return \"User message\";\n    case \"reasoning\":\n      return \"Reasoning\";\n    case \"plan\":\n      return \"Plan\";\n    case \"command_execution\":\n      return \"Ran command\";\n    case \"file_change\":\n      return \"File change\";\n    case \"mcp_tool_call\":\n      return \"MCP tool call\";\n    case \"dynamic_tool_call\":\n      return \"Tool call\";\n    case \"web_search\":\n      return \"Web search\";\n    case \"image_view\":\n      return \"Image view\";\n    case \"error\":\n      return \"Error\";\n    default:\n      return undefined;\n  }\n}\n\nfunction itemDetail(itemType: CanonicalItemType, item: CodexLifecycleItem): string | undefined {\n  const itemRecord = item as Record<string, unknown>;\n  const action = itemRecord.action as Record<string, unknown> | undefined;\n  const actionQueries = Array.isArray(action?.queries) ? action.queries : [];\n  const candidates = [\n    ...(itemType === \"web_search\"\n      ? [itemRecord.query, action?.query, ...actionQueries, action?.pattern, action?.url]\n      : []),\n    \"command\" in item ? item.command : undefined,\n    \"title\" in item ? item.title : undefined,\n    \"summary\" in item ? item.summary : undefined,\n    \"text\" in item ? item.text : undefined,\n    \"path\" in item ? item.path : undefined,\n    \"prompt\" in item ? item.prompt : undefined,\n  ];\n\n  for (const candidate of candidates) {\n    const trimmed = typeof candidate === \"string\" ? trimText(candidate) : undefined;\n    if (!trimmed) continue;\n    return trimmed;\n  }\n  return undefined;\n}\n\nfunction toRequestTypeFromMethod(method: string): CanonicalRequestType {\n  switch (method) {\n    case \"item/commandExecution/requestApproval\":\n      return \"command_execution_approval\";\n    case \"item/fileRead/requestApproval\":\n      return \"file_read_approval\";\n    case \"item/fileChange/requestApproval\":\n      return \"file_change_approval\";\n    case \"applyPatchApproval\":\n      return \"apply_patch_approval\";\n    case \"execCommandApproval\":\n      return \"exec_command_approval\";\n    case \"item/tool/requestUserInput\":\n      return \"tool_user_input\";\n    case \"item/tool/call\":\n      return \"dynamic_tool_call\";\n    case \"account/chatgptAuthTokens/refresh\":\n      return \"auth_tokens_refresh\";\n    default:\n      return \"unknown\";\n  }\n}\n\nfunction toRequestTypeFromKind(kind: ProviderRequestKind | undefined): CanonicalRequestType {\n  switch (kind) {\n    case \"command\":\n      return \"command_execution_approval\";\n    case \"file-read\":\n      return \"file_read_approval\";\n    case \"file-change\":\n      return \"file_change_approval\";\n    default:\n      return \"unknown\";\n  }\n}\n\nfunction toCanonicalUserInputAnswers(\n  answers: EffectCodexSchema.ToolRequestUserInputResponse[\"answers\"],\n): ProviderUserInputAnswers {\n  return Object.fromEntries(\n    Object.entries(answers).map(([questionId, value]) => {\n      const normalizedAnswers = value.answers.length === 1 ? value.answers[0]! : [...value.answers];\n      return [questionId, normalizedAnswers] as const;\n    }),\n  );\n}\n\nfunction toUserInputQuestions(questions: ReadonlyArray<CodexToolUserInputQuestion>) {\n  const parsedQuestions = questions\n    .map((question) => {\n      const options =\n        question.options\n          ?.map((option) => {\n            const label = trimText(option.label);\n            const description = trimText(option.description);\n            if (!label || !description) {\n              return undefined;\n            }\n            return { label, description };\n          })\n          .filter((option) => option !== undefined) ?? [];\n\n      const id = trimText(question.id);\n      const header = trimText(question.header);\n      const prompt = trimText(question.question);\n      if (!id || !header || !prompt || options.length === 0) {\n        return undefined;\n      }\n      return {\n        id,\n        header,\n        question: prompt,\n        options,\n        multiSelect: false,\n      };\n    })\n    .filter((question) => question !== undefined);\n\n  return parsedQuestions.length > 0 ? parsedQuestions : undefined;\n}\n\nfunction toThreadState(\n  status: EffectCodexSchema.V2ThreadStatusChangedNotification[\"status\"],\n): \"active\" | \"idle\" | \"archived\" | \"closed\" | \"compacted\" | \"error\" {\n  switch (status.type) {\n    case \"idle\":\n      return \"idle\";\n    case \"systemError\":\n      return \"error\";\n    default:\n      return \"active\";\n  }\n}\n\nfunction contentStreamKindFromMethod(\n  method: string,\n):\n  | \"assistant_text\"\n  | \"reasoning_text\"\n  | \"reasoning_summary_text\"\n  | \"plan_text\"\n  | \"command_output\"\n  | \"file_change_output\" {\n  switch (method) {\n    case \"item/agentMessage/delta\":\n      return \"assistant_text\";\n    case \"item/reasoning/textDelta\":\n      return \"reasoning_text\";\n    case \"item/reasoning/summaryTextDelta\":\n      return \"reasoning_summary_text\";\n    case \"item/commandExecution/outputDelta\":\n      return \"command_output\";\n    case \"item/fileChange/outputDelta\":\n      return \"file_change_output\";\n    default:\n      return \"assistant_text\";\n  }\n}\n\nfunction asRuntimeItemId(itemId: ProviderEvent[\"itemId\"] & string): RuntimeItemId {\n  return RuntimeItemId.make(itemId);\n}\n\nfunction asRuntimeRequestId(requestId: string): RuntimeRequestId {\n  return RuntimeRequestId.make(requestId);\n}\n\nfunction eventRawSource(event: ProviderEvent): NonNullable<ProviderRuntimeEvent[\"raw\"]>[\"source\"] {\n  return event.kind === \"request\" ? \"codex.app-server.request\" : \"codex.app-server.notification\";\n}\n\nfunction providerRefsFromEvent(\n  event: ProviderEvent,\n): ProviderRuntimeEvent[\"providerRefs\"] | undefined {\n  const refs: Record<string, string> = {};\n  if (event.turnId) refs.providerTurnId = event.turnId;\n  if (event.itemId) refs.providerItemId = event.itemId;\n  if (event.requestId) refs.providerRequestId = event.requestId;\n\n  return Object.keys(refs).length > 0 ? (refs as ProviderRuntimeEvent[\"providerRefs\"]) : undefined;\n}\n\nfunction runtimeEventBase(\n  event: ProviderEvent,\n  canonicalThreadId: ThreadId,\n): Omit<ProviderRuntimeEvent, \"type\" | \"payload\"> {\n  const refs = providerRefsFromEvent(event);\n  return {\n    eventId: event.id,\n    provider: event.provider,\n    threadId: canonicalThreadId,\n    createdAt: event.createdAt,\n    ...(event.turnId ? { turnId: event.turnId } : {}),\n    ...(event.itemId ? { itemId: asRuntimeItemId(event.itemId) } : {}),\n    ...(event.requestId ? { requestId: asRuntimeRequestId(event.requestId) } : {}),\n    ...(refs ? { providerRefs: refs } : {}),\n    raw: {\n      source: eventRawSource(event),\n      method: event.method,\n      payload: event.payload ?? {},\n    },\n  };\n}\n\nfunction mapItemLifecycle(\n  event: ProviderEvent,\n  canonicalThreadId: ThreadId,\n  lifecycle: \"item.started\" | \"item.updated\" | \"item.completed\",\n): ProviderRuntimeEvent | undefined {\n  const payload =\n    readPayload(EffectCodexSchema.V2ItemStartedNotification, event.payload) ??\n    readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload);\n  const item = payload?.item;\n  if (!item) {\n    return undefined;\n  }\n  const itemType = toCanonicalItemType(item.type);\n  if (itemType === \"unknown\" && lifecycle !== \"item.updated\") {\n    return undefined;\n  }\n\n  const detail = itemDetail(itemType, item);\n  const status =\n    lifecycle === \"item.started\"\n      ? \"inProgress\"\n      : lifecycle === \"item.completed\"\n        ? \"completed\"\n        : undefined;\n\n  return {\n    ...runtimeEventBase(event, canonicalThreadId),\n    type: lifecycle,\n    payload: {\n      itemType,\n      ...(status ? { status } : {}),\n      ...(itemTitle(itemType, item) ? { title: itemTitle(itemType, item) } : {}),\n      ...(detail ? { detail } : {}),\n      ...(event.payload !== undefined ? { data: event.payload } : {}),\n    },\n  };\n}\n\n/**\n * Maps the session runtime's synthetic `collabAgent/*` events (native\n * multi-agent v2 child-thread signals) into the shared task.* lifecycle.\n * Agent identity = child thread id; nickname is the display title, role is\n * agentRole (fallback: last agentPath segment, then \"general-purpose\").\n * A completed child turn is idle (resumable), not terminal. timelineBypass\n * keeps these rows out of the parent chat.\n */\nfunction mapCollabAgentEvent(\n  event: ProviderEvent,\n  canonicalThreadId: ThreadId,\n): ReadonlyArray<ProviderRuntimeEvent> {\n  const payload =\n    typeof event.payload === \"object\" && event.payload !== null\n      ? (event.payload as Record<string, unknown>)\n      : undefined;\n  const agentThreadId = typeof payload?.agentThreadId === \"string\" ? payload.agentThreadId : \"\";\n  if (!payload || agentThreadId.length === 0) {\n    return [];\n  }\n  const base = runtimeEventBase(event, canonicalThreadId);\n  const taskId = RuntimeTaskId.make(agentThreadId);\n  const agentPath = typeof payload.agentPath === \"string\" ? payload.agentPath : undefined;\n  const pathLeaf = agentPath?.split(\"/\").findLast((segment) => segment.length > 0);\n  const nickname = typeof payload.nickname === \"string\" ? payload.nickname : undefined;\n  const role =\n    (typeof payload.role === \"string\" ? payload.role : undefined) ?? pathLeaf ?? \"general-purpose\";\n  // A bare thread id is not a name. Omitting the title lets the client fold\n  // keep the real one from task.started instead of clobbering it (probe\n  // finding: progress rows renamed math_one to its UUID).\n  const knownName = nickname ?? pathLeaf;\n  const title = knownName ?? agentThreadId;\n  // Identity repeated on every status patch so rows are self-describing when\n  // the start row ages out of activity retention (review finding: a\n  // reconstructed agent had a UUID name and no role/path).\n  const statusLinkage = {\n    role,\n    ...(knownName ? { title: knownName } : {}),\n    ...(agentPath ? { agentPath } : {}),\n    timelineBypass: true,\n  } as const;\n\n  switch (event.method) {\n    case \"collabAgent/started\":\n      return [\n        {\n          ...base,\n          type: \"task.started\",\n          payload: {\n            taskId,\n            description: title,\n            title,\n            role,\n            ...(agentPath ? { agentPath } : {}),\n            ...(typeof payload.parentThreadId === \"string\"\n              ? { parentAgentId: payload.parentThreadId }\n              : {}),\n            timelineBypass: true,\n          },\n        },\n      ];\n    case \"collabAgent/activity\": {\n      const activityKind = typeof payload.activityKind === \"string\" ? payload.activityKind : \"\";\n      if (activityKind === \"interrupted\") {\n        return [\n          {\n            ...base,\n            type: \"task.updated\",\n            payload: { taskId, status: \"interrupted\", ...statusLinkage },\n          },\n        ];\n      }\n      if (activityKind === \"started\") {\n        // Wire-probe finding: children often register via subAgentActivity\n        // alone (no thread/started with a spawn source), so this is the one\n        // shot at a task.started with a real name — agentPath leaf beats a\n        // bare thread-id title.\n        return [\n          {\n            ...base,\n            type: \"task.started\",\n            payload: {\n              taskId,\n              description: title,\n              title,\n              role,\n              ...(agentPath ? { agentPath } : {}),\n              timelineBypass: true,\n            },\n          },\n        ];\n      }\n      // interacted → the child is (again) actively driven.\n      return [\n        {\n          ...base,\n          type: \"task.updated\",\n          payload: { taskId, status: \"running\", ...statusLinkage },\n        },\n      ];\n    }\n    case \"collabAgent/turnStarted\":\n      return [\n        {\n          ...base,\n          type: \"task.updated\",\n          payload: { taskId, status: \"running\", ...statusLinkage },\n        },\n      ];\n    case \"collabAgent/turnCompleted\": {\n      // Idle, not terminal: the identity is resumable via sendInput/resume.\n      const turn =\n        typeof payload.turn === \"object\" && payload.turn !== null\n          ? (payload.turn as Record<string, unknown>)\n          : undefined;\n      const turnStatus = typeof turn?.status === \"string\" ? turn.status : undefined;\n      const status =\n        turnStatus === \"failed\"\n          ? (\"failed\" as const)\n          : turnStatus === \"interrupted\"\n            ? (\"interrupted\" as const)\n            : (\"idle\" as const);\n      return [\n        {\n          ...base,\n          type: \"task.updated\",\n          payload: { taskId, status, ...statusLinkage },\n        },\n      ];\n    }\n    case \"collabAgent/statusChanged\": {\n      const status =\n        typeof payload.status === \"object\" && payload.status !== null\n          ? (payload.status as Record<string, unknown>)\n          : undefined;\n      const statusType = typeof status?.type === \"string\" ? status.type : undefined;\n      if (statusType === \"systemError\") {\n        // Silently dropping this once left children stuck running forever.\n        return [\n          {\n            ...base,\n            type: \"task.updated\",\n            payload: { taskId, status: \"failed\", ...statusLinkage },\n          },\n        ];\n      }\n      if (statusType === \"active\") {\n        const flags = Array.isArray(status?.activeFlags) ? status.activeFlags : [];\n        const waiting = flags.some(\n          (flag) => flag === \"waitingOnApproval\" || flag === \"waitingOnUserInput\",\n        );\n        return [\n          {\n            ...base,\n            type: \"task.updated\",\n            payload: { taskId, status: waiting ? \"waiting\" : \"running\", ...statusLinkage },\n          },\n        ];\n      }\n      if (statusType === \"idle\") {\n        return [\n          {\n            ...base,\n            type: \"task.updated\",\n            payload: { taskId, status: \"idle\", ...statusLinkage },\n          },\n        ];\n      }\n      return [];\n    }\n    case \"collabAgent/tokenUsage\": {\n      // Cumulative per child thread: always the `total` breakdown, never\n      // `last` (which shrinks on follow-ups). Client folds max-merge.\n      const tokenUsage =\n        typeof payload.tokenUsage === \"object\" && payload.tokenUsage !== null\n          ? (payload.tokenUsage as Record<string, unknown>)\n          : undefined;\n      const total =\n        typeof tokenUsage?.total === \"object\" && tokenUsage.total !== null\n          ? (tokenUsage.total as Record<string, unknown>)\n          : undefined;\n      const count = (value: unknown): number | undefined =>\n        typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? value : undefined;\n      // Same validation as every other field: RuntimeTaskUsage.totalTokens\n      // is NonNegativeInt, so NaN/Infinity/negative wire values must miss.\n      const totalTokens = count(total?.totalTokens);\n      if (totalTokens === undefined) {\n        return [];\n      }\n      const typedUsage: RuntimeTaskUsage = {\n        totalTokens,\n        ...(count(total?.inputTokens) !== undefined\n          ? { inputTokens: count(total?.inputTokens) }\n          : {}),\n        ...(count(total?.cachedInputTokens) !== undefined\n          ? { cachedInputTokens: count(total?.cachedInputTokens) }\n          : {}),\n        ...(count(total?.outputTokens) !== undefined\n          ? { outputTokens: count(total?.outputTokens) }\n          : {}),\n        ...(count(total?.reasoningOutputTokens) !== undefined\n          ? { reasoningOutputTokens: count(total?.reasoningOutputTokens) }\n          : {}),\n      };\n      return [\n        {\n          ...base,\n          type: \"task.progress\",\n          payload: {\n            taskId,\n            description: title,\n            ...(knownName ? { title: knownName } : {}),\n            typedUsage,\n            timelineBypass: true,\n          },\n        },\n      ];\n    }\n    case \"collabAgent/item\": {\n      const item =\n        typeof payload.item === \"object\" && payload.item !== null\n          ? (payload.item as Record<string, unknown>)\n          : undefined;\n      const itemTypeRaw = typeof item?.type === \"string\" ? item.type : undefined;\n      if (!itemTypeRaw) {\n        return [];\n      }\n      // A loose summary from the raw item: the child stream is untyped at\n      // this boundary (synthetic event payload), so read best-effort fields\n      // rather than force a schema decode.\n      const looseSummary =\n        (typeof item?.command === \"string\" ? item.command : undefined) ??\n        (typeof item?.title === \"string\" ? item.title : undefined) ??\n        (typeof item?.query === \"string\" ? item.query : undefined);\n      const canonical = toCanonicalItemType(itemTypeRaw);\n      const summary = looseSummary ?? canonical.replaceAll(\"_\", \" \");\n      return [\n        {\n          ...base,\n          type: \"task.progress\",\n          payload: {\n            taskId,\n            description: title,\n            ...(knownName ? { title: knownName } : {}),\n            summary,\n            timelineBypass: true,\n          },\n        },\n      ];\n    }\n    case \"collabAgent/closed\":\n      return [\n        {\n          ...base,\n          type: \"task.updated\",\n          payload: { taskId, status: \"interrupted\", ...statusLinkage },\n        },\n      ];\n    default:\n      return [];\n  }\n}\n\nfunction mapToRuntimeEvents(\n  event: ProviderEvent,\n  canonicalThreadId: ThreadId,\n): ReadonlyArray<ProviderRuntimeEvent> {\n  if (event.kind === \"notification\" && event.method.startsWith(\"collabAgent/\")) {\n    return mapCollabAgentEvent(event, canonicalThreadId);\n  }\n  if (event.kind === \"error\") {\n    if (!event.message) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"runtime.error\",\n        payload: {\n          message: event.message,\n          class: \"provider_error\",\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.kind === \"request\") {\n    if (event.method === \"item/tool/requestUserInput\") {\n      const payload =\n        readPayload(EffectCodexSchema.ServerRequest__ToolRequestUserInputParams, event.payload) ??\n        readPayload(EffectCodexSchema.ToolRequestUserInputParams, event.payload);\n      const questions = payload ? toUserInputQuestions(payload.questions) : undefined;\n      if (!questions) {\n        return [];\n      }\n      return [\n        {\n          ...runtimeEventBase(event, canonicalThreadId),\n          type: \"user-input.requested\",\n          payload: {\n            questions,\n          },\n        },\n      ];\n    }\n\n    const detail = (() => {\n      switch (event.method) {\n        case \"item/commandExecution/requestApproval\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__CommandExecutionRequestApprovalParams,\n            event.payload,\n          );\n          return payload?.command ?? payload?.reason ?? undefined;\n        }\n        case \"item/fileChange/requestApproval\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__FileChangeRequestApprovalParams,\n            event.payload,\n          );\n          return payload?.reason ?? undefined;\n        }\n        case \"applyPatchApproval\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__ApplyPatchApprovalParams,\n            event.payload,\n          );\n          return payload?.reason ?? undefined;\n        }\n        case \"execCommandApproval\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__ExecCommandApprovalParams,\n            event.payload,\n          );\n          return payload?.reason ?? payload?.command.join(\" \");\n        }\n        case \"item/tool/call\": {\n          const payload = readPayload(\n            EffectCodexSchema.ServerRequest__DynamicToolCallParams,\n            event.payload,\n          );\n          return payload?.tool ?? undefined;\n        }\n        default:\n          return undefined;\n      }\n    })();\n\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"request.opened\",\n        payload: {\n          requestType: toRequestTypeFromMethod(event.method),\n          ...(detail ? { detail } : {}),\n          ...(event.payload !== undefined ? { args: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/requestApproval/decision\" && event.requestId) {\n    const payload = readPayload(ApprovalDecisionPayload, event.payload);\n    const requestType =\n      event.requestKind !== undefined\n        ? toRequestTypeFromKind(event.requestKind)\n        : toRequestTypeFromMethod(event.method);\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"request.resolved\",\n        payload: {\n          requestType,\n          ...(payload ? { decision: payload.decision } : {}),\n          ...(event.payload !== undefined ? { resolution: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"session/connecting\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"session.state.changed\",\n        payload: {\n          state: \"starting\",\n          ...(event.message ? { reason: event.message } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"session/ready\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"session.state.changed\",\n        payload: {\n          state: \"ready\",\n          ...(event.message ? { reason: event.message } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"session/started\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"session.started\",\n        payload: {\n          ...(event.message ? { message: event.message } : {}),\n          ...(event.payload !== undefined ? { resume: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"session/exited\" || event.method === \"session/closed\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"session.exited\",\n        payload: {\n          ...(event.message ? { reason: event.message } : {}),\n          ...(event.method === \"session/closed\" ? { exitKind: \"graceful\" } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/started\") {\n    const payload = readPayload(EffectCodexSchema.V2ThreadStartedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"thread.started\",\n        payload: {\n          providerThreadId: payload.thread.id,\n        },\n      },\n    ];\n  }\n\n  if (\n    event.method === \"thread/status/changed\" ||\n    event.method === \"thread/archived\" ||\n    event.method === \"thread/unarchived\" ||\n    event.method === \"thread/closed\" ||\n    event.method === \"thread/compacted\"\n  ) {\n    const payload =\n      event.method === \"thread/status/changed\"\n        ? readPayload(EffectCodexSchema.V2ThreadStatusChangedNotification, event.payload)\n        : undefined;\n    return [\n      {\n        type: \"thread.state.changed\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          state:\n            event.method === \"thread/archived\"\n              ? \"archived\"\n              : event.method === \"thread/closed\"\n                ? \"closed\"\n                : event.method === \"thread/compacted\"\n                  ? \"compacted\"\n                  : payload\n                    ? toThreadState(payload.status)\n                    : \"active\",\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/name/updated\") {\n    const payload = readPayload(EffectCodexSchema.V2ThreadNameUpdatedNotification, event.payload);\n    return [\n      {\n        type: \"thread.metadata.updated\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          ...(trimText(payload?.threadName) ? { name: trimText(payload?.threadName) } : {}),\n          ...(payload\n            ? {\n                metadata: {\n                  threadId: payload.threadId,\n                  ...(payload.threadName !== undefined && payload.threadName !== null\n                    ? { threadName: payload.threadName }\n                    : {}),\n                },\n              }\n            : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/tokenUsage/updated\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,\n      event.payload,\n    );\n    const normalizedUsage = payload ? normalizeCodexTokenUsage(payload.tokenUsage) : undefined;\n    if (!normalizedUsage) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.token-usage.updated\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          usage: normalizedUsage,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"turn/started\") {\n    const turnId = event.turnId;\n    if (!turnId) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        turnId,\n        type: \"turn.started\",\n        payload: {},\n      },\n    ];\n  }\n\n  if (event.method === \"turn/completed\") {\n    const payload = readPayload(EffectCodexSchema.V2TurnCompletedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    const errorMessage = trimText(payload.turn.error?.message);\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.completed\",\n        payload: {\n          state: toTurnStatus(payload.turn.status),\n          ...(errorMessage ? { errorMessage } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"turn/aborted\") {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.aborted\",\n        payload: {\n          reason: event.message ?? \"Turn aborted\",\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"turn/plan/updated\") {\n    const payload = readPayload(EffectCodexSchema.V2TurnPlanUpdatedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.plan.updated\",\n        payload: {\n          ...(trimText(payload.explanation) ? { explanation: trimText(payload.explanation) } : {}),\n          plan: payload.plan.map((step) => ({\n            step: trimText(step.step) ?? \"step\",\n            status:\n              step.status === \"completed\" || step.status === \"inProgress\" ? step.status : \"pending\",\n          })),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"turn/diff/updated\") {\n    const payload = readPayload(EffectCodexSchema.V2TurnDiffUpdatedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.diff.updated\",\n        payload: {\n          unifiedDiff: payload.diff,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/started\") {\n    const started = mapItemLifecycle(event, canonicalThreadId, \"item.started\");\n    return started ? [started] : [];\n  }\n\n  if (event.method === \"item/completed\") {\n    const payload = readPayload(EffectCodexSchema.V2ItemCompletedNotification, event.payload);\n    const item = payload?.item;\n    if (!item) {\n      return [];\n    }\n    const itemType = toCanonicalItemType(item.type);\n    if (itemType === \"plan\") {\n      const detail = itemDetail(itemType, item);\n      if (!detail) {\n        return [];\n      }\n      return [\n        {\n          ...runtimeEventBase(event, canonicalThreadId),\n          type: \"turn.proposed.completed\",\n          payload: {\n            planMarkdown: detail,\n          },\n        },\n      ];\n    }\n    const completed = mapItemLifecycle(event, canonicalThreadId, \"item.completed\");\n    return completed ? [completed] : [];\n  }\n\n  if (\n    event.method === \"item/reasoning/summaryPartAdded\" ||\n    event.method === \"item/commandExecution/terminalInteraction\"\n  ) {\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"item.updated\",\n        payload: {\n          itemType:\n            event.method === \"item/reasoning/summaryPartAdded\" ? \"reasoning\" : \"command_execution\",\n          ...(event.payload !== undefined ? { data: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/plan/delta\") {\n    const payload = readPayload(EffectCodexSchema.V2PlanDeltaNotification, event.payload);\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"turn.proposed.delta\",\n        payload: {\n          delta,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/agentMessage/delta\") {\n    const payload = readPayload(EffectCodexSchema.V2AgentMessageDeltaNotification, event.payload);\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: contentStreamKindFromMethod(event.method),\n          delta,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/commandExecution/outputDelta\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2CommandExecutionOutputDeltaNotification,\n      event.payload,\n    );\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: \"command_output\",\n          delta,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/fileChange/outputDelta\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2FileChangeOutputDeltaNotification,\n      event.payload,\n    );\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: \"file_change_output\",\n          delta,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/reasoning/summaryTextDelta\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ReasoningSummaryTextDeltaNotification,\n      event.payload,\n    );\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: \"reasoning_summary_text\",\n          delta,\n          ...(payload ? { summaryIndex: payload.summaryIndex } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/reasoning/textDelta\") {\n    const payload = readPayload(EffectCodexSchema.V2ReasoningTextDeltaNotification, event.payload);\n    const delta = event.textDelta ?? payload?.delta;\n    if (!delta || delta.length === 0) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"content.delta\",\n        payload: {\n          streamKind: \"reasoning_text\",\n          delta,\n          ...(payload ? { contentIndex: payload.contentIndex } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/mcpToolCall/progress\") {\n    const payload = readPayload(EffectCodexSchema.V2McpToolCallProgressNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"tool.progress\",\n        payload: {\n          summary: payload.message,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"serverRequest/resolved\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ServerRequestResolvedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    const requestType = toRequestTypeFromKind(event.requestKind);\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"request.resolved\",\n        payload: {\n          requestType,\n          ...(event.payload !== undefined ? { resolution: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"item/tool/requestUserInput/answered\") {\n    const payload = readPayload(EffectCodexSchema.ToolRequestUserInputResponse, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        ...runtimeEventBase(event, canonicalThreadId),\n        type: \"user-input.resolved\",\n        payload: {\n          answers: toCanonicalUserInputAnswers(payload.answers),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"model/rerouted\") {\n    const payload = readPayload(EffectCodexSchema.V2ModelReroutedNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"model.rerouted\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          fromModel: payload.fromModel,\n          toModel: payload.toModel,\n          reason: payload.reason,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"deprecationNotice\") {\n    const payload = readPayload(EffectCodexSchema.V2DeprecationNoticeNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"deprecation.notice\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          summary: payload.summary,\n          ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"configWarning\") {\n    const payload = readPayload(EffectCodexSchema.V2ConfigWarningNotification, event.payload);\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"config.warning\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          summary: payload.summary,\n          ...(trimText(payload.details) ? { details: trimText(payload.details) } : {}),\n          ...(trimText(payload.path) ? { path: trimText(payload.path) } : {}),\n          ...(payload.range !== undefined && payload.range !== null\n            ? { range: payload.range }\n            : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"account/updated\") {\n    if (!readPayload(EffectCodexSchema.V2AccountUpdatedNotification, event.payload)) {\n      return [];\n    }\n    return [\n      {\n        type: \"account.updated\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          account: event.payload ?? {},\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"account/rateLimits/updated\") {\n    if (!readPayload(EffectCodexSchema.V2AccountRateLimitsUpdatedNotification, event.payload)) {\n      return [];\n    }\n    return [\n      {\n        type: \"account.rate-limits.updated\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          rateLimits: event.payload ?? {},\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"mcpServer/oauthLogin/completed\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2McpServerOauthLoginCompletedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"mcp.oauth.completed\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          success: payload.success,\n          name: payload.name,\n          ...(trimText(payload.error) ? { error: trimText(payload.error) } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/started\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeStartedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.realtime.started\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          realtimeSessionId: payload.realtimeSessionId ?? undefined,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/itemAdded\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeItemAddedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.realtime.item-added\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          item: payload.item,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/outputAudio/delta\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeOutputAudioDeltaNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    return [\n      {\n        type: \"thread.realtime.audio.delta\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          audio: payload.audio,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/error\") {\n    const payload = readPayload(EffectCodexSchema.V2ThreadRealtimeErrorNotification, event.payload);\n    const message = payload?.message ?? event.message ?? \"Realtime error\";\n    return [\n      {\n        type: \"thread.realtime.error\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          message,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"thread/realtime/closed\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2ThreadRealtimeClosedNotification,\n      event.payload,\n    );\n    return [\n      {\n        type: \"thread.realtime.closed\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          reason: payload?.reason ?? event.message,\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"error\") {\n    const payload = readPayload(EffectCodexSchema.V2ErrorNotification, event.payload);\n    const message = payload?.error.message ?? event.message ?? \"Provider runtime error\";\n    const willRetry = payload?.willRetry === true;\n    return [\n      {\n        type: willRetry ? \"runtime.warning\" : \"runtime.error\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          message,\n          ...(!willRetry ? { class: \"provider_error\" as const } : {}),\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"process/stderr\") {\n    const message = event.message ?? \"Codex process stderr\";\n    const isFatal = isFatalCodexProcessStderrMessage(message);\n    return [\n      isFatal\n        ? {\n            type: \"runtime.error\",\n            ...runtimeEventBase(event, canonicalThreadId),\n            payload: {\n              message,\n              class: \"provider_error\" as const,\n              ...(event.payload !== undefined ? { detail: event.payload } : {}),\n            },\n          }\n        : {\n            type: \"runtime.warning\",\n            ...runtimeEventBase(event, canonicalThreadId),\n            payload: {\n              message,\n              ...(event.payload !== undefined ? { detail: event.payload } : {}),\n            },\n          },\n    ];\n  }\n\n  if (event.method === \"windows/worldWritableWarning\") {\n    if (!readPayload(EffectCodexSchema.V2WindowsWorldWritableWarningNotification, event.payload)) {\n      return [];\n    }\n    return [\n      {\n        type: \"runtime.warning\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          message: event.message ?? \"Windows world-writable warning\",\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n    ];\n  }\n\n  if (event.method === \"windowsSandbox/setupCompleted\") {\n    const payload = readPayload(\n      EffectCodexSchema.V2WindowsSandboxSetupCompletedNotification,\n      event.payload,\n    );\n    if (!payload) {\n      return [];\n    }\n    const successMessage = event.message ?? \"Windows sandbox setup completed\";\n    const failureMessage = event.message ?? \"Windows sandbox setup failed\";\n\n    return [\n      {\n        type: \"session.state.changed\",\n        ...runtimeEventBase(event, canonicalThreadId),\n        payload: {\n          state: payload.success === false ? \"error\" : \"ready\",\n          reason: payload.success === false ? failureMessage : successMessage,\n          ...(event.payload !== undefined ? { detail: event.payload } : {}),\n        },\n      },\n      ...(payload.success === false\n        ? [\n            {\n              type: \"runtime.warning\" as const,\n              ...runtimeEventBase(event, canonicalThreadId),\n              payload: {\n                message: failureMessage,\n                ...(event.payload !== undefined ? { detail: event.payload } : {}),\n              },\n            },\n          ]\n        : []),\n    ];\n  }\n\n  return [];\n}\n\n/**\n * Build a Codex provider adapter bound to a specific `CodexSettings` payload.\n *\n * The adapter is a captured closure over `codexConfig` — the `binaryPath` and\n * `homePath` are read from that payload, not from `ServerSettingsService`.\n * This is what makes multi-instance routing possible: each `ProviderInstance`\n * in the registry owns its own closure with its own config, so two Codex\n * instances with different `homePath`s cannot step on each other.\n */\nexport const makeCodexAdapter = Effect.fn(\"makeCodexAdapter\")(function* (\n  codexConfig: CodexSettings,\n  options?: CodexAdapterLiveOptions,\n) {\n  const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make(\"codex\");\n  const fileSystem = yield* FileSystem.FileSystem;\n  const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const crypto = yield* Crypto.Crypto;\n  const serverConfig = yield* Effect.service(ServerConfig);\n  const nativeEventLogger =\n    options?.nativeEventLogger ??\n    (options?.nativeEventLogPath !== undefined\n      ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {\n          stream: \"native\",\n        })\n      : undefined);\n  const managedNativeEventLogger =\n    options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n  const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();\n  const sessions = new Map<ThreadId, CodexAdapterSessionContext>();\n\n  const startSession: CodexAdapterShape[\"startSession\"] = (input) =>\n    Effect.scoped(\n      Effect.gen(function* () {\n        if (input.provider !== undefined && input.provider !== PROVIDER) {\n          return yield* new ProviderAdapterValidationError({\n            provider: PROVIDER,\n            operation: \"startSession\",\n            issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,\n          });\n        }\n\n        const existing = sessions.get(input.threadId);\n        if (existing && !existing.stopped) {\n          yield* Effect.suspend(() => stopSessionInternal(existing));\n        }\n\n        const serviceTier =\n          input.modelSelection?.instanceId === boundInstanceId\n            ? getCodexServiceTierOptionValue(input.modelSelection)\n            : undefined;\n        const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);\n        const runtimeInput: CodexSessionRuntimeOptions = {\n          threadId: input.threadId,\n          providerInstanceId: boundInstanceId,\n          cwd: input.cwd ?? process.cwd(),\n          binaryPath: codexConfig.binaryPath,\n          launchArgs: resolveCodexLaunchArgs(codexConfig.launchArgs, options?.environment),\n          ...(options?.environment ? { environment: options.environment } : {}),\n          ...(codexConfig.homePath ? { homePath: codexConfig.homePath } : {}),\n          ...(isCodexResumeCursorSchema(input.resumeCursor)\n            ? { resumeCursor: input.resumeCursor }\n            : {}),\n          runtimeMode: input.runtimeMode,\n          ...(input.modelSelection?.instanceId === boundInstanceId\n            ? { model: input.modelSelection.model }\n            : {}),\n          ...(serviceTier ? { serviceTier } : {}),\n          ...(mcpSession\n            ? {\n                environment: {\n                  ...(options?.environment ?? process.env),\n                  SYNAPTIC_MCP_BEARER_TOKEN: mcpSession.authorizationHeader.replace(\n                    /^Bearer\\s+/,\n                    \"\",\n                  ),\n                },\n                appServerArgs: [\n                  \"-c\",\n                  `mcp_servers.synaptic-code.url=${mcpSession.endpoint}`,\n                  \"-c\",\n                  'mcp_servers.synaptic-code.bearer_token_env_var=\"SYNAPTIC_MCP_BEARER_TOKEN\"',\n                ],\n              }\n            : {}),\n        };\n        const sessionScope = yield* Scope.make(\"sequential\");\n        let sessionScopeTransferred = false;\n        yield* Effect.addFinalizer(() =>\n          sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),\n        );\n        const createRuntime = options?.makeRuntime ?? makeCodexSessionRuntime;\n        const runtime = yield* createRuntime(runtimeInput).pipe(\n          Effect.provideService(Scope.Scope, sessionScope),\n          Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),\n          Effect.provideService(Crypto.Crypto, crypto),\n          Effect.mapError(\n            (cause) =>\n              new ProviderAdapterProcessError({\n                provider: PROVIDER,\n                threadId: input.threadId,\n                detail: cause.message,\n                cause,\n              }),\n          ),\n        );\n\n        const eventFiber = yield* Stream.runForEach(runtime.events, (event) =>\n          Effect.gen(function* () {\n            yield* writeNativeEvent(event);\n            const runtimeEvents = mapToRuntimeEvents(event, event.threadId);\n            if (runtimeEvents.length === 0) {\n              yield* Effect.logDebug(\"ignoring unhandled Codex provider event\", {\n                method: event.method,\n                threadId: event.threadId,\n                turnId: event.turnId,\n                itemId: event.itemId,\n              });\n              return;\n            }\n            yield* Queue.offerAll(runtimeEventQueue, runtimeEvents);\n          }),\n        ).pipe(Effect.forkChild);\n\n        const started = yield* runtime.start().pipe(\n          Effect.mapError(\n            (cause) =>\n              new ProviderAdapterProcessError({\n                provider: PROVIDER,\n                threadId: input.threadId,\n                detail: cause.message,\n                cause,\n              }),\n          ),\n          Effect.onError(() =>\n            runtime.close.pipe(\n              Effect.andThen(Effect.ignore(Scope.close(sessionScope, Exit.void))),\n              Effect.andThen(Fiber.interrupt(eventFiber)),\n              Effect.ignore,\n            ),\n          ),\n        );\n\n        sessions.set(input.threadId, {\n          threadId: input.threadId,\n          scope: sessionScope,\n          runtime,\n          eventFiber,\n          stopped: false,\n        });\n        sessionScopeTransferred = true;\n\n        return started;\n      }),\n    );\n\n  const resolveAttachment = Effect.fn(\"resolveAttachment\")(function* (\n    input: ProviderSendTurnInput,\n    attachment: NonNullable<ProviderSendTurnInput[\"attachments\"]>[number],\n  ) {\n    const attachmentPath = resolveAttachmentPath({\n      attachmentsDir: serverConfig.attachmentsDir,\n      attachment,\n    });\n    if (!attachmentPath) {\n      return yield* new ProviderAdapterRequestError({\n        provider: PROVIDER,\n        method: \"turn/start\",\n        detail: `Invalid attachment id '${attachment.id}'.`,\n      });\n    }\n    const bytes = yield* fileSystem.readFile(attachmentPath).pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"turn/start\",\n            detail: `Failed to read attachment file: ${cause.message}.`,\n            cause,\n          }),\n      ),\n    );\n    return {\n      type: \"image\" as const,\n      url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString(\"base64\")}`,\n    };\n  });\n\n  const sendTurn: CodexAdapterShape[\"sendTurn\"] = Effect.fn(\"sendTurn\")(function* (input) {\n    const codexAttachments = yield* Effect.forEach(\n      input.attachments ?? [],\n      (attachment) => resolveAttachment(input, attachment),\n      { concurrency: 1 },\n    );\n\n    const session = yield* requireSession(input.threadId);\n    const reasoningEffort =\n      input.modelSelection?.instanceId === boundInstanceId\n        ? getModelSelectionStringOptionValue(input.modelSelection, \"reasoningEffort\")\n        : undefined;\n    const serviceTier =\n      input.modelSelection?.instanceId === boundInstanceId\n        ? getCodexServiceTierOptionValue(input.modelSelection)\n        : undefined;\n    return yield* session.runtime\n      .sendTurn({\n        ...(input.input !== undefined ? { input: input.input } : {}),\n        ...(input.modelSelection?.instanceId === boundInstanceId\n          ? { model: input.modelSelection.model }\n          : {}),\n        ...(reasoningEffort\n          ? {\n              effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort,\n            }\n          : {}),\n        ...(serviceTier ? { serviceTier } : {}),\n        ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),\n        ...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),\n      })\n      .pipe(Effect.mapError((cause) => mapCodexRuntimeError(input.threadId, \"turn/start\", cause)));\n  });\n\n  const requireSession = Effect.fn(\"requireSession\")(function* (threadId: ThreadId) {\n    const session = sessions.get(threadId);\n    if (!session || session.stopped) {\n      return yield* new ProviderAdapterSessionNotFoundError({\n        provider: PROVIDER,\n        threadId,\n      });\n    }\n    return session;\n  });\n\n  const interruptTurn: CodexAdapterShape[\"interruptTurn\"] = (threadId, turnId) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.interruptTurn(turnId)),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"turn/interrupt\", cause),\n      ),\n    );\n\n  const readThread: CodexAdapterShape[\"readThread\"] = (threadId) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.readThread),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"thread/read\", cause),\n      ),\n      Effect.map((snapshot) => ({\n        threadId,\n        turns: snapshot.turns,\n      })),\n    );\n\n  const rollbackThread: CodexAdapterShape[\"rollbackThread\"] = (threadId, numTurns) => {\n    if (!Number.isInteger(numTurns) || numTurns < 1) {\n      return Effect.fail(\n        new ProviderAdapterValidationError({\n          provider: PROVIDER,\n          operation: \"rollbackThread\",\n          issue: \"numTurns must be an integer >= 1.\",\n        }),\n      );\n    }\n\n    return requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.rollbackThread(numTurns)),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"thread/rollback\", cause),\n      ),\n      Effect.map((snapshot) => ({\n        threadId,\n        turns: snapshot.turns,\n      })),\n    );\n  };\n\n  const respondToRequest: CodexAdapterShape[\"respondToRequest\"] = (threadId, requestId, decision) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.respondToRequest(requestId, decision)),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"item/requestApproval/decision\", cause),\n      ),\n    );\n\n  const respondToUserInput: CodexAdapterShape[\"respondToUserInput\"] = (\n    threadId,\n    requestId,\n    answers,\n  ) =>\n    requireSession(threadId).pipe(\n      Effect.flatMap((session) => session.runtime.respondToUserInput(requestId, answers)),\n      Effect.mapError((cause) =>\n        cause._tag === \"ProviderAdapterSessionNotFoundError\"\n          ? cause\n          : mapCodexRuntimeError(threadId, \"item/tool/requestUserInput\", cause),\n      ),\n    );\n\n  const writeNativeEvent = Effect.fnUntraced(function* (event: ProviderEvent) {\n    if (!nativeEventLogger) {\n      return;\n    }\n    yield* nativeEventLogger.write(event, event.threadId);\n  });\n\n  const stopSessionInternal = Effect.fn(\"stopSessionInternal\")(function* (\n    session: CodexAdapterSessionContext,\n  ) {\n    if (session.stopped) {\n      return;\n    }\n    session.stopped = true;\n    sessions.delete(session.threadId);\n    yield* session.runtime.close.pipe(Effect.ignore);\n    yield* Effect.ignore(Scope.close(session.scope, Exit.void));\n    yield* Fiber.interrupt(session.eventFiber).pipe(Effect.ignore);\n  });\n\n  const stopSession: CodexAdapterShape[\"stopSession\"] = (threadId) =>\n    Effect.gen(function* () {\n      const session = sessions.get(threadId);\n      if (!session) {\n        return;\n      }\n      yield* stopSessionInternal(session);\n    });\n\n  const listSessions: CodexAdapterShape[\"listSessions\"] = () =>\n    Effect.forEach(\n      Array.from(sessions.values()).filter((session) => !session.stopped),\n      (session) => session.runtime.getSession,\n      { concurrency: 1 },\n    );\n\n  const hasSession: CodexAdapterShape[\"hasSession\"] = (threadId) =>\n    Effect.succeed(Boolean(sessions.get(threadId) && !sessions.get(threadId)?.stopped));\n\n  const stopAll: CodexAdapterShape[\"stopAll\"] = () =>\n    Effect.forEach(Array.from(sessions.values()), stopSessionInternal, {\n      concurrency: 1,\n      discard: true,\n    }).pipe(Effect.asVoid);\n\n  yield* Effect.acquireRelease(Effect.void, () =>\n    stopAll().pipe(\n      Effect.andThen(Queue.shutdown(runtimeEventQueue)),\n      Effect.andThen(managedNativeEventLogger?.close() ?? Effect.void),\n      Effect.ignore,\n    ),\n  );\n\n  return {\n    provider: PROVIDER,\n    capabilities: {\n      sessionModelSwitch: \"in-session\",\n    },\n    startSession,\n    sendTurn,\n    interruptTurn,\n    readThread,\n    rollbackThread,\n    respondToRequest,\n    respondToUserInput,\n    stopSession,\n    listSessions,\n    hasSession,\n    stopAll,\n    get streamEvents() {\n      return Stream.fromQueue(runtimeEventQueue);\n    },\n  } satisfies CodexAdapterShape;\n});\n\n// NOTE: the old `CodexAdapterLive` / `makeCodexAdapterLive` singleton Layer\n// exports have been removed as part of the per-instance-driver refactor.\n// `makeCodexAdapter(codexConfig, options?)` is now invoked directly by\n// `CodexDriver.create()` for each configured instance; downstream consumers\n// (server bootstrap, integration harness, this module's tests) will be\n// migrated to the registry in a follow-up pass.\n","/**\n * CodexDriver — first concrete `ProviderDriver` in the new per-instance model.\n *\n * A driver is a plain value (not a Context.Service) whose `create()` returns\n * one `ProviderInstance` bundling:\n *   - `snapshot`   — the live `ServerProviderShape` for this instance;\n *   - `adapter`    — the Codex session/turn/approval runtime;\n *   - `textGeneration` — commit/PR/branch/title generation via `codex exec`.\n *\n * Each call to `create()` captures the `codexConfig` argument in closures\n * owned by the returned instance. Two instances created with different\n * `homePath`s (e.g. `codex_personal` + `codex_work`) therefore run with\n * fully independent Codex app-server processes and `CODEX_HOME`\n * environments — no shared mutable state.\n *\n * Resource lifecycle: `create()` runs in a scope handed in by the registry.\n * Closing that scope releases the adapter's child processes, the managed\n * snapshot's refresh fibre, and the text-generation binaries' transient\n * scratch files. The registry uses this to tear down an instance when its\n * `providerInstances` entry disappears or its config changes.\n *\n * @module provider/Drivers/CodexDriver\n */\nimport { CodexSettings, ProviderDriverKind, type ServerProvider } from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { makeCodexTextGeneration } from \"../../textGeneration/CodexTextGeneration.ts\";\nimport * as BackgroundPolicy from \"../../background/BackgroundPolicy.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { ProviderDriverError } from \"../Errors.ts\";\nimport { makeCodexAdapter } from \"../Layers/CodexAdapter.ts\";\nimport { checkCodexProviderStatus, makePendingCodexProvider } from \"../Layers/CodexProvider.ts\";\nimport { ProviderEventLoggers } from \"../Layers/ProviderEventLoggers.ts\";\nimport { makeManagedServerProvider } from \"../makeManagedServerProvider.ts\";\nimport type { ProviderDriver, ProviderInstance } from \"../ProviderDriver.ts\";\nimport type { ServerProviderDraft } from \"../providerSnapshot.ts\";\nimport { mergeProviderInstanceEnvironment } from \"../ProviderInstanceEnvironment.ts\";\nimport {\n  enrichProviderSnapshotWithVersionAdvisory,\n  makePackageManagedProviderMaintenanceResolver,\n  resolveProviderMaintenanceCapabilitiesEffect,\n} from \"../providerMaintenance.ts\";\nimport {\n  haveProviderSnapshotSettingsChanged,\n  makeProviderSnapshotSettingsSource,\n  type ProviderSnapshotSettings,\n} from \"../providerUpdateSettings.ts\";\nimport {\n  codexContinuationIdentity,\n  materializeCodexShadowHome,\n  resolveCodexHomeLayout,\n} from \"./CodexHomeLayout.ts\";\nconst decodeCodexSettings = Schema.decodeSync(CodexSettings);\n\nconst DRIVER_KIND = ProviderDriverKind.make(\"codex\");\nconst UPDATE = makePackageManagedProviderMaintenanceResolver({\n  provider: DRIVER_KIND,\n  npmPackageName: \"@openai/codex\",\n  homebrewFormula: \"codex\",\n  nativeUpdate: null,\n});\n\n/**\n * Services the driver needs to materialize an instance. Surfaced as the\n * driver's `R` so the registry layer aggregates these across every\n * registered driver and the runtime satisfies them once.\n */\nexport type CodexDriverEnv =\n  | BackgroundPolicy.BackgroundPolicy\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | HttpClient.HttpClient\n  | Path.Path\n  | ProviderEventLoggers\n  | ServerConfig\n  | ServerSettingsService;\n\n/**\n * Stamp instance identity onto a `ServerProvider` snapshot produced by the\n * driver-kind-only codex helpers. Once `buildServerProvider` in\n * `providerSnapshot.ts` is widened to accept `instanceId`/`driver`, this\n * wrapper disappears.\n */\nconst withInstanceIdentity =\n  (input: {\n    readonly instanceId: ProviderInstance[\"instanceId\"];\n    readonly displayName: string | undefined;\n    readonly accentColor: string | undefined;\n    readonly continuationGroupKey: string;\n  }) =>\n  (snapshot: ServerProviderDraft): ServerProvider => ({\n    ...snapshot,\n    instanceId: input.instanceId,\n    driver: DRIVER_KIND,\n    ...(input.displayName ? { displayName: input.displayName } : {}),\n    ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n    continuation: { groupKey: input.continuationGroupKey },\n  });\n\nexport const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {\n  driverKind: DRIVER_KIND,\n  metadata: {\n    displayName: \"Codex\",\n    supportsMultipleInstances: true,\n  },\n  configSchema: CodexSettings,\n  defaultConfig: (): CodexSettings => decodeCodexSettings({}),\n  create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n    Effect.gen(function* () {\n      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n      const httpClient = yield* HttpClient.HttpClient;\n      const serverSettings = yield* ServerSettingsService;\n      const eventLoggers = yield* ProviderEventLoggers;\n      const processEnv = mergeProviderInstanceEnvironment(environment);\n      const homeLayout = yield* resolveCodexHomeLayout(config);\n      const continuationIdentity = codexContinuationIdentity(homeLayout);\n      const stampIdentity = withInstanceIdentity({\n        instanceId,\n        displayName,\n        accentColor,\n        continuationGroupKey: continuationIdentity.continuationKey,\n      });\n      yield* materializeCodexShadowHome(homeLayout).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProviderDriverError({\n              driver: DRIVER_KIND,\n              instanceId,\n              detail: cause.message,\n              cause,\n            }),\n        ),\n      );\n      const effectiveConfig = {\n        ...config,\n        enabled,\n        homePath: homeLayout.effectiveHomePath ?? \"\",\n      } satisfies CodexSettings;\n      const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {\n        binaryPath: effectiveConfig.binaryPath,\n        env: processEnv,\n      });\n\n      // `makeCodexAdapter` and `makeCodexTextGeneration` have `never` error\n      // channels at construction time — their failure modes are all on the\n      // per-operation closures they return. No `mapError` wrapper is needed\n      // here; the registry only has to worry about snapshot-build and\n      // spawner-availability failures surfaced from `checkCodexProviderStatus`\n      // below.\n      const adapter = yield* makeCodexAdapter(effectiveConfig, {\n        instanceId,\n        environment: processEnv,\n        ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n      });\n      const textGeneration = yield* makeCodexTextGeneration(effectiveConfig, processEnv);\n\n      // Build a managed snapshot whose settings never change — mutations come\n      // in as instance rebuilds from the registry rather than in-place\n      // updates. Pre-provide `ChildProcessSpawner` so the check fits\n      // `makeManagedServerProvider.checkProvider`'s `R = never`.\n      const checkProvider = checkCodexProviderStatus(effectiveConfig, undefined, processEnv).pipe(\n        Effect.map(stampIdentity),\n        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n      );\n      const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);\n      const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CodexSettings>>({\n        maintenanceCapabilities,\n        getSettings: snapshotSettings.getSettings,\n        streamSettings: snapshotSettings.streamSettings,\n        haveSettingsChanged: haveProviderSnapshotSettingsChanged,\n        initialSnapshot: (settings) =>\n          makePendingCodexProvider(settings.provider).pipe(Effect.map(stampIdentity)),\n        checkProvider,\n        enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>\n          enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {\n            enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n          }).pipe(\n            Effect.provideService(HttpClient.HttpClient, httpClient),\n            Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),\n          ),\n      }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProviderDriverError({\n              driver: DRIVER_KIND,\n              instanceId,\n              detail: `Failed to build Codex snapshot: ${cause.message ?? String(cause)}`,\n              cause,\n            }),\n        ),\n      );\n\n      return {\n        instanceId,\n        driverKind: DRIVER_KIND,\n        continuationIdentity,\n        displayName,\n        accentColor,\n        enabled,\n        snapshot,\n        adapter,\n        textGeneration,\n      } satisfies ProviderInstance;\n    }),\n};\n","// This file is generated by the effect-acp package. Do not edit manually.\n// Current ACP schema release: v0.11.3\n\nimport * as Schema from \"effect/Schema\";\n\nexport type AuthEnvVar = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly label?: string | null;\n  readonly name: string;\n  readonly optional?: boolean;\n  readonly secret?: boolean;\n};\nexport const AuthEnvVar = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  label: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Human-readable label for this variable, displayed in client UI.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({\n    description: 'The environment variable name (e.g. `\"OPENAI_API_KEY\"`).',\n  }),\n  optional: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether this variable is optional.\\n\\nDefaults to `false`.\",\n      default: false,\n    }),\n  ),\n  secret: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether this value is a secret (e.g. API key, token).\\nClients should use a password-style input for secret vars.\\n\\nDefaults to `true`.\",\n      default: true,\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nDescribes a single environment variable for an [`AuthMethodEnvVar`] authentication method.\",\n});\n\nexport type AvailableCommandInput = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly hint: string;\n};\nexport const AvailableCommandInput = Schema.Union([\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    hint: Schema.String.annotate({\n      description: \"A hint to display when the input hasn't been provided yet\",\n    }),\n  }).annotate({\n    title: \"unstructured\",\n    description: \"All text that was typed after the command name is provided as input.\",\n  }),\n]).annotate({ description: \"The input specification for a command.\" });\n\nexport type Cost = { readonly amount: number; readonly currency: string };\nexport const Cost = Schema.Struct({\n  amount: Schema.Number.annotate({\n    description: \"Total cumulative cost for session.\",\n    format: \"double\",\n  }).check(Schema.isFinite()),\n  currency: Schema.String.annotate({ description: 'ISO 4217 currency code (e.g., \"USD\", \"EUR\").' }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nCost information for a session.\",\n});\n\nexport type ElicitationContentValue = string | number | number | boolean | ReadonlyArray<string>;\nexport const ElicitationContentValue = Schema.Union([\n  Schema.String.annotate({ title: \"String\" }),\n  Schema.Number.annotate({ title: \"Integer\", format: \"int64\" }).check(Schema.isInt()),\n  Schema.Number.annotate({ title: \"Number\", format: \"double\" }).check(Schema.isFinite()),\n  Schema.Boolean.annotate({ title: \"Boolean\" }),\n  Schema.Array(Schema.String).annotate({ title: \"StringArray\" }),\n]);\n\nexport type ElicitationFormCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n};\nexport const ElicitationFormCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nForm-based elicitation capabilities.\",\n});\n\nexport type ElicitationUrlCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n};\nexport const ElicitationUrlCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nURL-based elicitation capabilities.\",\n});\n\nexport type EmbeddedResourceResource =\n  | {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly mimeType?: string | null;\n      readonly text: string;\n      readonly uri: string;\n    }\n  | {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly blob: string;\n      readonly mimeType?: string | null;\n      readonly uri: string;\n    };\nexport const EmbeddedResourceResource = Schema.Union([\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    text: Schema.String,\n    uri: Schema.String,\n  }).annotate({ title: \"TextResourceContents\", description: \"Text-based resource contents.\" }),\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    blob: Schema.String,\n    mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    uri: Schema.String,\n  }).annotate({ title: \"BlobResourceContents\", description: \"Binary resource contents.\" }),\n]).annotate({ description: \"Resource content that can be embedded in a message.\" });\n\nexport type EnumOption = { readonly const: string; readonly title: string };\nexport const EnumOption = Schema.Struct({\n  const: Schema.String.annotate({ description: \"The constant value for this option.\" }),\n  title: Schema.String.annotate({ description: \"Human-readable title for this option.\" }),\n}).annotate({ description: \"A titled enum option with a const value and human-readable title.\" });\n\nexport type EnvVariable = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly name: string;\n  readonly value: string;\n};\nexport const EnvVariable = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({ description: \"The name of the environment variable.\" }),\n  value: Schema.String.annotate({ description: \"The value to set for the environment variable.\" }),\n}).annotate({ description: \"An environment variable to set when launching an MCP server.\" });\n\nexport type Error = {\n  readonly code:\n    | -32700\n    | -32600\n    | -32601\n    | -32602\n    | -32603\n    | -32800\n    | -32000\n    | -32002\n    | -32042\n    | number;\n  readonly data?: unknown;\n  readonly message: string;\n};\nexport const Error = Schema.Struct({\n  code: Schema.Union([\n    Schema.Literal(-32700).annotate({\n      title: \"Parse error\",\n      description:\n        \"**Parse error**: Invalid JSON was received by the server.\\nAn error occurred on the server while parsing the JSON text.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32600).annotate({\n      title: \"Invalid request\",\n      description: \"**Invalid request**: The JSON sent is not a valid Request object.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32601).annotate({\n      title: \"Method not found\",\n      description: \"**Method not found**: The method does not exist or is not available.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32602).annotate({\n      title: \"Invalid params\",\n      description: \"**Invalid params**: Invalid method parameter(s).\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32603).annotate({\n      title: \"Internal error\",\n      description:\n        \"**Internal error**: Internal JSON-RPC error.\\nReserved for implementation-defined server errors.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32800).annotate({\n      title: \"Request cancelled\",\n      description:\n        \"**Request cancelled**: **UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nExecution of the method was aborted either due to a cancellation request from the caller or\\nbecause of resource constraints or shutdown.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32000).annotate({\n      title: \"Authentication required\",\n      description:\n        \"**Authentication required**: Authentication is required before this operation can be performed.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32002).annotate({\n      title: \"Resource not found\",\n      description: \"**Resource not found**: A given resource, such as a file, was not found.\",\n      format: \"int32\",\n    }),\n    Schema.Literal(-32042).annotate({\n      title: \"URL elicitation required\",\n      description:\n        \"**URL elicitation required**: **UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe agent requires user input via a URL-based elicitation before it can proceed.\",\n      format: \"int32\",\n    }),\n    Schema.Number.annotate({\n      title: \"Other\",\n      description: \"Other undefined error code.\",\n      format: \"int32\",\n    }).check(Schema.isInt()),\n  ]).annotate({\n    description:\n      \"Predefined error codes for common JSON-RPC and ACP-specific errors.\\n\\nThese codes follow the JSON-RPC 2.0 specification for standard errors\\nand use the reserved range (-32000 to -32099) for protocol-specific errors.\",\n  }),\n  data: Schema.optionalKey(\n    Schema.Unknown.annotate({\n      description:\n        \"Optional primitive or structured value that contains additional information about the error.\\nThis may include debugging information or context-specific details.\",\n    }),\n  ),\n  message: Schema.String.annotate({\n    description:\n      \"A string providing a short description of the error.\\nThe message should be limited to a concise single sentence.\",\n  }),\n}).annotate({\n  description:\n    \"JSON-RPC error object.\\n\\nRepresents an error that occurred during method execution, following the\\nJSON-RPC 2.0 error object specification with optional additional data.\\n\\nSee protocol docs: [JSON-RPC Error Object](https://www.jsonrpc.org/specification#error_object)\",\n});\n\nexport type HttpHeader = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly name: string;\n  readonly value: string;\n};\nexport const HttpHeader = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({ description: \"The name of the HTTP header.\" }),\n  value: Schema.String.annotate({ description: \"The value to set for the HTTP header.\" }),\n}).annotate({ description: \"An HTTP header to set when making requests to the MCP server.\" });\n\nexport type Implementation = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly name: string;\n  readonly title?: string | null;\n  readonly version: string;\n};\nexport const Implementation = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({\n    description:\n      \"Intended for programmatic or logical use, but can be used as a display\\nname fallback if title isn’t present.\",\n  }),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Intended for UI and end-user contexts — optimized to be human-readable\\nand easily understood.\\n\\nIf not provided, the name should be used for display.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  version: Schema.String.annotate({\n    description:\n      'Version of the implementation. Can be displayed to the user or used\\nfor debugging or metrics purposes. (e.g. \"1.0.0\").',\n  }),\n}).annotate({\n  description:\n    \"Metadata about the implementation of the client or agent.\\nDescribes the name and version of an MCP implementation, with an optional\\ntitle for UI representation.\",\n});\n\nexport type LogoutCapabilities = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const LogoutCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nLogout capabilities supported by the agent.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n});\n\nexport type ModelInfo = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly modelId: string;\n  readonly name: string;\n};\nexport const ModelInfo = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional description of the model.\" }),\n      Schema.Null,\n    ]),\n  ),\n  modelId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable name of the model.\" }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInformation about a selectable model.\",\n});\n\nexport type PermissionOption = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly kind: \"allow_once\" | \"allow_always\" | \"reject_once\" | \"reject_always\";\n  readonly name: string;\n  readonly optionId: string;\n};\nexport const PermissionOption = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  kind: Schema.Literals([\"allow_once\", \"allow_always\", \"reject_once\", \"reject_always\"]).annotate({\n    description:\n      \"The type of permission option being presented to the user.\\n\\nHelps clients choose appropriate icons and UI treatment.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable label to display to the user.\" }),\n  optionId: Schema.String.annotate({ description: \"Unique identifier for a permission option.\" }),\n}).annotate({ description: \"An option presented to the user when requesting permission.\" });\n\nexport type PlanEntry = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content: string;\n  readonly priority: \"high\" | \"medium\" | \"low\";\n  readonly status: \"pending\" | \"in_progress\" | \"completed\";\n};\nexport const PlanEntry = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.String.annotate({\n    description: \"Human-readable description of what this task aims to accomplish.\",\n  }),\n  priority: Schema.Literals([\"high\", \"medium\", \"low\"]).annotate({\n    description:\n      \"Priority levels for plan entries.\\n\\nUsed to indicate the relative importance or urgency of different\\ntasks in the execution plan.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n  }),\n  status: Schema.Literals([\"pending\", \"in_progress\", \"completed\"]).annotate({\n    description:\n      \"Status of a plan entry in the execution flow.\\n\\nTracks the lifecycle of each task from planning through completion.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n  }),\n}).annotate({\n  description:\n    \"A single entry in the execution plan.\\n\\nRepresents a task or goal that the assistant intends to accomplish\\nas part of fulfilling the user's request.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n});\n\nexport type RequestId = null | number | string;\nexport const RequestId = Schema.Union([\n  Schema.Null.annotate({ title: \"Null\" }),\n  Schema.Number.annotate({ title: \"Number\", format: \"int64\" }).check(Schema.isInt()),\n  Schema.String.annotate({ title: \"Str\" }),\n]).annotate({\n  description:\n    \"JSON RPC Request Id\\n\\nAn identifier established by the Client that MUST contain a String, Number, or NULL value if included. If it is not included it is assumed to be a notification. The value SHOULD normally not be Null [1] and Numbers SHOULD NOT contain fractional parts [2]\\n\\nThe Server MUST reply with the same value in the Response object if included. This member is used to correlate the context between the two objects.\\n\\n[1] The use of Null as a value for the id member in a Request object is discouraged, because this specification uses a value of Null for Responses with an unknown id. Also, because JSON-RPC 1.0 uses an id value of Null for Notifications this could cause confusion in handling.\\n\\n[2] Fractional parts may be problematic, since many decimal fractions cannot be represented exactly as binary fractions.\",\n});\n\nexport type Role = \"assistant\" | \"user\";\nexport const Role = Schema.Literals([\"assistant\", \"user\"]).annotate({\n  description: \"The sender or recipient of messages and data in a conversation.\",\n});\n\nexport type SessionCloseCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n};\nexport const SessionCloseCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nCapabilities for the `session/close` method.\\n\\nBy supplying `{}` it means that the agent supports closing of sessions.\",\n});\n\nexport type SessionConfigOptionCategory = \"mode\" | \"model\" | \"thought_level\" | string;\nexport const SessionConfigOptionCategory = Schema.Union([\n  Schema.Literal(\"mode\").annotate({ description: \"Session mode selector.\" }),\n  Schema.Literal(\"model\").annotate({ description: \"Model selector.\" }),\n  Schema.Literal(\"thought_level\").annotate({ description: \"Thought/reasoning level selector.\" }),\n  Schema.String.annotate({ title: \"other\", description: \"Unknown / uncategorized selector.\" }),\n]).annotate({\n  description:\n    \"Semantic category for a session configuration option.\\n\\nThis is intended to help Clients distinguish broadly common selectors (e.g. model selector vs\\nsession mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,\\nplacement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown\\ncategories gracefully.\\n\\nCategory names beginning with `_` are free for custom use, like other ACP extension methods.\\nCategory names that do not begin with `_` are reserved for the ACP spec.\",\n});\n\nexport type SessionConfigSelectOption = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly name: string;\n  readonly value: string;\n};\nexport const SessionConfigSelectOption = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional description for this option value.\" }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({ description: \"Human-readable label for this option value.\" }),\n  value: Schema.String.annotate({\n    description: \"Unique identifier for a session configuration option value.\",\n  }),\n}).annotate({ description: \"A possible value for a session configuration option.\" });\n\nexport type SessionForkCapabilities = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const SessionForkCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nCapabilities for the `session/fork` method.\\n\\nBy supplying `{}` it means that the agent supports forking of sessions.\",\n});\n\nexport type SessionInfo = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly sessionId: string;\n  readonly title?: string | null;\n  readonly updatedAt?: string | null;\n};\nexport const SessionInfo = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({\n    description: \"The working directory for this session. Must be an absolute path.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable title for the session\" }),\n      Schema.Null,\n    ]),\n  ),\n  updatedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"ISO 8601 timestamp of last activity\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Information about a session returned by session/list\" });\n\nexport type SessionListCapabilities = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const SessionListCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Capabilities for the `session/list` method.\\n\\nBy supplying `{}` it means that the agent supports listing of sessions.\",\n});\n\nexport type SessionModeId = string;\nexport const SessionModeId = Schema.String.annotate({\n  description: \"Unique identifier for a Session Mode.\",\n});\n\nexport type SessionResumeCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n};\nexport const SessionResumeCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nCapabilities for the `session/resume` method.\\n\\nBy supplying `{}` it means that the agent supports resuming of sessions.\",\n});\n\nexport type StringFormat = \"email\" | \"uri\" | \"date\" | \"date-time\";\nexport const StringFormat = Schema.Literals([\"email\", \"uri\", \"date\", \"date-time\"]).annotate({\n  description: \"String format types for string properties in elicitation schemas.\",\n});\n\nexport type TerminalExitStatus = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly exitCode?: number | null;\n  readonly signal?: string | null;\n};\nexport const TerminalExitStatus = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  exitCode: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"The process exit code (may be null if terminated by signal).\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  signal: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"The signal that terminated the process (may be null if exited normally).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Exit status of a terminal command.\" });\n\nexport type ToolCallLocation = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly line?: number | null;\n  readonly path: string;\n};\nexport const ToolCallLocation = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  line: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Optional line number within the file.\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({ description: \"The file path being accessed or modified.\" }),\n}).annotate({\n  description:\n    'A file location being accessed or modified by a tool.\\n\\nEnables clients to implement \"follow-along\" features that track\\nwhich files the agent is working with in real-time.\\n\\nSee protocol docs: [Following the Agent](https://agentclientprotocol.com/protocol/tool-calls#following-the-agent)',\n});\n\nexport type ToolCallStatus = \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\nexport const ToolCallStatus = Schema.Literals([\n  \"pending\",\n  \"in_progress\",\n  \"completed\",\n  \"failed\",\n]).annotate({\n  description:\n    \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n});\n\nexport type ToolKind =\n  | \"read\"\n  | \"edit\"\n  | \"delete\"\n  | \"move\"\n  | \"search\"\n  | \"execute\"\n  | \"think\"\n  | \"fetch\"\n  | \"switch_mode\"\n  | \"other\";\nexport const ToolKind = Schema.Literals([\n  \"read\",\n  \"edit\",\n  \"delete\",\n  \"move\",\n  \"search\",\n  \"execute\",\n  \"think\",\n  \"fetch\",\n  \"switch_mode\",\n  \"other\",\n]).annotate({\n  description:\n    \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n});\n\nexport type Usage = {\n  readonly cachedReadTokens?: number | null;\n  readonly cachedWriteTokens?: number | null;\n  readonly inputTokens: number;\n  readonly outputTokens: number;\n  readonly thoughtTokens?: number | null;\n  readonly totalTokens: number;\n};\nexport const Usage = Schema.Struct({\n  cachedReadTokens: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Total cache read tokens.\", format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  cachedWriteTokens: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Total cache write tokens.\", format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  inputTokens: Schema.Number.annotate({\n    description: \"Total input tokens across all turns.\",\n    format: \"uint64\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  outputTokens: Schema.Number.annotate({\n    description: \"Total output tokens across all turns.\",\n    format: \"uint64\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  thoughtTokens: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Total thought/reasoning tokens\", format: \"uint64\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  totalTokens: Schema.Number.annotate({\n    description: \"Sum of all token types across session.\",\n    format: \"uint64\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nToken usage information for a prompt turn.\",\n});\n\nexport type AuthMethod =\n  | {\n      readonly type: \"env_var\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly description?: string | null;\n      readonly id: string;\n      readonly link?: string | null;\n      readonly name: string;\n      readonly vars: ReadonlyArray<AuthEnvVar>;\n    }\n  | {\n      readonly type: \"terminal\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly args?: ReadonlyArray<string>;\n      readonly description?: string | null;\n      readonly env?: { readonly [x: string]: string };\n      readonly id: string;\n      readonly name: string;\n    }\n  | {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly description?: string | null;\n      readonly id: string;\n      readonly name: string;\n    };\nexport const AuthMethod = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"env_var\"),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"Optional description providing more details about this authentication method.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for this authentication method.\",\n    }),\n    link: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional link to a page where the user can obtain their credentials.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    name: Schema.String.annotate({\n      description: \"Human-readable name of the authentication method.\",\n    }),\n    vars: Schema.Array(AuthEnvVar).annotate({\n      description: \"The environment variables the client should set.\",\n    }),\n  }).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nEnvironment variable authentication method.\\n\\nThe user provides credentials that the client passes to the agent as environment variables.\",\n  }),\n  Schema.Struct({\n    type: Schema.Literal(\"terminal\"),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    args: Schema.optionalKey(\n      Schema.Array(Schema.String).annotate({\n        description:\n          \"Additional arguments to pass when running the agent binary for terminal auth.\",\n      }),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"Optional description providing more details about this authentication method.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    env: Schema.optionalKey(\n      Schema.Record(Schema.String, Schema.String).annotate({\n        description:\n          \"Additional environment variables to set when running the agent binary for terminal auth.\",\n      }),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for this authentication method.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name of the authentication method.\",\n    }),\n  }).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nTerminal-based authentication method.\\n\\nThe client runs an interactive terminal for the user to authenticate via a TUI.\",\n  }),\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description:\n            \"Optional description providing more details about this authentication method.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for this authentication method.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name of the authentication method.\",\n    }),\n  }).annotate({\n    title: \"agent\",\n    description:\n      \"Agent handles authentication itself.\\n\\nThis is the default authentication method type.\",\n  }),\n]).annotate({\n  description:\n    \"Describes an available authentication method.\\n\\nThe `type` field acts as the discriminator in the serialized JSON form.\\nWhen no `type` is present, the method is treated as `agent`.\",\n});\n\nexport type AvailableCommand = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description: string;\n  readonly input?: AvailableCommandInput | null;\n  readonly name: string;\n};\nexport const AvailableCommand = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.String.annotate({\n    description: \"Human-readable description of what the command does.\",\n  }),\n  input: Schema.optionalKey(\n    Schema.Union([AvailableCommandInput, Schema.Null]).annotate({\n      description: \"Input for the command if required\",\n    }),\n  ),\n  name: Schema.String.annotate({\n    description: \"Command name (e.g., `create_plan`, `research_codebase`).\",\n  }),\n}).annotate({ description: \"Information about a command.\" });\n\nexport type ElicitationCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly form?: ElicitationFormCapabilities | null;\n  readonly url?: ElicitationUrlCapabilities | null;\n};\nexport const ElicitationCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  form: Schema.optionalKey(\n    Schema.Union([ElicitationFormCapabilities, Schema.Null]).annotate({\n      description: \"Whether the client supports form-based elicitation.\",\n    }),\n  ),\n  url: Schema.optionalKey(\n    Schema.Union([ElicitationUrlCapabilities, Schema.Null]).annotate({\n      description: \"Whether the client supports URL-based elicitation.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nElicitation capabilities supported by the client.\",\n});\n\nexport type McpServer =\n  | {\n      readonly type: \"http\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly headers: ReadonlyArray<HttpHeader>;\n      readonly name: string;\n      readonly url: string;\n    }\n  | {\n      readonly type: \"sse\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly headers: ReadonlyArray<HttpHeader>;\n      readonly name: string;\n      readonly url: string;\n    }\n  | {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly args: ReadonlyArray<string>;\n      readonly command: string;\n      readonly env: ReadonlyArray<EnvVariable>;\n      readonly name: string;\n    };\nexport const McpServer = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"http\"),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    headers: Schema.Array(HttpHeader).annotate({\n      description: \"HTTP headers to set when making requests to the MCP server.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name identifying this MCP server.\",\n    }),\n    url: Schema.String.annotate({ description: \"URL to the MCP server.\" }),\n  }).annotate({ description: \"HTTP transport configuration for MCP.\" }),\n  Schema.Struct({\n    type: Schema.Literal(\"sse\"),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    headers: Schema.Array(HttpHeader).annotate({\n      description: \"HTTP headers to set when making requests to the MCP server.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name identifying this MCP server.\",\n    }),\n    url: Schema.String.annotate({ description: \"URL to the MCP server.\" }),\n  }).annotate({ description: \"SSE transport configuration for MCP.\" }),\n  Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    args: Schema.Array(Schema.String).annotate({\n      description: \"Command-line arguments to pass to the MCP server.\",\n    }),\n    command: Schema.String.annotate({ description: \"Path to the MCP server executable.\" }),\n    env: Schema.Array(EnvVariable).annotate({\n      description: \"Environment variables to set when launching the MCP server.\",\n    }),\n    name: Schema.String.annotate({\n      description: \"Human-readable name identifying this MCP server.\",\n    }),\n  }).annotate({ title: \"stdio\", description: \"Stdio transport configuration for MCP.\" }),\n]).annotate({\n  description:\n    \"Configuration for connecting to an MCP (Model Context Protocol) server.\\n\\nMCP servers provide tools and context that the agent can use when\\nprocessing prompts.\\n\\nSee protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/session-setup#mcp-servers)\",\n});\n\nexport type SessionModelState = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly availableModels: ReadonlyArray<ModelInfo>;\n  readonly currentModelId: string;\n};\nexport const SessionModelState = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  availableModels: Schema.Array(ModelInfo).annotate({\n    description: \"The set of models that the Agent can use\",\n  }),\n  currentModelId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe set of models and the one currently active.\",\n});\n\nexport type Annotations = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly audience?: ReadonlyArray<Role> | null;\n  readonly lastModified?: string | null;\n  readonly priority?: number | null;\n};\nexport const Annotations = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  audience: Schema.optionalKey(Schema.Union([Schema.Array(Role), Schema.Null])),\n  lastModified: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  priority: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ format: \"double\" }).check(Schema.isFinite()),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Optional annotations for the client. The client can use annotations to inform how objects are used or displayed\",\n});\n\nexport type SessionConfigSelectGroup = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly group: string;\n  readonly name: string;\n  readonly options: ReadonlyArray<SessionConfigSelectOption>;\n};\nexport const SessionConfigSelectGroup = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  group: Schema.String.annotate({\n    description: \"Unique identifier for a session configuration option value group.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable label for this group.\" }),\n  options: Schema.Array(SessionConfigSelectOption).annotate({\n    description: \"The set of option values in this group.\",\n  }),\n}).annotate({ description: \"A group of possible values for a session configuration option.\" });\n\nexport type SessionMode = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly id: SessionModeId;\n  readonly name: string;\n};\nexport const SessionMode = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  id: SessionModeId,\n  name: Schema.String,\n}).annotate({\n  description:\n    \"A mode the agent can operate in.\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n});\n\nexport type ElicitationPropertySchema =\n  | {\n      readonly type: \"string\";\n      readonly default?: string | null;\n      readonly description?: string | null;\n      readonly enum?: ReadonlyArray<string> | null;\n      readonly format?: StringFormat | null;\n      readonly maxLength?: number | null;\n      readonly minLength?: number | null;\n      readonly oneOf?: ReadonlyArray<EnumOption> | null;\n      readonly pattern?: string | null;\n      readonly title?: string | null;\n    }\n  | {\n      readonly type: \"number\";\n      readonly default?: number | null;\n      readonly description?: string | null;\n      readonly maximum?: number | null;\n      readonly minimum?: number | null;\n      readonly title?: string | null;\n    }\n  | {\n      readonly type: \"integer\";\n      readonly default?: number | null;\n      readonly description?: string | null;\n      readonly maximum?: number | null;\n      readonly minimum?: number | null;\n      readonly title?: string | null;\n    }\n  | {\n      readonly type: \"boolean\";\n      readonly default?: boolean | null;\n      readonly description?: string | null;\n      readonly title?: string | null;\n    }\n  | {\n      readonly type: \"array\";\n      readonly default?: ReadonlyArray<string> | null;\n      readonly description?: string | null;\n      readonly items:\n        | { readonly enum: ReadonlyArray<string>; readonly type: \"string\" }\n        | { readonly anyOf: ReadonlyArray<EnumOption> };\n      readonly maxItems?: number | null;\n      readonly minItems?: number | null;\n      readonly title?: string | null;\n    };\nexport const ElicitationPropertySchema = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"string\"),\n      default: Schema.optionalKey(\n        Schema.Union([Schema.String.annotate({ description: \"Default value.\" }), Schema.Null]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      enum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.String).annotate({\n            description: \"Enum values for untitled single-select enums.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      format: Schema.optionalKey(\n        Schema.Union([StringFormat, Schema.Null]).annotate({ description: \"String format.\" }),\n      ),\n      maxLength: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ description: \"Maximum string length.\", format: \"uint32\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      minLength: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ description: \"Minimum string length.\", format: \"uint32\" })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      oneOf: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(EnumOption).annotate({\n            description: \"Titled enum options for titled single-select enums.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      pattern: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Pattern the string must match.\" }),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description:\n        'Schema for string properties in an elicitation form.\\n\\nWhen `enum` or `oneOf` is set, this represents a single-select enum\\nwith `\"type\": \"string\"`.',\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"number\"),\n      default: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ description: \"Default value.\", format: \"double\" }).check(\n            Schema.isFinite(),\n          ),\n          Schema.Null,\n        ]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      maximum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Maximum value (inclusive).\",\n            format: \"double\",\n          }).check(Schema.isFinite()),\n          Schema.Null,\n        ]),\n      ),\n      minimum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Minimum value (inclusive).\",\n            format: \"double\",\n          }).check(Schema.isFinite()),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description: \"Schema for number (floating-point) properties in an elicitation form.\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"integer\"),\n      default: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ description: \"Default value.\", format: \"int64\" }).check(\n            Schema.isInt(),\n          ),\n          Schema.Null,\n        ]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      maximum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Maximum value (inclusive).\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      minimum: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Minimum value (inclusive).\",\n            format: \"int64\",\n          }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"Schema for integer properties in an elicitation form.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"boolean\"),\n      default: Schema.optionalKey(\n        Schema.Union([Schema.Boolean.annotate({ description: \"Default value.\" }), Schema.Null]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"Schema for boolean properties in an elicitation form.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"array\"),\n      default: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.String).annotate({ description: \"Default selected values.\" }),\n          Schema.Null,\n        ]),\n      ),\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Human-readable description.\" }),\n          Schema.Null,\n        ]),\n      ),\n      items: Schema.Union([\n        Schema.Struct({\n          enum: Schema.Array(Schema.String).annotate({ description: \"Allowed enum values.\" }),\n          type: Schema.Literal(\"string\").annotate({\n            description: \"Items definition for untitled multi-select enum properties.\",\n          }),\n        }).annotate({\n          title: \"Untitled\",\n          description: \"Items definition for untitled multi-select enum properties.\",\n        }),\n        Schema.Struct({\n          anyOf: Schema.Array(EnumOption).annotate({ description: \"Titled enum options.\" }),\n        }).annotate({\n          title: \"Titled\",\n          description: \"Items definition for titled multi-select enum properties.\",\n        }),\n      ]).annotate({ description: \"Items for a multi-select (array) property schema.\" }),\n      maxItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Maximum number of items to select.\",\n            format: \"uint64\",\n          })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      minItems: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({\n            description: \"Minimum number of items to select.\",\n            format: \"uint64\",\n          })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0)),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the property.\" }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description: \"Schema for multi-select (array) properties in an elicitation form.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    'Property schema for elicitation form fields.\\n\\nEach variant corresponds to a JSON Schema `\"type\"` value.\\nSingle-select enums use the `String` variant with `enum` or `oneOf` set.\\nMulti-select enums use the `Array` variant.',\n});\n\nexport type ContentBlock =\n  | {\n      readonly type: \"text\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly text: string;\n    }\n  | {\n      readonly type: \"image\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly data: string;\n      readonly mimeType: string;\n      readonly uri?: string | null;\n    }\n  | {\n      readonly type: \"audio\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly data: string;\n      readonly mimeType: string;\n    }\n  | {\n      readonly type: \"resource_link\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly description?: string | null;\n      readonly mimeType?: string | null;\n      readonly name: string;\n      readonly size?: number | null;\n      readonly title?: string | null;\n      readonly uri: string;\n    }\n  | {\n      readonly type: \"resource\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly annotations?: Annotations | null;\n      readonly resource: EmbeddedResourceResource;\n    };\nexport const ContentBlock = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"text\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      text: Schema.String,\n    }).annotate({ description: \"Text provided to or from an LLM.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"image\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      data: Schema.String,\n      mimeType: Schema.String,\n      uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n    }).annotate({ description: \"An image provided to or from an LLM.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"audio\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      data: Schema.String,\n      mimeType: Schema.String,\n    }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"resource_link\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      name: Schema.String,\n      size: Schema.optionalKey(\n        Schema.Union([\n          Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      uri: Schema.String,\n    }).annotate({\n      description:\n        \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"resource\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n      resource: EmbeddedResourceResource,\n    }).annotate({\n      description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n});\n\nexport type ToolCallContent =\n  | {\n      readonly type: \"content\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content:\n        | {\n            readonly type: \"text\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly text: string;\n          }\n        | {\n            readonly type: \"image\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n            readonly uri?: string | null;\n          }\n        | {\n            readonly type: \"audio\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n          }\n        | {\n            readonly type: \"resource_link\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly description?: string | null;\n            readonly mimeType?: string | null;\n            readonly name: string;\n            readonly size?: number | null;\n            readonly title?: string | null;\n            readonly uri: string;\n          }\n        | {\n            readonly type: \"resource\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly resource: EmbeddedResourceResource;\n          };\n    }\n  | {\n      readonly type: \"diff\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly newText: string;\n      readonly oldText?: string | null;\n      readonly path: string;\n    }\n  | {\n      readonly type: \"terminal\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly terminalId: string;\n    };\nexport const ToolCallContent = Schema.Union(\n  [\n    Schema.Struct({\n      type: Schema.Literal(\"content\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.Union(\n        [\n          Schema.Struct({\n            type: Schema.Literal(\"text\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            text: Schema.String,\n          }).annotate({ description: \"Text provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"image\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n            uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n          }).annotate({ description: \"An image provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"audio\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n          }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource_link\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            name: Schema.String,\n            size: Schema.optionalKey(\n              Schema.Union([\n                Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                Schema.Null,\n              ]),\n            ),\n            title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            uri: Schema.String,\n          }).annotate({\n            description:\n              \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n          }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            resource: EmbeddedResourceResource,\n          }).annotate({\n            description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n          }),\n        ],\n        { mode: \"oneOf\" },\n      ).annotate({\n        description:\n          \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n      }),\n    }).annotate({ description: \"Standard content block (text, images, resources).\" }),\n    Schema.Struct({\n      type: Schema.Literal(\"diff\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      newText: Schema.String.annotate({ description: \"The new content after modification.\" }),\n      oldText: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"The original content (None for new files).\" }),\n          Schema.Null,\n        ]),\n      ),\n      path: Schema.String.annotate({ description: \"The file path being modified.\" }),\n    }).annotate({\n      description:\n        \"A diff representing file modifications.\\n\\nShows changes to files in a format suitable for display in the client UI.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/tool-calls#content)\",\n    }),\n    Schema.Struct({\n      type: Schema.Literal(\"terminal\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      terminalId: Schema.String,\n    }).annotate({\n      description:\n        \"Embed a terminal created with `terminal/create` by its id.\\n\\nThe terminal must be added before calling `terminal/release`.\\n\\nSee protocol docs: [Terminal](https://agentclientprotocol.com/protocol/terminals)\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Content produced by a tool call.\\n\\nTool calls can produce different types of content including\\nstandard content blocks (text, images) or file diffs.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/tool-calls#content)\",\n});\n\nexport type SessionConfigOption =\n  | {\n      readonly type: \"select\";\n      readonly currentValue: string;\n      readonly options:\n        | ReadonlyArray<SessionConfigSelectOption>\n        | ReadonlyArray<SessionConfigSelectGroup>;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly category?: SessionConfigOptionCategory | null;\n      readonly description?: string | null;\n      readonly id: string;\n      readonly name: string;\n    }\n  | {\n      readonly type: \"boolean\";\n      readonly currentValue: boolean;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly category?: SessionConfigOptionCategory | null;\n      readonly description?: string | null;\n      readonly id: string;\n      readonly name: string;\n    };\nexport const SessionConfigOption = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"select\"),\n    currentValue: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option value.\",\n    }),\n    options: Schema.Union([\n      Schema.Array(SessionConfigSelectOption).annotate({\n        title: \"Ungrouped\",\n        description: \"A flat list of options with no grouping.\",\n      }),\n      Schema.Array(SessionConfigSelectGroup).annotate({\n        title: \"Grouped\",\n        description: \"A list of options grouped under headers.\",\n      }),\n    ]).annotate({ description: \"Possible values for a session configuration option.\" }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    category: Schema.optionalKey(\n      Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({\n        description: \"Optional semantic category for this option (UX only).\",\n      }),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional description for the Client to display to the user.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option.\",\n    }),\n    name: Schema.String.annotate({ description: \"Human-readable label for the option.\" }),\n  }).annotate({ description: \"A session configuration option selector and its current state.\" }),\n  Schema.Struct({\n    type: Schema.Literal(\"boolean\"),\n    currentValue: Schema.Boolean.annotate({\n      description: \"The current value of the boolean option.\",\n    }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    category: Schema.optionalKey(\n      Schema.Union([SessionConfigOptionCategory, Schema.Null]).annotate({\n        description: \"Optional semantic category for this option (UX only).\",\n      }),\n    ),\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional description for the Client to display to the user.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    id: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option.\",\n    }),\n    name: Schema.String.annotate({ description: \"Human-readable label for the option.\" }),\n  }).annotate({ description: \"A session configuration option selector and its current state.\" }),\n]);\n\nexport type SessionModeState = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly availableModes: ReadonlyArray<SessionMode>;\n  readonly currentModeId: string;\n};\nexport const SessionModeState = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  availableModes: Schema.Array(SessionMode).annotate({\n    description: \"The set of modes that the Agent can operate in\",\n  }),\n  currentModeId: Schema.String.annotate({ description: \"Unique identifier for a Session Mode.\" }),\n}).annotate({ description: \"The set of modes and the one currently active.\" });\n\nexport type AgentAuthCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly logout?: LogoutCapabilities | null;\n};\nexport const AgentAuthCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  logout: Schema.optionalKey(\n    Schema.Union([LogoutCapabilities, Schema.Null]).annotate({\n      description:\n        \"Whether the agent supports the logout method.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication-related capabilities supported by the agent.\",\n});\n\nexport type AgentCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly auth?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly logout?: LogoutCapabilities | null;\n  };\n  readonly loadSession?: boolean;\n  readonly mcpCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly http?: boolean;\n    readonly sse?: boolean;\n  };\n  readonly promptCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly audio?: boolean;\n    readonly embeddedContext?: boolean;\n    readonly image?: boolean;\n  };\n  readonly sessionCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly close?: SessionCloseCapabilities | null;\n    readonly fork?: SessionForkCapabilities | null;\n    readonly list?: SessionListCapabilities | null;\n    readonly resume?: SessionResumeCapabilities | null;\n  };\n};\nexport const AgentCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  auth: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      logout: Schema.optionalKey(\n        Schema.Union([LogoutCapabilities, Schema.Null]).annotate({\n          description:\n            \"Whether the agent supports the logout method.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n        }),\n      ),\n    }).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication-related capabilities supported by the agent.\",\n      default: {},\n    }),\n  ),\n  loadSession: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether the agent supports `session/load`.\",\n      default: false,\n    }),\n  ),\n  mcpCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      http: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Agent supports [`McpServer::Http`].\",\n          default: false,\n        }),\n      ),\n      sse: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Agent supports [`McpServer::Sse`].\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description: \"MCP capabilities supported by the agent\",\n      default: { http: false, sse: false },\n    }),\n  ),\n  promptCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      audio: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Agent supports [`ContentBlock::Audio`].\",\n          default: false,\n        }),\n      ),\n      embeddedContext: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description:\n            \"Agent supports embedded context in `session/prompt` requests.\\n\\nWhen enabled, the Client is allowed to include [`ContentBlock::Resource`]\\nin prompt requests for pieces of context that are referenced in the message.\",\n          default: false,\n        }),\n      ),\n      image: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Agent supports [`ContentBlock::Image`].\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description:\n        \"Prompt capabilities supported by the agent in `session/prompt` requests.\\n\\nBaseline agent functionality requires support for [`ContentBlock::Text`]\\nand [`ContentBlock::ResourceLink`] in prompt requests.\\n\\nOther variants must be explicitly opted in to.\\nCapabilities for different types of content in prompt requests.\\n\\nIndicates which content types beyond the baseline (text and resource links)\\nthe agent can process.\\n\\nSee protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/initialization#prompt-capabilities)\",\n      default: { audio: false, embeddedContext: false, image: false },\n    }),\n  ),\n  sessionCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      close: Schema.optionalKey(\n        Schema.Union([SessionCloseCapabilities, Schema.Null]).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/close`.\",\n        }),\n      ),\n      fork: Schema.optionalKey(\n        Schema.Union([SessionForkCapabilities, Schema.Null]).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/fork`.\",\n        }),\n      ),\n      list: Schema.optionalKey(\n        Schema.Union([SessionListCapabilities, Schema.Null]).annotate({\n          description: \"Whether the agent supports `session/list`.\",\n        }),\n      ),\n      resume: Schema.optionalKey(\n        Schema.Union([SessionResumeCapabilities, Schema.Null]).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/resume`.\",\n        }),\n      ),\n    }).annotate({\n      default: {},\n      description:\n        \"Session capabilities supported by the agent.\\n\\nAs a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.\\n\\nOptionally, they **MAY** support other session methods and notifications by specifying additional capabilities.\\n\\nNote: `session/load` is still handled by the top-level `load_session` capability. This will be unified in future versions of the protocol.\\n\\nSee protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/initialization#session-capabilities)\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Capabilities supported by the agent.\\n\\nAdvertised during initialization to inform the client about\\navailable features and content types.\\n\\nSee protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/initialization#agent-capabilities)\",\n});\n\nexport type AgentNotification = {\n  readonly method: string;\n  readonly params?:\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly update:\n          | {\n              readonly sessionUpdate: \"user_message_chunk\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content:\n                | {\n                    readonly type: \"text\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly text: string;\n                  }\n                | {\n                    readonly type: \"image\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                    readonly uri?: string | null;\n                  }\n                | {\n                    readonly type: \"audio\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                  }\n                | {\n                    readonly type: \"resource_link\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly description?: string | null;\n                    readonly mimeType?: string | null;\n                    readonly name: string;\n                    readonly size?: number | null;\n                    readonly title?: string | null;\n                    readonly uri: string;\n                  }\n                | {\n                    readonly type: \"resource\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly resource: EmbeddedResourceResource;\n                  };\n              readonly messageId?: string | null;\n            }\n          | {\n              readonly sessionUpdate: \"agent_message_chunk\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content:\n                | {\n                    readonly type: \"text\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly text: string;\n                  }\n                | {\n                    readonly type: \"image\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                    readonly uri?: string | null;\n                  }\n                | {\n                    readonly type: \"audio\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                  }\n                | {\n                    readonly type: \"resource_link\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly description?: string | null;\n                    readonly mimeType?: string | null;\n                    readonly name: string;\n                    readonly size?: number | null;\n                    readonly title?: string | null;\n                    readonly uri: string;\n                  }\n                | {\n                    readonly type: \"resource\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly resource: EmbeddedResourceResource;\n                  };\n              readonly messageId?: string | null;\n            }\n          | {\n              readonly sessionUpdate: \"agent_thought_chunk\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content:\n                | {\n                    readonly type: \"text\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly text: string;\n                  }\n                | {\n                    readonly type: \"image\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                    readonly uri?: string | null;\n                  }\n                | {\n                    readonly type: \"audio\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly data: string;\n                    readonly mimeType: string;\n                  }\n                | {\n                    readonly type: \"resource_link\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly description?: string | null;\n                    readonly mimeType?: string | null;\n                    readonly name: string;\n                    readonly size?: number | null;\n                    readonly title?: string | null;\n                    readonly uri: string;\n                  }\n                | {\n                    readonly type: \"resource\";\n                    readonly _meta?: { readonly [x: string]: unknown } | null;\n                    readonly annotations?: Annotations | null;\n                    readonly resource: EmbeddedResourceResource;\n                  };\n              readonly messageId?: string | null;\n            }\n          | {\n              readonly sessionUpdate: \"tool_call\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content?: ReadonlyArray<ToolCallContent>;\n              readonly kind?:\n                | \"read\"\n                | \"edit\"\n                | \"delete\"\n                | \"move\"\n                | \"search\"\n                | \"execute\"\n                | \"think\"\n                | \"fetch\"\n                | \"switch_mode\"\n                | \"other\";\n              readonly locations?: ReadonlyArray<ToolCallLocation>;\n              readonly rawInput?: unknown;\n              readonly rawOutput?: unknown;\n              readonly status?: \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n              readonly title: string;\n              readonly toolCallId: string;\n            }\n          | {\n              readonly sessionUpdate: \"tool_call_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly content?: ReadonlyArray<ToolCallContent> | null;\n              readonly kind?: ToolKind | null;\n              readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n              readonly rawInput?: unknown;\n              readonly rawOutput?: unknown;\n              readonly status?: ToolCallStatus | null;\n              readonly title?: string | null;\n              readonly toolCallId: string;\n            }\n          | {\n              readonly sessionUpdate: \"plan\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly entries: ReadonlyArray<PlanEntry>;\n            }\n          | {\n              readonly sessionUpdate: \"available_commands_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly availableCommands: ReadonlyArray<AvailableCommand>;\n            }\n          | {\n              readonly sessionUpdate: \"current_mode_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly currentModeId: string;\n            }\n          | {\n              readonly sessionUpdate: \"config_option_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly configOptions: ReadonlyArray<SessionConfigOption>;\n            }\n          | {\n              readonly sessionUpdate: \"session_info_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly title?: string | null;\n              readonly updatedAt?: string | null;\n            }\n          | {\n              readonly sessionUpdate: \"usage_update\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly cost?: Cost | null;\n              readonly size: number;\n              readonly used: number;\n            };\n      }\n    | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly elicitationId: string }\n    | unknown\n    | null;\n};\nexport const AgentNotification = Schema.Struct({\n  method: Schema.String,\n  params: Schema.optionalKey(\n    Schema.Union([\n      Schema.Union([\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          update: Schema.Union(\n            [\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"user_message_chunk\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.Union(\n                  [\n                    Schema.Struct({\n                      type: Schema.Literal(\"text\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      text: Schema.String,\n                    }).annotate({ description: \"Text provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"image\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                      uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                    }).annotate({ description: \"An image provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"audio\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                    }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource_link\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      name: Schema.String,\n                      size: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                          Schema.Null,\n                        ]),\n                      ),\n                      title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      uri: Schema.String,\n                    }).annotate({\n                      description:\n                        \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n                    }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      resource: EmbeddedResourceResource,\n                    }).annotate({\n                      description:\n                        \"The contents of a resource, embedded into a prompt or tool call result.\",\n                    }),\n                  ],\n                  { mode: \"oneOf\" },\n                ).annotate({\n                  description:\n                    \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n                }),\n                messageId: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description:\n                        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n              }).annotate({ description: \"A streamed item of content\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"agent_message_chunk\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.Union(\n                  [\n                    Schema.Struct({\n                      type: Schema.Literal(\"text\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      text: Schema.String,\n                    }).annotate({ description: \"Text provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"image\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                      uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                    }).annotate({ description: \"An image provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"audio\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                    }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource_link\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      name: Schema.String,\n                      size: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                          Schema.Null,\n                        ]),\n                      ),\n                      title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      uri: Schema.String,\n                    }).annotate({\n                      description:\n                        \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n                    }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      resource: EmbeddedResourceResource,\n                    }).annotate({\n                      description:\n                        \"The contents of a resource, embedded into a prompt or tool call result.\",\n                    }),\n                  ],\n                  { mode: \"oneOf\" },\n                ).annotate({\n                  description:\n                    \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n                }),\n                messageId: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description:\n                        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n              }).annotate({ description: \"A streamed item of content\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"agent_thought_chunk\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.Union(\n                  [\n                    Schema.Struct({\n                      type: Schema.Literal(\"text\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      text: Schema.String,\n                    }).annotate({ description: \"Text provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"image\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                      uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                    }).annotate({ description: \"An image provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"audio\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      data: Schema.String,\n                      mimeType: Schema.String,\n                    }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource_link\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      name: Schema.String,\n                      size: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                          Schema.Null,\n                        ]),\n                      ),\n                      title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n                      uri: Schema.String,\n                    }).annotate({\n                      description:\n                        \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n                    }),\n                    Schema.Struct({\n                      type: Schema.Literal(\"resource\"),\n                      _meta: Schema.optionalKey(\n                        Schema.Union([\n                          Schema.Record(Schema.String, Schema.Unknown).annotate({\n                            description:\n                              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                          }),\n                          Schema.Null,\n                        ]),\n                      ),\n                      annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n                      resource: EmbeddedResourceResource,\n                    }).annotate({\n                      description:\n                        \"The contents of a resource, embedded into a prompt or tool call result.\",\n                    }),\n                  ],\n                  { mode: \"oneOf\" },\n                ).annotate({\n                  description:\n                    \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n                }),\n                messageId: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description:\n                        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n              }).annotate({ description: \"A streamed item of content\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"tool_call\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.optionalKey(\n                  Schema.Array(ToolCallContent).annotate({\n                    description: \"Content produced by the tool call.\",\n                  }),\n                ),\n                kind: Schema.optionalKey(\n                  Schema.Literals([\n                    \"read\",\n                    \"edit\",\n                    \"delete\",\n                    \"move\",\n                    \"search\",\n                    \"execute\",\n                    \"think\",\n                    \"fetch\",\n                    \"switch_mode\",\n                    \"other\",\n                  ]).annotate({\n                    description:\n                      \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n                  }),\n                ),\n                locations: Schema.optionalKey(\n                  Schema.Array(ToolCallLocation).annotate({\n                    description:\n                      'File locations affected by this tool call.\\nEnables \"follow-along\" features in clients.',\n                  }),\n                ),\n                rawInput: Schema.optionalKey(\n                  Schema.Unknown.annotate({\n                    description: \"Raw input parameters sent to the tool.\",\n                  }),\n                ),\n                rawOutput: Schema.optionalKey(\n                  Schema.Unknown.annotate({ description: \"Raw output returned by the tool.\" }),\n                ),\n                status: Schema.optionalKey(\n                  Schema.Literals([\"pending\", \"in_progress\", \"completed\", \"failed\"]).annotate({\n                    description:\n                      \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n                  }),\n                ),\n                title: Schema.String.annotate({\n                  description: \"Human-readable title describing what the tool is doing.\",\n                }),\n                toolCallId: Schema.String.annotate({\n                  description: \"Unique identifier for a tool call within a session.\",\n                }),\n              }).annotate({\n                description:\n                  \"Represents a tool call that the language model has requested.\\n\\nTool calls are actions that the agent executes on behalf of the language model,\\nsuch as reading files, executing code, or fetching data from external sources.\\n\\nSee protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/tool-calls)\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"tool_call_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                content: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Array(ToolCallContent).annotate({\n                      description: \"Replace the content collection.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                kind: Schema.optionalKey(\n                  Schema.Union([ToolKind, Schema.Null]).annotate({\n                    description: \"Update the tool kind.\",\n                  }),\n                ),\n                locations: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Array(ToolCallLocation).annotate({\n                      description: \"Replace the locations collection.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                rawInput: Schema.optionalKey(\n                  Schema.Unknown.annotate({ description: \"Update the raw input.\" }),\n                ),\n                rawOutput: Schema.optionalKey(\n                  Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n                ),\n                status: Schema.optionalKey(\n                  Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n                    description: \"Update the execution status.\",\n                  }),\n                ),\n                title: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n                    Schema.Null,\n                  ]),\n                ),\n                toolCallId: Schema.String.annotate({\n                  description: \"Unique identifier for a tool call within a session.\",\n                }),\n              }).annotate({\n                description:\n                  \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"plan\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                entries: Schema.Array(PlanEntry).annotate({\n                  description:\n                    \"The list of tasks to be accomplished.\\n\\nWhen updating a plan, the agent must send a complete list of all entries\\nwith their current status. The client replaces the entire plan with each update.\",\n                }),\n              }).annotate({\n                description:\n                  \"An execution plan for accomplishing complex tasks.\\n\\nPlans consist of multiple entries representing individual tasks or goals.\\nAgents report plans to clients to provide visibility into their execution strategy.\\nPlans can evolve during execution as the agent discovers new requirements or completes tasks.\\n\\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/agent-plan)\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"available_commands_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                availableCommands: Schema.Array(AvailableCommand).annotate({\n                  description: \"Commands the agent can execute\",\n                }),\n              }).annotate({ description: \"Available commands are ready or have changed\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"current_mode_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                currentModeId: Schema.String.annotate({\n                  description: \"Unique identifier for a Session Mode.\",\n                }),\n              }).annotate({\n                description:\n                  \"The current mode of the session has changed\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"config_option_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                configOptions: Schema.Array(SessionConfigOption).annotate({\n                  description: \"The full set of configuration options and their current values.\",\n                }),\n              }).annotate({ description: \"Session configuration options have been updated.\" }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"session_info_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                title: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description: \"Human-readable title for the session. Set to null to clear.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                updatedAt: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.String.annotate({\n                      description: \"ISO 8601 timestamp of last activity. Set to null to clear.\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n              }).annotate({\n                description:\n                  \"Update to session metadata. All fields are optional to support partial updates.\\n\\nAgents send this notification to update session information like title or custom metadata.\\nThis allows clients to display dynamic session names and track session state changes.\",\n              }),\n              Schema.Struct({\n                sessionUpdate: Schema.Literal(\"usage_update\"),\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                cost: Schema.optionalKey(\n                  Schema.Union([Cost, Schema.Null]).annotate({\n                    description: \"Cumulative session cost (optional).\",\n                  }),\n                ),\n                size: Schema.Number.annotate({\n                  description: \"Total context window size in tokens.\",\n                  format: \"uint64\",\n                })\n                  .check(Schema.isInt())\n                  .check(Schema.isGreaterThanOrEqualTo(0)),\n                used: Schema.Number.annotate({\n                  description: \"Tokens currently in context.\",\n                  format: \"uint64\",\n                })\n                  .check(Schema.isInt())\n                  .check(Schema.isGreaterThanOrEqualTo(0)),\n              }).annotate({\n                description:\n                  \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nContext window and cost update for a session.\",\n              }),\n            ],\n            { mode: \"oneOf\" },\n          ).annotate({\n            description:\n              \"Different types of updates that can be sent during session processing.\\n\\nThese updates provide real-time feedback about the agent's progress.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n          }),\n        }).annotate({\n          title: \"SessionNotification\",\n          description:\n            \"Notification containing a session update from the agent.\\n\\nUsed to stream real-time progress and results during prompt processing.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          elicitationId: Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n          }),\n        }).annotate({\n          title: \"ElicitationCompleteNotification\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nNotification sent by the agent when a URL-based elicitation is complete.\",\n        }),\n        Schema.Unknown.annotate({\n          title: \"ExtNotification\",\n          description:\n            \"Allows the Agent to send an arbitrary notification that is not part of the ACP spec.\\nExtension notifications provide a way to send one-way messages for custom functionality\\nwhile maintaining protocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n      ]).annotate({\n        description:\n          \"All possible notifications that an agent can send to a client.\\n\\nThis enum is used internally for routing RPC notifications. You typically won't need\\nto use this directly - use the notification methods on the [`Client`] trait instead.\\n\\nNotifications do not expect a response.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type AgentRequest = {\n  readonly id: RequestId;\n  readonly method: string;\n  readonly params?:\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content: string;\n        readonly path: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly limit?: number | null;\n        readonly line?: number | null;\n        readonly path: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly options: ReadonlyArray<PermissionOption>;\n        readonly sessionId: string;\n        readonly toolCall: {\n          readonly _meta?: { readonly [x: string]: unknown } | null;\n          readonly content?: ReadonlyArray<ToolCallContent> | null;\n          readonly kind?: ToolKind | null;\n          readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n          readonly rawInput?: unknown;\n          readonly rawOutput?: unknown;\n          readonly status?: ToolCallStatus | null;\n          readonly title?: string | null;\n          readonly toolCallId: string;\n        };\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly args?: ReadonlyArray<string>;\n        readonly command: string;\n        readonly cwd?: string | null;\n        readonly env?: ReadonlyArray<EnvVariable>;\n        readonly outputByteLimit?: number | null;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly terminalId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly terminalId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly terminalId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly sessionId: string;\n        readonly terminalId: string;\n      }\n    | {\n        readonly mode: \"form\";\n        readonly requestedSchema: {\n          readonly description?: string | null;\n          readonly properties?: { readonly [x: string]: ElicitationPropertySchema };\n          readonly required?: ReadonlyArray<string> | null;\n          readonly title?: string | null;\n          readonly type?: \"object\";\n        };\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly message: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly mode: \"url\";\n        readonly elicitationId: string;\n        readonly url: string;\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly message: string;\n        readonly sessionId: string;\n      }\n    | unknown\n    | null;\n};\nexport const AgentRequest = Schema.Struct({\n  id: RequestId,\n  method: Schema.String,\n  params: Schema.optionalKey(\n    Schema.Union([\n      Schema.Union([\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          content: Schema.String.annotate({\n            description: \"The text content to write to the file.\",\n          }),\n          path: Schema.String.annotate({ description: \"Absolute path to the file to write.\" }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"WriteTextFileRequest\",\n          description:\n            \"Request to write content to a text file.\\n\\nOnly available if the client supports the `fs.writeTextFile` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          limit: Schema.optionalKey(\n            Schema.Union([\n              Schema.Number.annotate({\n                description: \"Maximum number of lines to read.\",\n                format: \"uint32\",\n              })\n                .check(Schema.isInt())\n                .check(Schema.isGreaterThanOrEqualTo(0)),\n              Schema.Null,\n            ]),\n          ),\n          line: Schema.optionalKey(\n            Schema.Union([\n              Schema.Number.annotate({\n                description: \"Line number to start reading from (1-based).\",\n                format: \"uint32\",\n              })\n                .check(Schema.isInt())\n                .check(Schema.isGreaterThanOrEqualTo(0)),\n              Schema.Null,\n            ]),\n          ),\n          path: Schema.String.annotate({ description: \"Absolute path to the file to read.\" }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"ReadTextFileRequest\",\n          description:\n            \"Request to read content from a text file.\\n\\nOnly available if the client supports the `fs.readTextFile` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          options: Schema.Array(PermissionOption).annotate({\n            description: \"Available permission options for the user to choose from.\",\n          }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          toolCall: Schema.Struct({\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            content: Schema.optionalKey(\n              Schema.Union([\n                Schema.Array(ToolCallContent).annotate({\n                  description: \"Replace the content collection.\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            kind: Schema.optionalKey(\n              Schema.Union([ToolKind, Schema.Null]).annotate({\n                description: \"Update the tool kind.\",\n              }),\n            ),\n            locations: Schema.optionalKey(\n              Schema.Union([\n                Schema.Array(ToolCallLocation).annotate({\n                  description: \"Replace the locations collection.\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            rawInput: Schema.optionalKey(\n              Schema.Unknown.annotate({ description: \"Update the raw input.\" }),\n            ),\n            rawOutput: Schema.optionalKey(\n              Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n            ),\n            status: Schema.optionalKey(\n              Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n                description: \"Update the execution status.\",\n              }),\n            ),\n            title: Schema.optionalKey(\n              Schema.Union([\n                Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n                Schema.Null,\n              ]),\n            ),\n            toolCallId: Schema.String.annotate({\n              description: \"Unique identifier for a tool call within a session.\",\n            }),\n          }).annotate({\n            description:\n              \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n          }),\n        }).annotate({\n          title: \"RequestPermissionRequest\",\n          description:\n            \"Request for user permission to execute a tool call.\\n\\nSent when the agent needs authorization before performing a sensitive operation.\\n\\nSee protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/tool-calls#requesting-permission)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          args: Schema.optionalKey(\n            Schema.Array(Schema.String).annotate({ description: \"Array of command arguments.\" }),\n          ),\n          command: Schema.String.annotate({ description: \"The command to execute.\" }),\n          cwd: Schema.optionalKey(\n            Schema.Union([\n              Schema.String.annotate({\n                description: \"Working directory for the command (absolute path).\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          env: Schema.optionalKey(\n            Schema.Array(EnvVariable).annotate({\n              description: \"Environment variables for the command.\",\n            }),\n          ),\n          outputByteLimit: Schema.optionalKey(\n            Schema.Union([\n              Schema.Number.annotate({\n                description:\n                  \"Maximum number of output bytes to retain.\\n\\nWhen the limit is exceeded, the Client truncates from the beginning of the output\\nto stay within the limit.\\n\\nThe Client MUST ensure truncation happens at a character boundary to maintain valid\\nstring output, even if this means the retained output is slightly less than the\\nspecified limit.\",\n                format: \"uint64\",\n              })\n                .check(Schema.isInt())\n                .check(Schema.isGreaterThanOrEqualTo(0)),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"CreateTerminalRequest\",\n          description: \"Request to create a new terminal and execute a command.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          terminalId: Schema.String.annotate({\n            description: \"The ID of the terminal to get output from.\",\n          }),\n        }).annotate({\n          title: \"TerminalOutputRequest\",\n          description: \"Request to get the current output and status of a terminal.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          terminalId: Schema.String.annotate({ description: \"The ID of the terminal to release.\" }),\n        }).annotate({\n          title: \"ReleaseTerminalRequest\",\n          description: \"Request to release a terminal and free its resources.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          terminalId: Schema.String.annotate({\n            description: \"The ID of the terminal to wait for.\",\n          }),\n        }).annotate({\n          title: \"WaitForTerminalExitRequest\",\n          description: \"Request to wait for a terminal command to exit.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n          terminalId: Schema.String.annotate({ description: \"The ID of the terminal to kill.\" }),\n        }).annotate({\n          title: \"KillTerminalRequest\",\n          description: \"Request to kill a terminal without releasing it.\",\n        }),\n        Schema.Union([\n          Schema.Struct({\n            mode: Schema.Literal(\"form\"),\n            requestedSchema: Schema.Struct({\n              description: Schema.optionalKey(\n                Schema.Union([\n                  Schema.String.annotate({\n                    description: \"Optional description of what this schema represents.\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              properties: Schema.optionalKey(\n                Schema.Record(Schema.String, ElicitationPropertySchema).annotate({\n                  description: \"Property definitions (must be primitive types).\",\n                  default: {},\n                }),\n              ),\n              required: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Array(Schema.String).annotate({\n                    description: \"List of required property names.\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              title: Schema.optionalKey(\n                Schema.Union([\n                  Schema.String.annotate({ description: \"Optional title for the schema.\" }),\n                  Schema.Null,\n                ]),\n              ),\n              type: Schema.optionalKey(\n                Schema.Literal(\"object\").annotate({\n                  description: \"Type discriminator for elicitation schemas.\",\n                  default: \"object\",\n                }),\n              ),\n            }).annotate({\n              description:\n                \"Type-safe elicitation schema for requesting structured user input.\\n\\nThis represents a JSON Schema object with primitive-typed properties,\\nas required by the elicitation specification.\",\n            }),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            message: Schema.String.annotate({\n              description: \"A human-readable message describing what input is needed.\",\n            }),\n            sessionId: Schema.String.annotate({\n              description:\n                \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n            }),\n          }).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest from the agent to elicit structured user input.\\n\\nThe agent sends this to the client to request information from the user,\\neither via a form or by directing them to a URL.\",\n          }),\n          Schema.Struct({\n            mode: Schema.Literal(\"url\"),\n            elicitationId: Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n            }),\n            url: Schema.String.annotate({\n              description: \"The URL to direct the user to.\",\n              format: \"uri\",\n            }),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            message: Schema.String.annotate({\n              description: \"A human-readable message describing what input is needed.\",\n            }),\n            sessionId: Schema.String.annotate({\n              description:\n                \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n            }),\n          }).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest from the agent to elicit structured user input.\\n\\nThe agent sends this to the client to request information from the user,\\neither via a form or by directing them to a URL.\",\n          }),\n        ]).annotate({\n          title: \"ElicitationRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequests structured user input via a form or URL.\",\n        }),\n        Schema.Unknown.annotate({\n          title: \"ExtMethodRequest\",\n          description:\n            \"Allows for sending an arbitrary request that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n      ]).annotate({\n        description:\n          \"All possible requests that an agent can send to a client.\\n\\nThis enum is used internally for routing RPC requests. You typically won't need\\nto use this directly - instead, use the methods on the [`Client`] trait.\\n\\nThis enum encompasses all method calls from agent to client.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type AgentResponse =\n  | {\n      readonly id: RequestId;\n      readonly result:\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly agentCapabilities?: {\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly auth?: {\n                readonly _meta?: { readonly [x: string]: unknown } | null;\n                readonly logout?: LogoutCapabilities | null;\n              };\n              readonly loadSession?: boolean;\n              readonly mcpCapabilities?: {\n                readonly _meta?: { readonly [x: string]: unknown } | null;\n                readonly http?: boolean;\n                readonly sse?: boolean;\n              };\n              readonly promptCapabilities?: {\n                readonly _meta?: { readonly [x: string]: unknown } | null;\n                readonly audio?: boolean;\n                readonly embeddedContext?: boolean;\n                readonly image?: boolean;\n              };\n              readonly sessionCapabilities?: {\n                readonly _meta?: { readonly [x: string]: unknown } | null;\n                readonly close?: SessionCloseCapabilities | null;\n                readonly fork?: SessionForkCapabilities | null;\n                readonly list?: SessionListCapabilities | null;\n                readonly resume?: SessionResumeCapabilities | null;\n              };\n            };\n            readonly agentInfo?: Implementation | null;\n            readonly authMethods?: ReadonlyArray<AuthMethod>;\n            readonly protocolVersion: number;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n            readonly models?: SessionModelState | null;\n            readonly modes?: SessionModeState | null;\n            readonly sessionId: string;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n            readonly models?: SessionModelState | null;\n            readonly modes?: SessionModeState | null;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly nextCursor?: string | null;\n            readonly sessions: ReadonlyArray<SessionInfo>;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n            readonly models?: SessionModelState | null;\n            readonly modes?: SessionModeState | null;\n            readonly sessionId: string;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n            readonly models?: SessionModelState | null;\n            readonly modes?: SessionModeState | null;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly configOptions: ReadonlyArray<SessionConfigOption>;\n          }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly stopReason:\n              | \"end_turn\"\n              | \"max_tokens\"\n              | \"max_turn_requests\"\n              | \"refusal\"\n              | \"cancelled\";\n            readonly usage?: Usage | null;\n            readonly userMessageId?: string | null;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | unknown;\n    }\n  | { readonly error: Error; readonly id: RequestId };\nexport const AgentResponse = Schema.Union([\n  Schema.Struct({\n    id: RequestId,\n    result: Schema.Union([\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        agentCapabilities: Schema.optionalKey(\n          Schema.Struct({\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            auth: Schema.optionalKey(\n              Schema.Struct({\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                logout: Schema.optionalKey(\n                  Schema.Union([LogoutCapabilities, Schema.Null]).annotate({\n                    description:\n                      \"Whether the agent supports the logout method.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n                  }),\n                ),\n              }).annotate({\n                description:\n                  \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication-related capabilities supported by the agent.\",\n                default: {},\n              }),\n            ),\n            loadSession: Schema.optionalKey(\n              Schema.Boolean.annotate({\n                description: \"Whether the agent supports `session/load`.\",\n                default: false,\n              }),\n            ),\n            mcpCapabilities: Schema.optionalKey(\n              Schema.Struct({\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                http: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description: \"Agent supports [`McpServer::Http`].\",\n                    default: false,\n                  }),\n                ),\n                sse: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description: \"Agent supports [`McpServer::Sse`].\",\n                    default: false,\n                  }),\n                ),\n              }).annotate({\n                description: \"MCP capabilities supported by the agent\",\n                default: { http: false, sse: false },\n              }),\n            ),\n            promptCapabilities: Schema.optionalKey(\n              Schema.Struct({\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                audio: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description: \"Agent supports [`ContentBlock::Audio`].\",\n                    default: false,\n                  }),\n                ),\n                embeddedContext: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description:\n                      \"Agent supports embedded context in `session/prompt` requests.\\n\\nWhen enabled, the Client is allowed to include [`ContentBlock::Resource`]\\nin prompt requests for pieces of context that are referenced in the message.\",\n                    default: false,\n                  }),\n                ),\n                image: Schema.optionalKey(\n                  Schema.Boolean.annotate({\n                    description: \"Agent supports [`ContentBlock::Image`].\",\n                    default: false,\n                  }),\n                ),\n              }).annotate({\n                description:\n                  \"Prompt capabilities supported by the agent in `session/prompt` requests.\\n\\nBaseline agent functionality requires support for [`ContentBlock::Text`]\\nand [`ContentBlock::ResourceLink`] in prompt requests.\\n\\nOther variants must be explicitly opted in to.\\nCapabilities for different types of content in prompt requests.\\n\\nIndicates which content types beyond the baseline (text and resource links)\\nthe agent can process.\\n\\nSee protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/initialization#prompt-capabilities)\",\n                default: { audio: false, embeddedContext: false, image: false },\n              }),\n            ),\n            sessionCapabilities: Schema.optionalKey(\n              Schema.Struct({\n                _meta: Schema.optionalKey(\n                  Schema.Union([\n                    Schema.Record(Schema.String, Schema.Unknown).annotate({\n                      description:\n                        \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                    }),\n                    Schema.Null,\n                  ]),\n                ),\n                close: Schema.optionalKey(\n                  Schema.Union([SessionCloseCapabilities, Schema.Null]).annotate({\n                    description:\n                      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/close`.\",\n                  }),\n                ),\n                fork: Schema.optionalKey(\n                  Schema.Union([SessionForkCapabilities, Schema.Null]).annotate({\n                    description:\n                      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/fork`.\",\n                  }),\n                ),\n                list: Schema.optionalKey(\n                  Schema.Union([SessionListCapabilities, Schema.Null]).annotate({\n                    description: \"Whether the agent supports `session/list`.\",\n                  }),\n                ),\n                resume: Schema.optionalKey(\n                  Schema.Union([SessionResumeCapabilities, Schema.Null]).annotate({\n                    description:\n                      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/resume`.\",\n                  }),\n                ),\n              }).annotate({\n                default: {},\n                description:\n                  \"Session capabilities supported by the agent.\\n\\nAs a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.\\n\\nOptionally, they **MAY** support other session methods and notifications by specifying additional capabilities.\\n\\nNote: `session/load` is still handled by the top-level `load_session` capability. This will be unified in future versions of the protocol.\\n\\nSee protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/initialization#session-capabilities)\",\n              }),\n            ),\n          }).annotate({\n            description:\n              \"Capabilities supported by the agent.\\n\\nAdvertised during initialization to inform the client about\\navailable features and content types.\\n\\nSee protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/initialization#agent-capabilities)\",\n            default: {\n              auth: {},\n              loadSession: false,\n              mcpCapabilities: { http: false, sse: false },\n              promptCapabilities: { audio: false, embeddedContext: false, image: false },\n              sessionCapabilities: {},\n            },\n          }),\n        ),\n        agentInfo: Schema.optionalKey(\n          Schema.Union([Implementation, Schema.Null]).annotate({\n            description:\n              \"Information about the Agent name and version sent to the Client.\\n\\nNote: in future versions of the protocol, this will be required.\",\n          }),\n        ),\n        authMethods: Schema.optionalKey(\n          Schema.Array(AuthMethod).annotate({\n            description: \"Authentication methods supported by the agent.\",\n            default: [],\n          }),\n        ),\n        protocolVersion: Schema.Number.annotate({\n          description:\n            \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n          format: \"uint16\",\n        })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0))\n          .check(Schema.isLessThanOrEqualTo(65535)),\n      }).annotate({\n        title: \"InitializeResponse\",\n        description:\n          \"Response to the `initialize` method.\\n\\nContains the negotiated protocol version and agent capabilities.\\n\\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"AuthenticateResponse\",\n        description: \"Response to the `authenticate` method.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"LogoutResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse to the `logout` method.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(SessionConfigOption).annotate({\n              description: \"Initial session configuration options if supported by the Agent.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        models: Schema.optionalKey(\n          Schema.Union([SessionModelState, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n          }),\n        ),\n        modes: Schema.optionalKey(\n          Schema.Union([SessionModeState, Schema.Null]).annotate({\n            description:\n              \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n          }),\n        ),\n        sessionId: Schema.String.annotate({\n          description:\n            \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n        }),\n      }).annotate({\n        title: \"NewSessionResponse\",\n        description:\n          \"Response from creating a new session.\\n\\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(SessionConfigOption).annotate({\n              description: \"Initial session configuration options if supported by the Agent.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        models: Schema.optionalKey(\n          Schema.Union([SessionModelState, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n          }),\n        ),\n        modes: Schema.optionalKey(\n          Schema.Union([SessionModeState, Schema.Null]).annotate({\n            description:\n              \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n          }),\n        ),\n      }).annotate({\n        title: \"LoadSessionResponse\",\n        description: \"Response from loading an existing session.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        nextCursor: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"Opaque cursor token. If present, pass this in the next request's cursor parameter\\nto fetch the next page. If absent, there are no more results.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        sessions: Schema.Array(SessionInfo).annotate({\n          description: \"Array of session information objects\",\n        }),\n      }).annotate({\n        title: \"ListSessionsResponse\",\n        description: \"Response from listing sessions.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(SessionConfigOption).annotate({\n              description: \"Initial session configuration options if supported by the Agent.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        models: Schema.optionalKey(\n          Schema.Union([SessionModelState, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n          }),\n        ),\n        modes: Schema.optionalKey(\n          Schema.Union([SessionModeState, Schema.Null]).annotate({\n            description:\n              \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n          }),\n        ),\n        sessionId: Schema.String.annotate({\n          description:\n            \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n        }),\n      }).annotate({\n        title: \"ForkSessionResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from forking an existing session.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(SessionConfigOption).annotate({\n              description: \"Initial session configuration options if supported by the Agent.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        models: Schema.optionalKey(\n          Schema.Union([SessionModelState, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n          }),\n        ),\n        modes: Schema.optionalKey(\n          Schema.Union([SessionModeState, Schema.Null]).annotate({\n            description:\n              \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n          }),\n        ),\n      }).annotate({\n        title: \"ResumeSessionResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from resuming an existing session.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"CloseSessionResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from closing a session.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"SetSessionModeResponse\",\n        description: \"Response to `session/set_mode` method.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.Array(SessionConfigOption).annotate({\n          description: \"The full set of configuration options and their current values.\",\n        }),\n      }).annotate({\n        title: \"SetSessionConfigOptionResponse\",\n        description: \"Response to `session/set_config_option` method.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        stopReason: Schema.Literals([\n          \"end_turn\",\n          \"max_tokens\",\n          \"max_turn_requests\",\n          \"refusal\",\n          \"cancelled\",\n        ]).annotate({\n          description:\n            \"Reasons why an agent stops processing a prompt turn.\\n\\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/prompt-turn#stop-reasons)\",\n        }),\n        usage: Schema.optionalKey(\n          Schema.Union([Usage, Schema.Null]).annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nToken usage for this turn (optional).\",\n          }),\n        ),\n        userMessageId: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe acknowledged user message ID.\\n\\nIf the client provided a `messageId` in the [`PromptRequest`], the agent echoes it here\\nto confirm it was recorded. If the client did not provide one, the agent MAY assign one\\nand return it here. Absence of this field indicates the agent did not record a message ID.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"PromptResponse\",\n        description:\n          \"Response from processing a user prompt.\\n\\nSee protocol docs: [Check for Completion](https://agentclientprotocol.com/protocol/prompt-turn#4-check-for-completion)\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"SetSessionModelResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse to `session/set_model` method.\",\n      }),\n      Schema.Unknown.annotate({\n        title: \"ExtMethodResponse\",\n        description:\n          \"Allows for sending an arbitrary response to an [`ExtRequest`] that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n    ]).annotate({\n      description:\n        \"All possible responses that an agent can send to a client.\\n\\nThis enum is used internally for routing RPC responses. You typically won't need\\nto use this directly - the responses are handled automatically by the connection.\\n\\nThese are responses to the corresponding `ClientRequest` variants.\",\n    }),\n  }).annotate({ title: \"Result\" }),\n  Schema.Struct({ error: Error, id: RequestId }).annotate({ title: \"Error\" }),\n]);\n\nexport type AudioContent = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly data: string;\n  readonly mimeType: string;\n};\nexport const AudioContent = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  data: Schema.String,\n  mimeType: Schema.String,\n}).annotate({ description: \"Audio provided to or from an LLM.\" });\n\nexport type AuthCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly terminal?: boolean;\n};\nexport const AuthCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  terminal: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Whether the client supports `terminal` authentication methods.\\n\\nWhen `true`, the agent may include `terminal` entries in its authentication methods.\",\n      default: false,\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent which authentication\\nmethod types the client can handle. This governs opt-in types that require\\nadditional client-side support.\",\n});\n\nexport type AuthenticateRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly methodId: string;\n};\nexport const AuthenticateRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  methodId: Schema.String.annotate({\n    description:\n      \"The ID of the authentication method to use.\\nMust be one of the methods advertised in the initialize response.\",\n  }),\n}).annotate({\n  description:\n    \"Request parameters for the authenticate method.\\n\\nSpecifies which authentication method to use.\",\n});\n\nexport type AuthenticateResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const AuthenticateResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to the `authenticate` method.\" });\n\nexport type AuthMethodAgent = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly id: string;\n  readonly name: string;\n};\nexport const AuthMethodAgent = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional description providing more details about this authentication method.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({ description: \"Unique identifier for this authentication method.\" }),\n  name: Schema.String.annotate({\n    description: \"Human-readable name of the authentication method.\",\n  }),\n}).annotate({\n  description:\n    \"Agent handles authentication itself.\\n\\nThis is the default authentication method type.\",\n});\n\nexport type AuthMethodEnvVar = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly description?: string | null;\n  readonly id: string;\n  readonly link?: string | null;\n  readonly name: string;\n  readonly vars: ReadonlyArray<AuthEnvVar>;\n};\nexport const AuthMethodEnvVar = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional description providing more details about this authentication method.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  id: Schema.String.annotate({ description: \"Unique identifier for this authentication method.\" }),\n  link: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional link to a page where the user can obtain their credentials.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  name: Schema.String.annotate({\n    description: \"Human-readable name of the authentication method.\",\n  }),\n  vars: Schema.Array(AuthEnvVar).annotate({\n    description: \"The environment variables the client should set.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nEnvironment variable authentication method.\\n\\nThe user provides credentials that the client passes to the agent as environment variables.\",\n});\n\nexport type AuthMethodTerminal = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly args?: ReadonlyArray<string>;\n  readonly description?: string | null;\n  readonly env?: { readonly [x: string]: string };\n  readonly id: string;\n  readonly name: string;\n};\nexport const AuthMethodTerminal = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  args: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({\n      description: \"Additional arguments to pass when running the agent binary for terminal auth.\",\n    }),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Optional description providing more details about this authentication method.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  env: Schema.optionalKey(\n    Schema.Record(Schema.String, Schema.String).annotate({\n      description:\n        \"Additional environment variables to set when running the agent binary for terminal auth.\",\n    }),\n  ),\n  id: Schema.String.annotate({ description: \"Unique identifier for this authentication method.\" }),\n  name: Schema.String.annotate({\n    description: \"Human-readable name of the authentication method.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nTerminal-based authentication method.\\n\\nThe client runs an interactive terminal for the user to authenticate via a TUI.\",\n});\n\nexport type AvailableCommandsUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly availableCommands: ReadonlyArray<AvailableCommand>;\n};\nexport const AvailableCommandsUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  availableCommands: Schema.Array(AvailableCommand).annotate({\n    description: \"Commands the agent can execute\",\n  }),\n}).annotate({ description: \"Available commands are ready or have changed\" });\n\nexport type BlobResourceContents = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly blob: string;\n  readonly mimeType?: string | null;\n  readonly uri: string;\n};\nexport const BlobResourceContents = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  blob: Schema.String,\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n}).annotate({ description: \"Binary resource contents.\" });\n\nexport type BooleanPropertySchema = {\n  readonly default?: boolean | null;\n  readonly description?: string | null;\n  readonly title?: string | null;\n};\nexport const BooleanPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([Schema.Boolean.annotate({ description: \"Default value.\" }), Schema.Null]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Schema for boolean properties in an elicitation form.\" });\n\nexport type CancelNotification = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n};\nexport const CancelNotification = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Notification to cancel ongoing operations for a session.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n});\n\nexport type CancelRequestNotification = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly requestId: null | number | string;\n};\nexport const CancelRequestNotification = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  requestId: Schema.Union([\n    Schema.Null.annotate({ title: \"Null\" }),\n    Schema.Number.annotate({ title: \"Number\", format: \"int64\" }).check(Schema.isInt()),\n    Schema.String.annotate({ title: \"Str\" }),\n  ]).annotate({\n    description:\n      \"JSON RPC Request Id\\n\\nAn identifier established by the Client that MUST contain a String, Number, or NULL value if included. If it is not included it is assumed to be a notification. The value SHOULD normally not be Null [1] and Numbers SHOULD NOT contain fractional parts [2]\\n\\nThe Server MUST reply with the same value in the Response object if included. This member is used to correlate the context between the two objects.\\n\\n[1] The use of Null as a value for the id member in a Request object is discouraged, because this specification uses a value of Null for Responses with an unknown id. Also, because JSON-RPC 1.0 uses an id value of Null for Notifications this could cause confusion in handling.\\n\\n[2] Fractional parts may be problematic, since many decimal fractions cannot be represented exactly as binary fractions.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nNotification to cancel an ongoing request.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/cancellation)\",\n});\n\nexport type ClientCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly auth?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly terminal?: boolean;\n  };\n  readonly elicitation?: ElicitationCapabilities | null;\n  readonly fs?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly readTextFile?: boolean;\n    readonly writeTextFile?: boolean;\n  };\n  readonly terminal?: boolean;\n};\nexport const ClientCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  auth: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      terminal: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description:\n            \"Whether the client supports `terminal` authentication methods.\\n\\nWhen `true`, the agent may include `terminal` entries in its authentication methods.\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent which authentication\\nmethod types the client can handle. This governs opt-in types that require\\nadditional client-side support.\",\n      default: { terminal: false },\n    }),\n  ),\n  elicitation: Schema.optionalKey(\n    Schema.Union([ElicitationCapabilities, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nElicitation capabilities supported by the client.\\nDetermines which elicitation modes the agent may use.\",\n    }),\n  ),\n  fs: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      readTextFile: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Whether the Client supports `fs/read_text_file` requests.\",\n          default: false,\n        }),\n      ),\n      writeTextFile: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Whether the Client supports `fs/write_text_file` requests.\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description:\n        \"File system capabilities that a client may support.\\n\\nSee protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/initialization#filesystem)\",\n      default: { readTextFile: false, writeTextFile: false },\n    }),\n  ),\n  terminal: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether the Client support all `terminal/*` methods.\",\n      default: false,\n    }),\n  ),\n}).annotate({\n  description:\n    \"Capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent about\\navailable features and methods.\\n\\nSee protocol docs: [Client Capabilities](https://agentclientprotocol.com/protocol/initialization#client-capabilities)\",\n});\n\nexport type ClientNotification = {\n  readonly method: string;\n  readonly params?:\n    | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly sessionId: string }\n    | unknown\n    | null;\n};\nexport const ClientNotification = Schema.Struct({\n  method: Schema.String,\n  params: Schema.optionalKey(\n    Schema.Union([\n      Schema.Union([\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"CancelNotification\",\n          description:\n            \"Notification to cancel ongoing operations for a session.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n        }),\n        Schema.Unknown.annotate({\n          title: \"ExtNotification\",\n          description:\n            \"Allows the Agent to send an arbitrary notification that is not part of the ACP spec.\\nExtension notifications provide a way to send one-way messages for custom functionality\\nwhile maintaining protocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n      ]).annotate({\n        description:\n          \"All possible notifications that a client can send to an agent.\\n\\nThis enum is used internally for routing RPC notifications. You typically won't need\\nto use this directly - use the notification methods on the [`Agent`] trait instead.\\n\\nNotifications do not expect a response.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientRequest = {\n  readonly id: RequestId;\n  readonly method: string;\n  readonly params?:\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly clientCapabilities?: {\n          readonly _meta?: { readonly [x: string]: unknown } | null;\n          readonly auth?: {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly terminal?: boolean;\n          };\n          readonly elicitation?: ElicitationCapabilities | null;\n          readonly fs?: {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly readTextFile?: boolean;\n            readonly writeTextFile?: boolean;\n          };\n          readonly terminal?: boolean;\n        };\n        readonly clientInfo?: Implementation | null;\n        readonly protocolVersion: number;\n      }\n    | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly methodId: string }\n    | { readonly _meta?: { readonly [x: string]: unknown } | null }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cwd: string;\n        readonly mcpServers: ReadonlyArray<McpServer>;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cwd: string;\n        readonly mcpServers: ReadonlyArray<McpServer>;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cursor?: string | null;\n        readonly cwd?: string | null;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cwd: string;\n        readonly mcpServers?: ReadonlyArray<McpServer>;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cwd: string;\n        readonly mcpServers?: ReadonlyArray<McpServer>;\n        readonly sessionId: string;\n      }\n    | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly sessionId: string }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly modeId: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly type: \"boolean\";\n        readonly value: boolean;\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly configId: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly value: string;\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly configId: string;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly messageId?: string | null;\n        readonly prompt: ReadonlyArray<ContentBlock>;\n        readonly sessionId: string;\n      }\n    | {\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly modelId: string;\n        readonly sessionId: string;\n      }\n    | unknown\n    | null;\n};\nexport const ClientRequest = Schema.Struct({\n  id: RequestId,\n  method: Schema.String,\n  params: Schema.optionalKey(\n    Schema.Union([\n      Schema.Union([\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          clientCapabilities: Schema.optionalKey(\n            Schema.Struct({\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              auth: Schema.optionalKey(\n                Schema.Struct({\n                  _meta: Schema.optionalKey(\n                    Schema.Union([\n                      Schema.Record(Schema.String, Schema.Unknown).annotate({\n                        description:\n                          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                      }),\n                      Schema.Null,\n                    ]),\n                  ),\n                  terminal: Schema.optionalKey(\n                    Schema.Boolean.annotate({\n                      description:\n                        \"Whether the client supports `terminal` authentication methods.\\n\\nWhen `true`, the agent may include `terminal` entries in its authentication methods.\",\n                      default: false,\n                    }),\n                  ),\n                }).annotate({\n                  description:\n                    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent which authentication\\nmethod types the client can handle. This governs opt-in types that require\\nadditional client-side support.\",\n                  default: { terminal: false },\n                }),\n              ),\n              elicitation: Schema.optionalKey(\n                Schema.Union([ElicitationCapabilities, Schema.Null]).annotate({\n                  description:\n                    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nElicitation capabilities supported by the client.\\nDetermines which elicitation modes the agent may use.\",\n                }),\n              ),\n              fs: Schema.optionalKey(\n                Schema.Struct({\n                  _meta: Schema.optionalKey(\n                    Schema.Union([\n                      Schema.Record(Schema.String, Schema.Unknown).annotate({\n                        description:\n                          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                      }),\n                      Schema.Null,\n                    ]),\n                  ),\n                  readTextFile: Schema.optionalKey(\n                    Schema.Boolean.annotate({\n                      description: \"Whether the Client supports `fs/read_text_file` requests.\",\n                      default: false,\n                    }),\n                  ),\n                  writeTextFile: Schema.optionalKey(\n                    Schema.Boolean.annotate({\n                      description: \"Whether the Client supports `fs/write_text_file` requests.\",\n                      default: false,\n                    }),\n                  ),\n                }).annotate({\n                  description:\n                    \"File system capabilities that a client may support.\\n\\nSee protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/initialization#filesystem)\",\n                  default: { readTextFile: false, writeTextFile: false },\n                }),\n              ),\n              terminal: Schema.optionalKey(\n                Schema.Boolean.annotate({\n                  description: \"Whether the Client support all `terminal/*` methods.\",\n                  default: false,\n                }),\n              ),\n            }).annotate({\n              description:\n                \"Capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent about\\navailable features and methods.\\n\\nSee protocol docs: [Client Capabilities](https://agentclientprotocol.com/protocol/initialization#client-capabilities)\",\n              default: {\n                auth: { terminal: false },\n                fs: { readTextFile: false, writeTextFile: false },\n                terminal: false,\n              },\n            }),\n          ),\n          clientInfo: Schema.optionalKey(\n            Schema.Union([Implementation, Schema.Null]).annotate({\n              description:\n                \"Information about the Client name and version sent to the Agent.\\n\\nNote: in future versions of the protocol, this will be required.\",\n            }),\n          ),\n          protocolVersion: Schema.Number.annotate({\n            description:\n              \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n            format: \"uint16\",\n          })\n            .check(Schema.isInt())\n            .check(Schema.isGreaterThanOrEqualTo(0))\n            .check(Schema.isLessThanOrEqualTo(65535)),\n        }).annotate({\n          title: \"InitializeRequest\",\n          description:\n            \"Request parameters for the initialize method.\\n\\nSent by the client to establish connection and negotiate capabilities.\\n\\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          methodId: Schema.String.annotate({\n            description:\n              \"The ID of the authentication method to use.\\nMust be one of the methods advertised in the initialize response.\",\n          }),\n        }).annotate({\n          title: \"AuthenticateRequest\",\n          description:\n            \"Request parameters for the authenticate method.\\n\\nSpecifies which authentication method to use.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n        }).annotate({\n          title: \"LogoutRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for the logout method.\\n\\nTerminates the current authenticated session.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.String.annotate({\n            description: \"The working directory for this session. Must be an absolute path.\",\n          }),\n          mcpServers: Schema.Array(McpServer).annotate({\n            description:\n              \"List of MCP (Model Context Protocol) servers the agent should connect to.\",\n          }),\n        }).annotate({\n          title: \"NewSessionRequest\",\n          description:\n            \"Request parameters for creating a new session.\\n\\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n          mcpServers: Schema.Array(McpServer).annotate({\n            description: \"List of MCP servers to connect to for this session.\",\n          }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"LoadSessionRequest\",\n          description:\n            \"Request parameters for loading an existing session.\\n\\nOnly available if the Agent supports the `loadSession` capability.\\n\\nSee protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cursor: Schema.optionalKey(\n            Schema.Union([\n              Schema.String.annotate({\n                description:\n                  \"Opaque cursor token from a previous response's nextCursor field for cursor-based pagination\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.optionalKey(\n            Schema.Union([\n              Schema.String.annotate({\n                description: \"Filter sessions by working directory. Must be an absolute path.\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n        }).annotate({\n          title: \"ListSessionsRequest\",\n          description:\n            \"Request parameters for listing existing sessions.\\n\\nOnly available if the Agent supports the `sessionCapabilities.list` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n          mcpServers: Schema.optionalKey(\n            Schema.Array(McpServer).annotate({\n              description: \"List of MCP servers to connect to for this session.\",\n            }),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"ForkSessionRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for forking an existing session.\\n\\nCreates a new session based on the context of an existing one, allowing\\noperations like generating summaries without affecting the original session's history.\\n\\nOnly available if the Agent supports the `session.fork` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n          mcpServers: Schema.optionalKey(\n            Schema.Array(McpServer).annotate({\n              description: \"List of MCP servers to connect to for this session.\",\n            }),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"ResumeSessionRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for resuming an existing session.\\n\\nResumes an existing session without returning previous messages (unlike `session/load`).\\nThis is useful for agents that can resume sessions but don't implement full session loading.\\n\\nOnly available if the Agent supports the `session.resume` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"CloseSessionRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for closing an active session.\\n\\nIf supported, the agent **must** cancel any ongoing work related to the session\\n(treat it as if `session/cancel` was called) and then free up any resources\\nassociated with the session.\\n\\nOnly available if the Agent supports the `session.close` capability.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          modeId: Schema.String.annotate({ description: \"Unique identifier for a Session Mode.\" }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"SetSessionModeRequest\",\n          description: \"Request parameters for setting a session mode.\",\n        }),\n        Schema.Union([\n          Schema.Struct({\n            type: Schema.Literal(\"boolean\"),\n            value: Schema.Boolean.annotate({ description: \"The boolean value.\" }),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            configId: Schema.String.annotate({\n              description: \"Unique identifier for a session configuration option.\",\n            }),\n            sessionId: Schema.String.annotate({\n              description:\n                \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n            }),\n          }).annotate({\n            description: \"Request parameters for setting a session configuration option.\",\n          }),\n          Schema.Struct({\n            value: Schema.String.annotate({\n              description: \"Unique identifier for a session configuration option value.\",\n            }),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            configId: Schema.String.annotate({\n              description: \"Unique identifier for a session configuration option.\",\n            }),\n            sessionId: Schema.String.annotate({\n              description:\n                \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n            }),\n          }).annotate({\n            title: \"value_id\",\n            description: \"Request parameters for setting a session configuration option.\",\n          }),\n        ]).annotate({\n          title: \"SetSessionConfigOptionRequest\",\n          description: \"Sets the current value for a session configuration option.\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          messageId: Schema.optionalKey(\n            Schema.Union([\n              Schema.String.annotate({\n                description:\n                  \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA client-generated unique identifier for this user message.\\n\\nIf provided, the Agent SHOULD echo this value as `userMessageId` in the\\n[`PromptResponse`] to confirm it was recorded.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          prompt: Schema.Array(ContentBlock).annotate({\n            description:\n              \"The blocks of content that compose the user's message.\\n\\nAs a baseline, the Agent MUST support [`ContentBlock::Text`] and [`ContentBlock::ResourceLink`],\\nwhile other variants are optionally enabled via [`PromptCapabilities`].\\n\\nThe Client MUST adapt its interface according to [`PromptCapabilities`].\\n\\nThe client MAY include referenced pieces of context as either\\n[`ContentBlock::Resource`] or [`ContentBlock::ResourceLink`].\\n\\nWhen available, [`ContentBlock::Resource`] is preferred\\nas it avoids extra round-trips and allows the message to include\\npieces of context from sources the agent may not have access to.\",\n          }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"PromptRequest\",\n          description:\n            \"Request parameters for sending a user prompt to the agent.\\n\\nContains the user's message and any additional context.\\n\\nSee protocol docs: [User Message](https://agentclientprotocol.com/protocol/prompt-turn#1-user-message)\",\n        }),\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          modelId: Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n          }),\n          sessionId: Schema.String.annotate({\n            description:\n              \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n          }),\n        }).annotate({\n          title: \"SetSessionModelRequest\",\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for setting a session model.\",\n        }),\n        Schema.Unknown.annotate({\n          title: \"ExtMethodRequest\",\n          description:\n            \"Allows for sending an arbitrary request that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n      ]).annotate({\n        description:\n          \"All possible requests that a client can send to an agent.\\n\\nThis enum is used internally for routing RPC requests. You typically won't need\\nto use this directly - instead, use the methods on the [`Agent`] trait.\\n\\nThis enum encompasses all method calls from client to agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n});\n\nexport type ClientResponse =\n  | {\n      readonly id: RequestId;\n      readonly result:\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly content: string }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly outcome:\n              | { readonly outcome: \"cancelled\" }\n              | {\n                  readonly outcome: \"selected\";\n                  readonly _meta?: { readonly [x: string]: unknown } | null;\n                  readonly optionId: string;\n                };\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null; readonly terminalId: string }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly exitStatus?: TerminalExitStatus | null;\n            readonly output: string;\n            readonly truncated: boolean;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly exitCode?: number | null;\n            readonly signal?: string | null;\n          }\n        | { readonly _meta?: { readonly [x: string]: unknown } | null }\n        | {\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly action:\n              | {\n                  readonly action: \"accept\";\n                  readonly content?: { readonly [x: string]: ElicitationContentValue } | null;\n                }\n              | { readonly action: \"decline\" }\n              | { readonly action: \"cancel\" };\n          }\n        | unknown;\n    }\n  | { readonly error: Error; readonly id: RequestId };\nexport const ClientResponse = Schema.Union([\n  Schema.Struct({\n    id: RequestId,\n    result: Schema.Union([\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"WriteTextFileResponse\",\n        description: \"Response to `fs/write_text_file`\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.String,\n      }).annotate({\n        title: \"ReadTextFileResponse\",\n        description: \"Response containing the contents of a text file.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        outcome: Schema.Union(\n          [\n            Schema.Struct({ outcome: Schema.Literal(\"cancelled\") }).annotate({\n              description:\n                \"The prompt turn was cancelled before the user responded.\\n\\nWhen a client sends a `session/cancel` notification to cancel an ongoing\\nprompt turn, it MUST respond to all pending `session/request_permission`\\nrequests with this `Cancelled` outcome.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n            }),\n            Schema.Struct({\n              outcome: Schema.Literal(\"selected\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              optionId: Schema.String.annotate({\n                description: \"Unique identifier for a permission option.\",\n              }),\n            }).annotate({ description: \"The user selected one of the provided options.\" }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({ description: \"The outcome of a permission request.\" }),\n      }).annotate({\n        title: \"RequestPermissionResponse\",\n        description: \"Response to a permission request.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        terminalId: Schema.String.annotate({\n          description: \"The unique identifier for the created terminal.\",\n        }),\n      }).annotate({\n        title: \"CreateTerminalResponse\",\n        description: \"Response containing the ID of the created terminal.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        exitStatus: Schema.optionalKey(\n          Schema.Union([TerminalExitStatus, Schema.Null]).annotate({\n            description: \"Exit status if the command has completed.\",\n          }),\n        ),\n        output: Schema.String.annotate({ description: \"The terminal output captured so far.\" }),\n        truncated: Schema.Boolean.annotate({\n          description: \"Whether the output was truncated due to byte limits.\",\n        }),\n      }).annotate({\n        title: \"TerminalOutputResponse\",\n        description: \"Response containing the terminal output and exit status.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"ReleaseTerminalResponse\",\n        description: \"Response to terminal/release method\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        exitCode: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({\n              description: \"The process exit code (may be null if terminated by signal).\",\n              format: \"uint32\",\n            })\n              .check(Schema.isInt())\n              .check(Schema.isGreaterThanOrEqualTo(0)),\n            Schema.Null,\n          ]),\n        ),\n        signal: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"The signal that terminated the process (may be null if exited normally).\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"WaitForTerminalExitResponse\",\n        description: \"Response containing the exit status of a terminal command.\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        title: \"KillTerminalResponse\",\n        description: \"Response to `terminal/kill` method\",\n      }),\n      Schema.Struct({\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        action: Schema.Union(\n          [\n            Schema.Struct({\n              action: Schema.Literal(\"accept\"),\n              content: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, ElicitationContentValue).annotate({\n                    description:\n                      \"The user-provided content, if any, as an object matching the requested schema.\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n            }).annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user accepted the elicitation and provided content.\",\n            }),\n            Schema.Struct({ action: Schema.Literal(\"decline\") }).annotate({\n              description: \"The user declined the elicitation.\",\n            }),\n            Schema.Struct({ action: Schema.Literal(\"cancel\") }).annotate({\n              description: \"The elicitation was cancelled.\",\n            }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user's action in response to an elicitation.\",\n        }),\n      }).annotate({\n        title: \"ElicitationResponse\",\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from the client to an elicitation request.\",\n      }),\n      Schema.Unknown.annotate({\n        title: \"ExtMethodResponse\",\n        description:\n          \"Allows for sending an arbitrary response to an [`ExtRequest`] that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n    ]).annotate({\n      description:\n        \"All possible responses that a client can send to an agent.\\n\\nThis enum is used internally for routing RPC responses. You typically won't need\\nto use this directly - the responses are handled automatically by the connection.\\n\\nThese are responses to the corresponding `AgentRequest` variants.\",\n    }),\n  }).annotate({ title: \"Result\" }),\n  Schema.Struct({ error: Error, id: RequestId }).annotate({ title: \"Error\" }),\n]);\n\nexport type CloseSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n};\nexport const CloseSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for closing an active session.\\n\\nIf supported, the agent **must** cancel any ongoing work related to the session\\n(treat it as if `session/cancel` was called) and then free up any resources\\nassociated with the session.\\n\\nOnly available if the Agent supports the `session.close` capability.\",\n});\n\nexport type CloseSessionResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const CloseSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from closing a session.\",\n});\n\nexport type ConfigOptionUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions: ReadonlyArray<SessionConfigOption>;\n};\nexport const ConfigOptionUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.Array(SessionConfigOption).annotate({\n    description: \"The full set of configuration options and their current values.\",\n  }),\n}).annotate({ description: \"Session configuration options have been updated.\" });\n\nexport type Content = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content:\n    | {\n        readonly type: \"text\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly text: string;\n      }\n    | {\n        readonly type: \"image\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly data: string;\n        readonly mimeType: string;\n        readonly uri?: string | null;\n      }\n    | {\n        readonly type: \"audio\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly data: string;\n        readonly mimeType: string;\n      }\n    | {\n        readonly type: \"resource_link\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly description?: string | null;\n        readonly mimeType?: string | null;\n        readonly name: string;\n        readonly size?: number | null;\n        readonly title?: string | null;\n        readonly uri: string;\n      }\n    | {\n        readonly type: \"resource\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly resource: EmbeddedResourceResource;\n      };\n};\nexport const Content = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"text\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        text: Schema.String,\n      }).annotate({ description: \"Text provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"image\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        data: Schema.String,\n        mimeType: Schema.String,\n        uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      }).annotate({ description: \"An image provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"audio\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        data: Schema.String,\n        mimeType: Schema.String,\n      }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"resource_link\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        name: Schema.String,\n        size: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n            Schema.Null,\n          ]),\n        ),\n        title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        uri: Schema.String,\n      }).annotate({\n        description:\n          \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n      }),\n      Schema.Struct({\n        type: Schema.Literal(\"resource\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        resource: EmbeddedResourceResource,\n      }).annotate({\n        description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n  }),\n}).annotate({ description: \"Standard content block (text, images, resources).\" });\n\nexport type ContentChunk = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content:\n    | {\n        readonly type: \"text\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly text: string;\n      }\n    | {\n        readonly type: \"image\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly data: string;\n        readonly mimeType: string;\n        readonly uri?: string | null;\n      }\n    | {\n        readonly type: \"audio\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly data: string;\n        readonly mimeType: string;\n      }\n    | {\n        readonly type: \"resource_link\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly description?: string | null;\n        readonly mimeType?: string | null;\n        readonly name: string;\n        readonly size?: number | null;\n        readonly title?: string | null;\n        readonly uri: string;\n      }\n    | {\n        readonly type: \"resource\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly annotations?: Annotations | null;\n        readonly resource: EmbeddedResourceResource;\n      };\n  readonly messageId?: string | null;\n};\nexport const ContentChunk = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.Union(\n    [\n      Schema.Struct({\n        type: Schema.Literal(\"text\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        text: Schema.String,\n      }).annotate({ description: \"Text provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"image\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        data: Schema.String,\n        mimeType: Schema.String,\n        uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n      }).annotate({ description: \"An image provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"audio\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        data: Schema.String,\n        mimeType: Schema.String,\n      }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n      Schema.Struct({\n        type: Schema.Literal(\"resource_link\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        name: Schema.String,\n        size: Schema.optionalKey(\n          Schema.Union([\n            Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n            Schema.Null,\n          ]),\n        ),\n        title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n        uri: Schema.String,\n      }).annotate({\n        description:\n          \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n      }),\n      Schema.Struct({\n        type: Schema.Literal(\"resource\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n        resource: EmbeddedResourceResource,\n      }).annotate({\n        description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n  }),\n  messageId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"A streamed item of content\" });\n\nexport type CreateTerminalRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly args?: ReadonlyArray<string>;\n  readonly command: string;\n  readonly cwd?: string | null;\n  readonly env?: ReadonlyArray<EnvVariable>;\n  readonly outputByteLimit?: number | null;\n  readonly sessionId: string;\n};\nexport const CreateTerminalRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  args: Schema.optionalKey(\n    Schema.Array(Schema.String).annotate({ description: \"Array of command arguments.\" }),\n  ),\n  command: Schema.String.annotate({ description: \"The command to execute.\" }),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Working directory for the command (absolute path).\" }),\n      Schema.Null,\n    ]),\n  ),\n  env: Schema.optionalKey(\n    Schema.Array(EnvVariable).annotate({ description: \"Environment variables for the command.\" }),\n  ),\n  outputByteLimit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description:\n          \"Maximum number of output bytes to retain.\\n\\nWhen the limit is exceeded, the Client truncates from the beginning of the output\\nto stay within the limit.\\n\\nThe Client MUST ensure truncation happens at a character boundary to maintain valid\\nstring output, even if this means the retained output is slightly less than the\\nspecified limit.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({ description: \"Request to create a new terminal and execute a command.\" });\n\nexport type CreateTerminalResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly terminalId: string;\n};\nexport const CreateTerminalResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  terminalId: Schema.String.annotate({\n    description: \"The unique identifier for the created terminal.\",\n  }),\n}).annotate({ description: \"Response containing the ID of the created terminal.\" });\n\nexport type CurrentModeUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly currentModeId: string;\n};\nexport const CurrentModeUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  currentModeId: Schema.String.annotate({ description: \"Unique identifier for a Session Mode.\" }),\n}).annotate({\n  description:\n    \"The current mode of the session has changed\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n});\n\nexport type Diff = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly newText: string;\n  readonly oldText?: string | null;\n  readonly path: string;\n};\nexport const Diff = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  newText: Schema.String.annotate({ description: \"The new content after modification.\" }),\n  oldText: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"The original content (None for new files).\" }),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({ description: \"The file path being modified.\" }),\n}).annotate({\n  description:\n    \"A diff representing file modifications.\\n\\nShows changes to files in a format suitable for display in the client UI.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/tool-calls#content)\",\n});\n\nexport type ElicitationAcceptAction = {\n  readonly content?: { readonly [x: string]: ElicitationContentValue } | null;\n};\nexport const ElicitationAcceptAction = Schema.Struct({\n  content: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, ElicitationContentValue).annotate({\n        description:\n          \"The user-provided content, if any, as an object matching the requested schema.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user accepted the elicitation and provided content.\",\n});\n\nexport type ElicitationAction =\n  | {\n      readonly action: \"accept\";\n      readonly content?: { readonly [x: string]: ElicitationContentValue } | null;\n    }\n  | { readonly action: \"decline\" }\n  | { readonly action: \"cancel\" };\nexport const ElicitationAction = Schema.Union(\n  [\n    Schema.Struct({\n      action: Schema.Literal(\"accept\"),\n      content: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, ElicitationContentValue).annotate({\n            description:\n              \"The user-provided content, if any, as an object matching the requested schema.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user accepted the elicitation and provided content.\",\n    }),\n    Schema.Struct({ action: Schema.Literal(\"decline\") }).annotate({\n      description: \"The user declined the elicitation.\",\n    }),\n    Schema.Struct({ action: Schema.Literal(\"cancel\") }).annotate({\n      description: \"The elicitation was cancelled.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user's action in response to an elicitation.\",\n});\n\nexport type ElicitationCompleteNotification = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly elicitationId: string;\n};\nexport const ElicitationCompleteNotification = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  elicitationId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nNotification sent by the agent when a URL-based elicitation is complete.\",\n});\n\nexport type ElicitationFormMode = {\n  readonly requestedSchema: {\n    readonly description?: string | null;\n    readonly properties?: { readonly [x: string]: ElicitationPropertySchema };\n    readonly required?: ReadonlyArray<string> | null;\n    readonly title?: string | null;\n    readonly type?: \"object\";\n  };\n};\nexport const ElicitationFormMode = Schema.Struct({\n  requestedSchema: Schema.Struct({\n    description: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({\n          description: \"Optional description of what this schema represents.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    properties: Schema.optionalKey(\n      Schema.Record(Schema.String, ElicitationPropertySchema).annotate({\n        description: \"Property definitions (must be primitive types).\",\n        default: {},\n      }),\n    ),\n    required: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(Schema.String).annotate({ description: \"List of required property names.\" }),\n        Schema.Null,\n      ]),\n    ),\n    title: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({ description: \"Optional title for the schema.\" }),\n        Schema.Null,\n      ]),\n    ),\n    type: Schema.optionalKey(\n      Schema.Literal(\"object\").annotate({\n        description: \"Type discriminator for elicitation schemas.\",\n        default: \"object\",\n      }),\n    ),\n  }).annotate({\n    description:\n      \"Type-safe elicitation schema for requesting structured user input.\\n\\nThis represents a JSON Schema object with primitive-typed properties,\\nas required by the elicitation specification.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nForm-based elicitation mode where the client renders a form from the provided schema.\",\n});\n\nexport type ElicitationId = string;\nexport const ElicitationId = Schema.String.annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n});\n\nexport type ElicitationRequest =\n  | {\n      readonly mode: \"form\";\n      readonly requestedSchema: {\n        readonly description?: string | null;\n        readonly properties?: { readonly [x: string]: ElicitationPropertySchema };\n        readonly required?: ReadonlyArray<string> | null;\n        readonly title?: string | null;\n        readonly type?: \"object\";\n      };\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly message: string;\n      readonly sessionId: string;\n    }\n  | {\n      readonly mode: \"url\";\n      readonly elicitationId: string;\n      readonly url: string;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly message: string;\n      readonly sessionId: string;\n    };\nexport const ElicitationRequest = Schema.Union([\n  Schema.Struct({\n    mode: Schema.Literal(\"form\"),\n    requestedSchema: Schema.Struct({\n      description: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Optional description of what this schema represents.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      properties: Schema.optionalKey(\n        Schema.Record(Schema.String, ElicitationPropertySchema).annotate({\n          description: \"Property definitions (must be primitive types).\",\n          default: {},\n        }),\n      ),\n      required: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(Schema.String).annotate({ description: \"List of required property names.\" }),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Optional title for the schema.\" }),\n          Schema.Null,\n        ]),\n      ),\n      type: Schema.optionalKey(\n        Schema.Literal(\"object\").annotate({\n          description: \"Type discriminator for elicitation schemas.\",\n          default: \"object\",\n        }),\n      ),\n    }).annotate({\n      description:\n        \"Type-safe elicitation schema for requesting structured user input.\\n\\nThis represents a JSON Schema object with primitive-typed properties,\\nas required by the elicitation specification.\",\n    }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    message: Schema.String.annotate({\n      description: \"A human-readable message describing what input is needed.\",\n    }),\n    sessionId: Schema.String.annotate({\n      description:\n        \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n    }),\n  }).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest from the agent to elicit structured user input.\\n\\nThe agent sends this to the client to request information from the user,\\neither via a form or by directing them to a URL.\",\n  }),\n  Schema.Struct({\n    mode: Schema.Literal(\"url\"),\n    elicitationId: Schema.String.annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n    }),\n    url: Schema.String.annotate({ description: \"The URL to direct the user to.\", format: \"uri\" }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    message: Schema.String.annotate({\n      description: \"A human-readable message describing what input is needed.\",\n    }),\n    sessionId: Schema.String.annotate({\n      description:\n        \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n    }),\n  }).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest from the agent to elicit structured user input.\\n\\nThe agent sends this to the client to request information from the user,\\neither via a form or by directing them to a URL.\",\n  }),\n]);\n\nexport type ElicitationResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly action:\n    | {\n        readonly action: \"accept\";\n        readonly content?: { readonly [x: string]: ElicitationContentValue } | null;\n      }\n    | { readonly action: \"decline\" }\n    | { readonly action: \"cancel\" };\n};\nexport const ElicitationResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  action: Schema.Union(\n    [\n      Schema.Struct({\n        action: Schema.Literal(\"accept\"),\n        content: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, ElicitationContentValue).annotate({\n              description:\n                \"The user-provided content, if any, as an object matching the requested schema.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user accepted the elicitation and provided content.\",\n      }),\n      Schema.Struct({ action: Schema.Literal(\"decline\") }).annotate({\n        description: \"The user declined the elicitation.\",\n      }),\n      Schema.Struct({ action: Schema.Literal(\"cancel\") }).annotate({\n        description: \"The elicitation was cancelled.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe user's action in response to an elicitation.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from the client to an elicitation request.\",\n});\n\nexport type ElicitationSchema = {\n  readonly description?: string | null;\n  readonly properties?: { readonly [x: string]: ElicitationPropertySchema };\n  readonly required?: ReadonlyArray<string> | null;\n  readonly title?: string | null;\n  readonly type?: \"object\";\n};\nexport const ElicitationSchema = Schema.Struct({\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Optional description of what this schema represents.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  properties: Schema.optionalKey(\n    Schema.Record(Schema.String, ElicitationPropertySchema).annotate({\n      description: \"Property definitions (must be primitive types).\",\n      default: {},\n    }),\n  ),\n  required: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({ description: \"List of required property names.\" }),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the schema.\" }),\n      Schema.Null,\n    ]),\n  ),\n  type: Schema.optionalKey(\n    Schema.Literal(\"object\").annotate({\n      description: \"Type discriminator for elicitation schemas.\",\n      default: \"object\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Type-safe elicitation schema for requesting structured user input.\\n\\nThis represents a JSON Schema object with primitive-typed properties,\\nas required by the elicitation specification.\",\n});\n\nexport type ElicitationSchemaType = \"object\";\nexport const ElicitationSchemaType = Schema.Literal(\"object\").annotate({\n  description: \"Type discriminator for elicitation schemas.\",\n});\n\nexport type ElicitationStringType = \"string\";\nexport const ElicitationStringType = Schema.Literal(\"string\").annotate({\n  description: \"Items definition for untitled multi-select enum properties.\",\n});\n\nexport type ElicitationUrlMode = { readonly elicitationId: string; readonly url: string };\nexport const ElicitationUrlMode = Schema.Struct({\n  elicitationId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nUnique identifier for an elicitation.\",\n  }),\n  url: Schema.String.annotate({ description: \"The URL to direct the user to.\", format: \"uri\" }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nURL-based elicitation mode where the client directs the user to a URL.\",\n});\n\nexport type EmbeddedResource = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly resource: EmbeddedResourceResource;\n};\nexport const EmbeddedResource = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  resource: EmbeddedResourceResource,\n}).annotate({\n  description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n});\n\nexport type ErrorCode =\n  | -32700\n  | -32600\n  | -32601\n  | -32602\n  | -32603\n  | -32800\n  | -32000\n  | -32002\n  | -32042\n  | number;\nexport const ErrorCode = Schema.Union([\n  Schema.Literal(-32700).annotate({\n    title: \"Parse error\",\n    description:\n      \"**Parse error**: Invalid JSON was received by the server.\\nAn error occurred on the server while parsing the JSON text.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32600).annotate({\n    title: \"Invalid request\",\n    description: \"**Invalid request**: The JSON sent is not a valid Request object.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32601).annotate({\n    title: \"Method not found\",\n    description: \"**Method not found**: The method does not exist or is not available.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32602).annotate({\n    title: \"Invalid params\",\n    description: \"**Invalid params**: Invalid method parameter(s).\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32603).annotate({\n    title: \"Internal error\",\n    description:\n      \"**Internal error**: Internal JSON-RPC error.\\nReserved for implementation-defined server errors.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32800).annotate({\n    title: \"Request cancelled\",\n    description:\n      \"**Request cancelled**: **UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nExecution of the method was aborted either due to a cancellation request from the caller or\\nbecause of resource constraints or shutdown.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32000).annotate({\n    title: \"Authentication required\",\n    description:\n      \"**Authentication required**: Authentication is required before this operation can be performed.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32002).annotate({\n    title: \"Resource not found\",\n    description: \"**Resource not found**: A given resource, such as a file, was not found.\",\n    format: \"int32\",\n  }),\n  Schema.Literal(-32042).annotate({\n    title: \"URL elicitation required\",\n    description:\n      \"**URL elicitation required**: **UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe agent requires user input via a URL-based elicitation before it can proceed.\",\n    format: \"int32\",\n  }),\n  Schema.Number.annotate({\n    title: \"Other\",\n    description: \"Other undefined error code.\",\n    format: \"int32\",\n  }).check(Schema.isInt()),\n]).annotate({\n  description:\n    \"Predefined error codes for common JSON-RPC and ACP-specific errors.\\n\\nThese codes follow the JSON-RPC 2.0 specification for standard errors\\nand use the reserved range (-32000 to -32099) for protocol-specific errors.\",\n});\n\nexport type ExtNotification = unknown;\nexport const ExtNotification = Schema.Unknown.annotate({\n  description:\n    \"Allows the Agent to send an arbitrary notification that is not part of the ACP spec.\\nExtension notifications provide a way to send one-way messages for custom functionality\\nwhile maintaining protocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n});\n\nexport type ExtRequest = unknown;\nexport const ExtRequest = Schema.Unknown.annotate({\n  description:\n    \"Allows for sending an arbitrary request that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n});\n\nexport type ExtResponse = unknown;\nexport const ExtResponse = Schema.Unknown.annotate({\n  description:\n    \"Allows for sending an arbitrary response to an [`ExtRequest`] that is not part of the ACP spec.\\nExtension methods provide a way to add custom functionality while maintaining\\nprotocol compatibility.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n});\n\nexport type FileSystemCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly readTextFile?: boolean;\n  readonly writeTextFile?: boolean;\n};\nexport const FileSystemCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  readTextFile: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether the Client supports `fs/read_text_file` requests.\",\n      default: false,\n    }),\n  ),\n  writeTextFile: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Whether the Client supports `fs/write_text_file` requests.\",\n      default: false,\n    }),\n  ),\n}).annotate({\n  description:\n    \"File system capabilities that a client may support.\\n\\nSee protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/initialization#filesystem)\",\n});\n\nexport type ForkSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly mcpServers?: ReadonlyArray<McpServer>;\n  readonly sessionId: string;\n};\nexport const ForkSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(McpServer).annotate({\n      description: \"List of MCP servers to connect to for this session.\",\n    }),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for forking an existing session.\\n\\nCreates a new session based on the context of an existing one, allowing\\noperations like generating summaries without affecting the original session's history.\\n\\nOnly available if the Agent supports the `session.fork` capability.\",\n});\n\nexport type ForkSessionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n  readonly models?: SessionModelState | null;\n  readonly modes?: SessionModeState | null;\n  readonly sessionId: string;\n};\nexport const ForkSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(SessionConfigOption).annotate({\n        description: \"Initial session configuration options if supported by the Agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([SessionModelState, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n    }),\n  ),\n  modes: Schema.optionalKey(\n    Schema.Union([SessionModeState, Schema.Null]).annotate({\n      description:\n        \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from forking an existing session.\",\n});\n\nexport type ImageContent = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly data: string;\n  readonly mimeType: string;\n  readonly uri?: string | null;\n};\nexport const ImageContent = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  data: Schema.String,\n  mimeType: Schema.String,\n  uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n}).annotate({ description: \"An image provided to or from an LLM.\" });\n\nexport type InitializeRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly clientCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly auth?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly terminal?: boolean;\n    };\n    readonly elicitation?: ElicitationCapabilities | null;\n    readonly fs?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly readTextFile?: boolean;\n      readonly writeTextFile?: boolean;\n    };\n    readonly terminal?: boolean;\n  };\n  readonly clientInfo?: Implementation | null;\n  readonly protocolVersion: number;\n};\nexport const InitializeRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  clientCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      auth: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          terminal: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description:\n                \"Whether the client supports `terminal` authentication methods.\\n\\nWhen `true`, the agent may include `terminal` entries in its authentication methods.\",\n              default: false,\n            }),\n          ),\n        }).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent which authentication\\nmethod types the client can handle. This governs opt-in types that require\\nadditional client-side support.\",\n          default: { terminal: false },\n        }),\n      ),\n      elicitation: Schema.optionalKey(\n        Schema.Union([ElicitationCapabilities, Schema.Null]).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nElicitation capabilities supported by the client.\\nDetermines which elicitation modes the agent may use.\",\n        }),\n      ),\n      fs: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          readTextFile: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Whether the Client supports `fs/read_text_file` requests.\",\n              default: false,\n            }),\n          ),\n          writeTextFile: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Whether the Client supports `fs/write_text_file` requests.\",\n              default: false,\n            }),\n          ),\n        }).annotate({\n          description:\n            \"File system capabilities that a client may support.\\n\\nSee protocol docs: [FileSystem](https://agentclientprotocol.com/protocol/initialization#filesystem)\",\n          default: { readTextFile: false, writeTextFile: false },\n        }),\n      ),\n      terminal: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Whether the Client support all `terminal/*` methods.\",\n          default: false,\n        }),\n      ),\n    }).annotate({\n      description:\n        \"Capabilities supported by the client.\\n\\nAdvertised during initialization to inform the agent about\\navailable features and methods.\\n\\nSee protocol docs: [Client Capabilities](https://agentclientprotocol.com/protocol/initialization#client-capabilities)\",\n      default: {\n        auth: { terminal: false },\n        fs: { readTextFile: false, writeTextFile: false },\n        terminal: false,\n      },\n    }),\n  ),\n  clientInfo: Schema.optionalKey(\n    Schema.Union([Implementation, Schema.Null]).annotate({\n      description:\n        \"Information about the Client name and version sent to the Agent.\\n\\nNote: in future versions of the protocol, this will be required.\",\n    }),\n  ),\n  protocolVersion: Schema.Number.annotate({\n    description:\n      \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0))\n    .check(Schema.isLessThanOrEqualTo(65535)),\n}).annotate({\n  description:\n    \"Request parameters for the initialize method.\\n\\nSent by the client to establish connection and negotiate capabilities.\\n\\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)\",\n});\n\nexport type InitializeResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly agentCapabilities?: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly auth?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly logout?: LogoutCapabilities | null;\n    };\n    readonly loadSession?: boolean;\n    readonly mcpCapabilities?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly http?: boolean;\n      readonly sse?: boolean;\n    };\n    readonly promptCapabilities?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly audio?: boolean;\n      readonly embeddedContext?: boolean;\n      readonly image?: boolean;\n    };\n    readonly sessionCapabilities?: {\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly close?: SessionCloseCapabilities | null;\n      readonly fork?: SessionForkCapabilities | null;\n      readonly list?: SessionListCapabilities | null;\n      readonly resume?: SessionResumeCapabilities | null;\n    };\n  };\n  readonly agentInfo?: Implementation | null;\n  readonly authMethods?: ReadonlyArray<AuthMethod>;\n  readonly protocolVersion: number;\n};\nexport const InitializeResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  agentCapabilities: Schema.optionalKey(\n    Schema.Struct({\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      auth: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          logout: Schema.optionalKey(\n            Schema.Union([LogoutCapabilities, Schema.Null]).annotate({\n              description:\n                \"Whether the agent supports the logout method.\\n\\nBy supplying `{}` it means that the agent supports the logout method.\",\n            }),\n          ),\n        }).annotate({\n          description:\n            \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nAuthentication-related capabilities supported by the agent.\",\n          default: {},\n        }),\n      ),\n      loadSession: Schema.optionalKey(\n        Schema.Boolean.annotate({\n          description: \"Whether the agent supports `session/load`.\",\n          default: false,\n        }),\n      ),\n      mcpCapabilities: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          http: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Agent supports [`McpServer::Http`].\",\n              default: false,\n            }),\n          ),\n          sse: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Agent supports [`McpServer::Sse`].\",\n              default: false,\n            }),\n          ),\n        }).annotate({\n          description: \"MCP capabilities supported by the agent\",\n          default: { http: false, sse: false },\n        }),\n      ),\n      promptCapabilities: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          audio: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Agent supports [`ContentBlock::Audio`].\",\n              default: false,\n            }),\n          ),\n          embeddedContext: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description:\n                \"Agent supports embedded context in `session/prompt` requests.\\n\\nWhen enabled, the Client is allowed to include [`ContentBlock::Resource`]\\nin prompt requests for pieces of context that are referenced in the message.\",\n              default: false,\n            }),\n          ),\n          image: Schema.optionalKey(\n            Schema.Boolean.annotate({\n              description: \"Agent supports [`ContentBlock::Image`].\",\n              default: false,\n            }),\n          ),\n        }).annotate({\n          description:\n            \"Prompt capabilities supported by the agent in `session/prompt` requests.\\n\\nBaseline agent functionality requires support for [`ContentBlock::Text`]\\nand [`ContentBlock::ResourceLink`] in prompt requests.\\n\\nOther variants must be explicitly opted in to.\\nCapabilities for different types of content in prompt requests.\\n\\nIndicates which content types beyond the baseline (text and resource links)\\nthe agent can process.\\n\\nSee protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/initialization#prompt-capabilities)\",\n          default: { audio: false, embeddedContext: false, image: false },\n        }),\n      ),\n      sessionCapabilities: Schema.optionalKey(\n        Schema.Struct({\n          _meta: Schema.optionalKey(\n            Schema.Union([\n              Schema.Record(Schema.String, Schema.Unknown).annotate({\n                description:\n                  \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n              }),\n              Schema.Null,\n            ]),\n          ),\n          close: Schema.optionalKey(\n            Schema.Union([SessionCloseCapabilities, Schema.Null]).annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/close`.\",\n            }),\n          ),\n          fork: Schema.optionalKey(\n            Schema.Union([SessionForkCapabilities, Schema.Null]).annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/fork`.\",\n            }),\n          ),\n          list: Schema.optionalKey(\n            Schema.Union([SessionListCapabilities, Schema.Null]).annotate({\n              description: \"Whether the agent supports `session/list`.\",\n            }),\n          ),\n          resume: Schema.optionalKey(\n            Schema.Union([SessionResumeCapabilities, Schema.Null]).annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/resume`.\",\n            }),\n          ),\n        }).annotate({\n          default: {},\n          description:\n            \"Session capabilities supported by the agent.\\n\\nAs a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.\\n\\nOptionally, they **MAY** support other session methods and notifications by specifying additional capabilities.\\n\\nNote: `session/load` is still handled by the top-level `load_session` capability. This will be unified in future versions of the protocol.\\n\\nSee protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/initialization#session-capabilities)\",\n        }),\n      ),\n    }).annotate({\n      description:\n        \"Capabilities supported by the agent.\\n\\nAdvertised during initialization to inform the client about\\navailable features and content types.\\n\\nSee protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/initialization#agent-capabilities)\",\n      default: {\n        auth: {},\n        loadSession: false,\n        mcpCapabilities: { http: false, sse: false },\n        promptCapabilities: { audio: false, embeddedContext: false, image: false },\n        sessionCapabilities: {},\n      },\n    }),\n  ),\n  agentInfo: Schema.optionalKey(\n    Schema.Union([Implementation, Schema.Null]).annotate({\n      description:\n        \"Information about the Agent name and version sent to the Client.\\n\\nNote: in future versions of the protocol, this will be required.\",\n    }),\n  ),\n  authMethods: Schema.optionalKey(\n    Schema.Array(AuthMethod).annotate({\n      description: \"Authentication methods supported by the agent.\",\n      default: [],\n    }),\n  ),\n  protocolVersion: Schema.Number.annotate({\n    description:\n      \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n    format: \"uint16\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0))\n    .check(Schema.isLessThanOrEqualTo(65535)),\n}).annotate({\n  description:\n    \"Response to the `initialize` method.\\n\\nContains the negotiated protocol version and agent capabilities.\\n\\nSee protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)\",\n});\n\nexport type IntegerPropertySchema = {\n  readonly default?: number | null;\n  readonly description?: string | null;\n  readonly maximum?: number | null;\n  readonly minimum?: number | null;\n  readonly title?: string | null;\n};\nexport const IntegerPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Default value.\", format: \"int64\" }).check(\n        Schema.isInt(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  maximum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Maximum value (inclusive).\", format: \"int64\" }).check(\n        Schema.isInt(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  minimum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Minimum value (inclusive).\", format: \"int64\" }).check(\n        Schema.isInt(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Schema for integer properties in an elicitation form.\" });\n\nexport type KillTerminalRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly terminalId: string;\n};\nexport const KillTerminalRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  terminalId: Schema.String.annotate({ description: \"The ID of the terminal to kill.\" }),\n}).annotate({ description: \"Request to kill a terminal without releasing it.\" });\n\nexport type KillTerminalResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const KillTerminalResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to `terminal/kill` method\" });\n\nexport type ListSessionsRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cursor?: string | null;\n  readonly cwd?: string | null;\n};\nexport const ListSessionsRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor token from a previous response's nextCursor field for cursor-based pagination\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Filter sessions by working directory. Must be an absolute path.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Request parameters for listing existing sessions.\\n\\nOnly available if the Agent supports the `sessionCapabilities.list` capability.\",\n});\n\nexport type ListSessionsResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly nextCursor?: string | null;\n  readonly sessions: ReadonlyArray<SessionInfo>;\n};\nexport const ListSessionsResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  nextCursor: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"Opaque cursor token. If present, pass this in the next request's cursor parameter\\nto fetch the next page. If absent, there are no more results.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessions: Schema.Array(SessionInfo).annotate({\n    description: \"Array of session information objects\",\n  }),\n}).annotate({ description: \"Response from listing sessions.\" });\n\nexport type LoadSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly mcpServers: ReadonlyArray<McpServer>;\n  readonly sessionId: string;\n};\nexport const LoadSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n  mcpServers: Schema.Array(McpServer).annotate({\n    description: \"List of MCP servers to connect to for this session.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Request parameters for loading an existing session.\\n\\nOnly available if the Agent supports the `loadSession` capability.\\n\\nSee protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)\",\n});\n\nexport type LoadSessionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n  readonly models?: SessionModelState | null;\n  readonly modes?: SessionModeState | null;\n};\nexport const LoadSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(SessionConfigOption).annotate({\n        description: \"Initial session configuration options if supported by the Agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([SessionModelState, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n    }),\n  ),\n  modes: Schema.optionalKey(\n    Schema.Union([SessionModeState, Schema.Null]).annotate({\n      description:\n        \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n  ),\n}).annotate({ description: \"Response from loading an existing session.\" });\n\nexport type LogoutRequest = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const LogoutRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for the logout method.\\n\\nTerminates the current authenticated session.\",\n});\n\nexport type LogoutResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const LogoutResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse to the `logout` method.\",\n});\n\nexport type McpCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly http?: boolean;\n  readonly sse?: boolean;\n};\nexport const McpCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  http: Schema.optionalKey(\n    Schema.Boolean.annotate({ description: \"Agent supports [`McpServer::Http`].\", default: false }),\n  ),\n  sse: Schema.optionalKey(\n    Schema.Boolean.annotate({ description: \"Agent supports [`McpServer::Sse`].\", default: false }),\n  ),\n}).annotate({ description: \"MCP capabilities supported by the agent\" });\n\nexport type McpServerHttp = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly headers: ReadonlyArray<HttpHeader>;\n  readonly name: string;\n  readonly url: string;\n};\nexport const McpServerHttp = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  headers: Schema.Array(HttpHeader).annotate({\n    description: \"HTTP headers to set when making requests to the MCP server.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable name identifying this MCP server.\" }),\n  url: Schema.String.annotate({ description: \"URL to the MCP server.\" }),\n}).annotate({ description: \"HTTP transport configuration for MCP.\" });\n\nexport type McpServerSse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly headers: ReadonlyArray<HttpHeader>;\n  readonly name: string;\n  readonly url: string;\n};\nexport const McpServerSse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  headers: Schema.Array(HttpHeader).annotate({\n    description: \"HTTP headers to set when making requests to the MCP server.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable name identifying this MCP server.\" }),\n  url: Schema.String.annotate({ description: \"URL to the MCP server.\" }),\n}).annotate({ description: \"SSE transport configuration for MCP.\" });\n\nexport type McpServerStdio = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly args: ReadonlyArray<string>;\n  readonly command: string;\n  readonly env: ReadonlyArray<EnvVariable>;\n  readonly name: string;\n};\nexport const McpServerStdio = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  args: Schema.Array(Schema.String).annotate({\n    description: \"Command-line arguments to pass to the MCP server.\",\n  }),\n  command: Schema.String.annotate({ description: \"Path to the MCP server executable.\" }),\n  env: Schema.Array(EnvVariable).annotate({\n    description: \"Environment variables to set when launching the MCP server.\",\n  }),\n  name: Schema.String.annotate({ description: \"Human-readable name identifying this MCP server.\" }),\n}).annotate({ description: \"Stdio transport configuration for MCP.\" });\n\nexport type ModelId = string;\nexport const ModelId = Schema.String.annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n});\n\nexport type MultiSelectItems =\n  | { readonly enum: ReadonlyArray<string>; readonly type: \"string\" }\n  | { readonly anyOf: ReadonlyArray<EnumOption> };\nexport const MultiSelectItems = Schema.Union([\n  Schema.Struct({\n    enum: Schema.Array(Schema.String).annotate({ description: \"Allowed enum values.\" }),\n    type: Schema.Literal(\"string\").annotate({\n      description: \"Items definition for untitled multi-select enum properties.\",\n    }),\n  }).annotate({\n    title: \"Untitled\",\n    description: \"Items definition for untitled multi-select enum properties.\",\n  }),\n  Schema.Struct({\n    anyOf: Schema.Array(EnumOption).annotate({ description: \"Titled enum options.\" }),\n  }).annotate({\n    title: \"Titled\",\n    description: \"Items definition for titled multi-select enum properties.\",\n  }),\n]).annotate({ description: \"Items for a multi-select (array) property schema.\" });\n\nexport type MultiSelectPropertySchema = {\n  readonly default?: ReadonlyArray<string> | null;\n  readonly description?: string | null;\n  readonly items:\n    | { readonly enum: ReadonlyArray<string>; readonly type: \"string\" }\n    | { readonly anyOf: ReadonlyArray<EnumOption> };\n  readonly maxItems?: number | null;\n  readonly minItems?: number | null;\n  readonly title?: string | null;\n};\nexport const MultiSelectPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({ description: \"Default selected values.\" }),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  items: Schema.Union([\n    Schema.Struct({\n      enum: Schema.Array(Schema.String).annotate({ description: \"Allowed enum values.\" }),\n      type: Schema.Literal(\"string\").annotate({\n        description: \"Items definition for untitled multi-select enum properties.\",\n      }),\n    }).annotate({\n      title: \"Untitled\",\n      description: \"Items definition for untitled multi-select enum properties.\",\n    }),\n    Schema.Struct({\n      anyOf: Schema.Array(EnumOption).annotate({ description: \"Titled enum options.\" }),\n    }).annotate({\n      title: \"Titled\",\n      description: \"Items definition for titled multi-select enum properties.\",\n    }),\n  ]).annotate({ description: \"Items for a multi-select (array) property schema.\" }),\n  maxItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Maximum number of items to select.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minItems: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Minimum number of items to select.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Schema for multi-select (array) properties in an elicitation form.\" });\n\nexport type NewSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly mcpServers: ReadonlyArray<McpServer>;\n};\nexport const NewSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({\n    description: \"The working directory for this session. Must be an absolute path.\",\n  }),\n  mcpServers: Schema.Array(McpServer).annotate({\n    description: \"List of MCP (Model Context Protocol) servers the agent should connect to.\",\n  }),\n}).annotate({\n  description:\n    \"Request parameters for creating a new session.\\n\\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)\",\n});\n\nexport type NewSessionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n  readonly models?: SessionModelState | null;\n  readonly modes?: SessionModeState | null;\n  readonly sessionId: string;\n};\nexport const NewSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(SessionConfigOption).annotate({\n        description: \"Initial session configuration options if supported by the Agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([SessionModelState, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n    }),\n  ),\n  modes: Schema.optionalKey(\n    Schema.Union([SessionModeState, Schema.Null]).annotate({\n      description:\n        \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Response from creating a new session.\\n\\nSee protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)\",\n});\n\nexport type NumberPropertySchema = {\n  readonly default?: number | null;\n  readonly description?: string | null;\n  readonly maximum?: number | null;\n  readonly minimum?: number | null;\n  readonly title?: string | null;\n};\nexport const NumberPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Default value.\", format: \"double\" }).check(\n        Schema.isFinite(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  maximum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Maximum value (inclusive).\", format: \"double\" }).check(\n        Schema.isFinite(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  minimum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Minimum value (inclusive).\", format: \"double\" }).check(\n        Schema.isFinite(),\n      ),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description: \"Schema for number (floating-point) properties in an elicitation form.\",\n});\n\nexport type PermissionOptionId = string;\nexport const PermissionOptionId = Schema.String.annotate({\n  description: \"Unique identifier for a permission option.\",\n});\n\nexport type PermissionOptionKind = \"allow_once\" | \"allow_always\" | \"reject_once\" | \"reject_always\";\nexport const PermissionOptionKind = Schema.Literals([\n  \"allow_once\",\n  \"allow_always\",\n  \"reject_once\",\n  \"reject_always\",\n]).annotate({\n  description:\n    \"The type of permission option being presented to the user.\\n\\nHelps clients choose appropriate icons and UI treatment.\",\n});\n\nexport type Plan = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly entries: ReadonlyArray<PlanEntry>;\n};\nexport const Plan = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  entries: Schema.Array(PlanEntry).annotate({\n    description:\n      \"The list of tasks to be accomplished.\\n\\nWhen updating a plan, the agent must send a complete list of all entries\\nwith their current status. The client replaces the entire plan with each update.\",\n  }),\n}).annotate({\n  description:\n    \"An execution plan for accomplishing complex tasks.\\n\\nPlans consist of multiple entries representing individual tasks or goals.\\nAgents report plans to clients to provide visibility into their execution strategy.\\nPlans can evolve during execution as the agent discovers new requirements or completes tasks.\\n\\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/agent-plan)\",\n});\n\nexport type PlanEntryPriority = \"high\" | \"medium\" | \"low\";\nexport const PlanEntryPriority = Schema.Literals([\"high\", \"medium\", \"low\"]).annotate({\n  description:\n    \"Priority levels for plan entries.\\n\\nUsed to indicate the relative importance or urgency of different\\ntasks in the execution plan.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n});\n\nexport type PlanEntryStatus = \"pending\" | \"in_progress\" | \"completed\";\nexport const PlanEntryStatus = Schema.Literals([\"pending\", \"in_progress\", \"completed\"]).annotate({\n  description:\n    \"Status of a plan entry in the execution flow.\\n\\nTracks the lifecycle of each task from planning through completion.\\nSee protocol docs: [Plan Entries](https://agentclientprotocol.com/protocol/agent-plan#plan-entries)\",\n});\n\nexport type PromptCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly audio?: boolean;\n  readonly embeddedContext?: boolean;\n  readonly image?: boolean;\n};\nexport const PromptCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  audio: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Agent supports [`ContentBlock::Audio`].\",\n      default: false,\n    }),\n  ),\n  embeddedContext: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description:\n        \"Agent supports embedded context in `session/prompt` requests.\\n\\nWhen enabled, the Client is allowed to include [`ContentBlock::Resource`]\\nin prompt requests for pieces of context that are referenced in the message.\",\n      default: false,\n    }),\n  ),\n  image: Schema.optionalKey(\n    Schema.Boolean.annotate({\n      description: \"Agent supports [`ContentBlock::Image`].\",\n      default: false,\n    }),\n  ),\n}).annotate({\n  description:\n    \"Prompt capabilities supported by the agent in `session/prompt` requests.\\n\\nBaseline agent functionality requires support for [`ContentBlock::Text`]\\nand [`ContentBlock::ResourceLink`] in prompt requests.\\n\\nOther variants must be explicitly opted in to.\\nCapabilities for different types of content in prompt requests.\\n\\nIndicates which content types beyond the baseline (text and resource links)\\nthe agent can process.\\n\\nSee protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/initialization#prompt-capabilities)\",\n});\n\nexport type PromptRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly messageId?: string | null;\n  readonly prompt: ReadonlyArray<ContentBlock>;\n  readonly sessionId: string;\n};\nexport const PromptRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  messageId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA client-generated unique identifier for this user message.\\n\\nIf provided, the Agent SHOULD echo this value as `userMessageId` in the\\n[`PromptResponse`] to confirm it was recorded.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  prompt: Schema.Array(ContentBlock).annotate({\n    description:\n      \"The blocks of content that compose the user's message.\\n\\nAs a baseline, the Agent MUST support [`ContentBlock::Text`] and [`ContentBlock::ResourceLink`],\\nwhile other variants are optionally enabled via [`PromptCapabilities`].\\n\\nThe Client MUST adapt its interface according to [`PromptCapabilities`].\\n\\nThe client MAY include referenced pieces of context as either\\n[`ContentBlock::Resource`] or [`ContentBlock::ResourceLink`].\\n\\nWhen available, [`ContentBlock::Resource`] is preferred\\nas it avoids extra round-trips and allows the message to include\\npieces of context from sources the agent may not have access to.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Request parameters for sending a user prompt to the agent.\\n\\nContains the user's message and any additional context.\\n\\nSee protocol docs: [User Message](https://agentclientprotocol.com/protocol/prompt-turn#1-user-message)\",\n});\n\nexport type PromptResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly stopReason: \"end_turn\" | \"max_tokens\" | \"max_turn_requests\" | \"refusal\" | \"cancelled\";\n  readonly usage?: Usage | null;\n  readonly userMessageId?: string | null;\n};\nexport const PromptResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  stopReason: Schema.Literals([\n    \"end_turn\",\n    \"max_tokens\",\n    \"max_turn_requests\",\n    \"refusal\",\n    \"cancelled\",\n  ]).annotate({\n    description:\n      \"Reasons why an agent stops processing a prompt turn.\\n\\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/prompt-turn#stop-reasons)\",\n  }),\n  usage: Schema.optionalKey(\n    Schema.Union([Usage, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nToken usage for this turn (optional).\",\n    }),\n  ),\n  userMessageId: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nThe acknowledged user message ID.\\n\\nIf the client provided a `messageId` in the [`PromptRequest`], the agent echoes it here\\nto confirm it was recorded. If the client did not provide one, the agent MAY assign one\\nand return it here. Absence of this field indicates the agent did not record a message ID.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Response from processing a user prompt.\\n\\nSee protocol docs: [Check for Completion](https://agentclientprotocol.com/protocol/prompt-turn#4-check-for-completion)\",\n});\n\nexport type ProtocolVersion = number;\nexport const ProtocolVersion = Schema.Number.annotate({\n  description:\n    \"Protocol version identifier.\\n\\nThis version is only bumped for breaking changes.\\nNon-breaking changes should be introduced via capabilities.\",\n  format: \"uint16\",\n})\n  .check(Schema.isInt())\n  .check(Schema.isGreaterThanOrEqualTo(0))\n  .check(Schema.isLessThanOrEqualTo(65535));\n\nexport type ReadTextFileRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly limit?: number | null;\n  readonly line?: number | null;\n  readonly path: string;\n  readonly sessionId: string;\n};\nexport const ReadTextFileRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  limit: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Maximum number of lines to read.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  line: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"Line number to start reading from (1-based).\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  path: Schema.String.annotate({ description: \"Absolute path to the file to read.\" }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Request to read content from a text file.\\n\\nOnly available if the client supports the `fs.readTextFile` capability.\",\n});\n\nexport type ReadTextFileResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content: string;\n};\nexport const ReadTextFileResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.String,\n}).annotate({ description: \"Response containing the contents of a text file.\" });\n\nexport type ReleaseTerminalRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly terminalId: string;\n};\nexport const ReleaseTerminalRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  terminalId: Schema.String.annotate({ description: \"The ID of the terminal to release.\" }),\n}).annotate({ description: \"Request to release a terminal and free its resources.\" });\n\nexport type ReleaseTerminalResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const ReleaseTerminalResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to terminal/release method\" });\n\nexport type RequestPermissionOutcome =\n  | { readonly outcome: \"cancelled\" }\n  | {\n      readonly outcome: \"selected\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly optionId: string;\n    };\nexport const RequestPermissionOutcome = Schema.Union(\n  [\n    Schema.Struct({ outcome: Schema.Literal(\"cancelled\") }).annotate({\n      description:\n        \"The prompt turn was cancelled before the user responded.\\n\\nWhen a client sends a `session/cancel` notification to cancel an ongoing\\nprompt turn, it MUST respond to all pending `session/request_permission`\\nrequests with this `Cancelled` outcome.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n    }),\n    Schema.Struct({\n      outcome: Schema.Literal(\"selected\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      optionId: Schema.String.annotate({\n        description: \"Unique identifier for a permission option.\",\n      }),\n    }).annotate({ description: \"The user selected one of the provided options.\" }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({ description: \"The outcome of a permission request.\" });\n\nexport type RequestPermissionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly options: ReadonlyArray<PermissionOption>;\n  readonly sessionId: string;\n  readonly toolCall: {\n    readonly _meta?: { readonly [x: string]: unknown } | null;\n    readonly content?: ReadonlyArray<ToolCallContent> | null;\n    readonly kind?: ToolKind | null;\n    readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n    readonly rawInput?: unknown;\n    readonly rawOutput?: unknown;\n    readonly status?: ToolCallStatus | null;\n    readonly title?: string | null;\n    readonly toolCallId: string;\n  };\n};\nexport const RequestPermissionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  options: Schema.Array(PermissionOption).annotate({\n    description: \"Available permission options for the user to choose from.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  toolCall: Schema.Struct({\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    content: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(ToolCallContent).annotate({ description: \"Replace the content collection.\" }),\n        Schema.Null,\n      ]),\n    ),\n    kind: Schema.optionalKey(\n      Schema.Union([ToolKind, Schema.Null]).annotate({ description: \"Update the tool kind.\" }),\n    ),\n    locations: Schema.optionalKey(\n      Schema.Union([\n        Schema.Array(ToolCallLocation).annotate({\n          description: \"Replace the locations collection.\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    rawInput: Schema.optionalKey(Schema.Unknown.annotate({ description: \"Update the raw input.\" })),\n    rawOutput: Schema.optionalKey(\n      Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n    ),\n    status: Schema.optionalKey(\n      Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n        description: \"Update the execution status.\",\n      }),\n    ),\n    title: Schema.optionalKey(\n      Schema.Union([\n        Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n        Schema.Null,\n      ]),\n    ),\n    toolCallId: Schema.String.annotate({\n      description: \"Unique identifier for a tool call within a session.\",\n    }),\n  }).annotate({\n    description:\n      \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n  }),\n}).annotate({\n  description:\n    \"Request for user permission to execute a tool call.\\n\\nSent when the agent needs authorization before performing a sensitive operation.\\n\\nSee protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/tool-calls#requesting-permission)\",\n});\n\nexport type RequestPermissionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly outcome:\n    | { readonly outcome: \"cancelled\" }\n    | {\n        readonly outcome: \"selected\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly optionId: string;\n      };\n};\nexport const RequestPermissionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  outcome: Schema.Union(\n    [\n      Schema.Struct({ outcome: Schema.Literal(\"cancelled\") }).annotate({\n        description:\n          \"The prompt turn was cancelled before the user responded.\\n\\nWhen a client sends a `session/cancel` notification to cancel an ongoing\\nprompt turn, it MUST respond to all pending `session/request_permission`\\nrequests with this `Cancelled` outcome.\\n\\nSee protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)\",\n      }),\n      Schema.Struct({\n        outcome: Schema.Literal(\"selected\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        optionId: Schema.String.annotate({\n          description: \"Unique identifier for a permission option.\",\n        }),\n      }).annotate({ description: \"The user selected one of the provided options.\" }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({ description: \"The outcome of a permission request.\" }),\n}).annotate({ description: \"Response to a permission request.\" });\n\nexport type ResourceLink = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly description?: string | null;\n  readonly mimeType?: string | null;\n  readonly name: string;\n  readonly size?: number | null;\n  readonly title?: string | null;\n  readonly uri: string;\n};\nexport const ResourceLink = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  name: Schema.String,\n  size: Schema.optionalKey(\n    Schema.Union([Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()), Schema.Null]),\n  ),\n  title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  uri: Schema.String,\n}).annotate({\n  description:\n    \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n});\n\nexport type ResumeSessionRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cwd: string;\n  readonly mcpServers?: ReadonlyArray<McpServer>;\n  readonly sessionId: string;\n};\nexport const ResumeSessionRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cwd: Schema.String.annotate({ description: \"The working directory for this session.\" }),\n  mcpServers: Schema.optionalKey(\n    Schema.Array(McpServer).annotate({\n      description: \"List of MCP servers to connect to for this session.\",\n    }),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for resuming an existing session.\\n\\nResumes an existing session without returning previous messages (unlike `session/load`).\\nThis is useful for agents that can resume sessions but don't implement full session loading.\\n\\nOnly available if the Agent supports the `session.resume` capability.\",\n});\n\nexport type ResumeSessionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions?: ReadonlyArray<SessionConfigOption> | null;\n  readonly models?: SessionModelState | null;\n  readonly modes?: SessionModeState | null;\n};\nexport const ResumeSessionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(SessionConfigOption).annotate({\n        description: \"Initial session configuration options if supported by the Agent.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  models: Schema.optionalKey(\n    Schema.Union([SessionModelState, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nInitial model state if supported by the Agent\",\n    }),\n  ),\n  modes: Schema.optionalKey(\n    Schema.Union([SessionModeState, Schema.Null]).annotate({\n      description:\n        \"Initial mode state if supported by the Agent\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse from resuming an existing session.\",\n});\n\nexport type SelectedPermissionOutcome = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly optionId: string;\n};\nexport const SelectedPermissionOutcome = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  optionId: Schema.String.annotate({ description: \"Unique identifier for a permission option.\" }),\n}).annotate({ description: \"The user selected one of the provided options.\" });\n\nexport type SessionCapabilities = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly close?: SessionCloseCapabilities | null;\n  readonly fork?: SessionForkCapabilities | null;\n  readonly list?: SessionListCapabilities | null;\n  readonly resume?: SessionResumeCapabilities | null;\n};\nexport const SessionCapabilities = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  close: Schema.optionalKey(\n    Schema.Union([SessionCloseCapabilities, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/close`.\",\n    }),\n  ),\n  fork: Schema.optionalKey(\n    Schema.Union([SessionForkCapabilities, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/fork`.\",\n    }),\n  ),\n  list: Schema.optionalKey(\n    Schema.Union([SessionListCapabilities, Schema.Null]).annotate({\n      description: \"Whether the agent supports `session/list`.\",\n    }),\n  ),\n  resume: Schema.optionalKey(\n    Schema.Union([SessionResumeCapabilities, Schema.Null]).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nWhether the agent supports `session/resume`.\",\n    }),\n  ),\n}).annotate({\n  description:\n    \"Session capabilities supported by the agent.\\n\\nAs a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.\\n\\nOptionally, they **MAY** support other session methods and notifications by specifying additional capabilities.\\n\\nNote: `session/load` is still handled by the top-level `load_session` capability. This will be unified in future versions of the protocol.\\n\\nSee protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/initialization#session-capabilities)\",\n});\n\nexport type SessionConfigBoolean = { readonly currentValue: boolean };\nexport const SessionConfigBoolean = Schema.Struct({\n  currentValue: Schema.Boolean.annotate({\n    description: \"The current value of the boolean option.\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA boolean on/off toggle session configuration option payload.\",\n});\n\nexport type SessionConfigGroupId = string;\nexport const SessionConfigGroupId = Schema.String.annotate({\n  description: \"Unique identifier for a session configuration option value group.\",\n});\n\nexport type SessionConfigId = string;\nexport const SessionConfigId = Schema.String.annotate({\n  description: \"Unique identifier for a session configuration option.\",\n});\n\nexport type SessionConfigSelect = {\n  readonly currentValue: string;\n  readonly options:\n    | ReadonlyArray<SessionConfigSelectOption>\n    | ReadonlyArray<SessionConfigSelectGroup>;\n};\nexport const SessionConfigSelect = Schema.Struct({\n  currentValue: Schema.String.annotate({\n    description: \"Unique identifier for a session configuration option value.\",\n  }),\n  options: Schema.Union([\n    Schema.Array(SessionConfigSelectOption).annotate({\n      title: \"Ungrouped\",\n      description: \"A flat list of options with no grouping.\",\n    }),\n    Schema.Array(SessionConfigSelectGroup).annotate({\n      title: \"Grouped\",\n      description: \"A list of options grouped under headers.\",\n    }),\n  ]).annotate({ description: \"Possible values for a session configuration option.\" }),\n}).annotate({\n  description: \"A single-value selector (dropdown) session configuration option payload.\",\n});\n\nexport type SessionConfigSelectOptions =\n  | ReadonlyArray<SessionConfigSelectOption>\n  | ReadonlyArray<SessionConfigSelectGroup>;\nexport const SessionConfigSelectOptions = Schema.Union([\n  Schema.Array(SessionConfigSelectOption).annotate({\n    title: \"Ungrouped\",\n    description: \"A flat list of options with no grouping.\",\n  }),\n  Schema.Array(SessionConfigSelectGroup).annotate({\n    title: \"Grouped\",\n    description: \"A list of options grouped under headers.\",\n  }),\n]).annotate({ description: \"Possible values for a session configuration option.\" });\n\nexport type SessionConfigValueId = string;\nexport const SessionConfigValueId = Schema.String.annotate({\n  description: \"Unique identifier for a session configuration option value.\",\n});\n\nexport type SessionId = string;\nexport const SessionId = Schema.String.annotate({\n  description:\n    \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n});\n\nexport type SessionInfoUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly title?: string | null;\n  readonly updatedAt?: string | null;\n};\nexport const SessionInfoUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"Human-readable title for the session. Set to null to clear.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  updatedAt: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"ISO 8601 timestamp of last activity. Set to null to clear.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"Update to session metadata. All fields are optional to support partial updates.\\n\\nAgents send this notification to update session information like title or custom metadata.\\nThis allows clients to display dynamic session names and track session state changes.\",\n});\n\nexport type SessionNotification = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly update:\n    | {\n        readonly sessionUpdate: \"user_message_chunk\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content:\n          | {\n              readonly type: \"text\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly text: string;\n            }\n          | {\n              readonly type: \"image\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n              readonly uri?: string | null;\n            }\n          | {\n              readonly type: \"audio\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n            }\n          | {\n              readonly type: \"resource_link\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly description?: string | null;\n              readonly mimeType?: string | null;\n              readonly name: string;\n              readonly size?: number | null;\n              readonly title?: string | null;\n              readonly uri: string;\n            }\n          | {\n              readonly type: \"resource\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly resource: EmbeddedResourceResource;\n            };\n        readonly messageId?: string | null;\n      }\n    | {\n        readonly sessionUpdate: \"agent_message_chunk\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content:\n          | {\n              readonly type: \"text\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly text: string;\n            }\n          | {\n              readonly type: \"image\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n              readonly uri?: string | null;\n            }\n          | {\n              readonly type: \"audio\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n            }\n          | {\n              readonly type: \"resource_link\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly description?: string | null;\n              readonly mimeType?: string | null;\n              readonly name: string;\n              readonly size?: number | null;\n              readonly title?: string | null;\n              readonly uri: string;\n            }\n          | {\n              readonly type: \"resource\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly resource: EmbeddedResourceResource;\n            };\n        readonly messageId?: string | null;\n      }\n    | {\n        readonly sessionUpdate: \"agent_thought_chunk\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content:\n          | {\n              readonly type: \"text\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly text: string;\n            }\n          | {\n              readonly type: \"image\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n              readonly uri?: string | null;\n            }\n          | {\n              readonly type: \"audio\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly data: string;\n              readonly mimeType: string;\n            }\n          | {\n              readonly type: \"resource_link\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly description?: string | null;\n              readonly mimeType?: string | null;\n              readonly name: string;\n              readonly size?: number | null;\n              readonly title?: string | null;\n              readonly uri: string;\n            }\n          | {\n              readonly type: \"resource\";\n              readonly _meta?: { readonly [x: string]: unknown } | null;\n              readonly annotations?: Annotations | null;\n              readonly resource: EmbeddedResourceResource;\n            };\n        readonly messageId?: string | null;\n      }\n    | {\n        readonly sessionUpdate: \"tool_call\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content?: ReadonlyArray<ToolCallContent>;\n        readonly kind?:\n          | \"read\"\n          | \"edit\"\n          | \"delete\"\n          | \"move\"\n          | \"search\"\n          | \"execute\"\n          | \"think\"\n          | \"fetch\"\n          | \"switch_mode\"\n          | \"other\";\n        readonly locations?: ReadonlyArray<ToolCallLocation>;\n        readonly rawInput?: unknown;\n        readonly rawOutput?: unknown;\n        readonly status?: \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n        readonly title: string;\n        readonly toolCallId: string;\n      }\n    | {\n        readonly sessionUpdate: \"tool_call_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly content?: ReadonlyArray<ToolCallContent> | null;\n        readonly kind?: ToolKind | null;\n        readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n        readonly rawInput?: unknown;\n        readonly rawOutput?: unknown;\n        readonly status?: ToolCallStatus | null;\n        readonly title?: string | null;\n        readonly toolCallId: string;\n      }\n    | {\n        readonly sessionUpdate: \"plan\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly entries: ReadonlyArray<PlanEntry>;\n      }\n    | {\n        readonly sessionUpdate: \"available_commands_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly availableCommands: ReadonlyArray<AvailableCommand>;\n      }\n    | {\n        readonly sessionUpdate: \"current_mode_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly currentModeId: string;\n      }\n    | {\n        readonly sessionUpdate: \"config_option_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly configOptions: ReadonlyArray<SessionConfigOption>;\n      }\n    | {\n        readonly sessionUpdate: \"session_info_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly title?: string | null;\n        readonly updatedAt?: string | null;\n      }\n    | {\n        readonly sessionUpdate: \"usage_update\";\n        readonly _meta?: { readonly [x: string]: unknown } | null;\n        readonly cost?: Cost | null;\n        readonly size: number;\n        readonly used: number;\n      };\n};\nexport const SessionNotification = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  update: Schema.Union(\n    [\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"user_message_chunk\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.Union(\n          [\n            Schema.Struct({\n              type: Schema.Literal(\"text\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              text: Schema.String,\n            }).annotate({ description: \"Text provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"image\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n              uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            }).annotate({ description: \"An image provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"audio\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n            }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource_link\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              name: Schema.String,\n              size: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                  Schema.Null,\n                ]),\n              ),\n              title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              uri: Schema.String,\n            }).annotate({\n              description:\n                \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n            }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              resource: EmbeddedResourceResource,\n            }).annotate({\n              description:\n                \"The contents of a resource, embedded into a prompt or tool call result.\",\n            }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({\n          description:\n            \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n        }),\n        messageId: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({ description: \"A streamed item of content\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"agent_message_chunk\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.Union(\n          [\n            Schema.Struct({\n              type: Schema.Literal(\"text\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              text: Schema.String,\n            }).annotate({ description: \"Text provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"image\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n              uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            }).annotate({ description: \"An image provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"audio\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n            }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource_link\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              name: Schema.String,\n              size: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                  Schema.Null,\n                ]),\n              ),\n              title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              uri: Schema.String,\n            }).annotate({\n              description:\n                \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n            }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              resource: EmbeddedResourceResource,\n            }).annotate({\n              description:\n                \"The contents of a resource, embedded into a prompt or tool call result.\",\n            }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({\n          description:\n            \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n        }),\n        messageId: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({ description: \"A streamed item of content\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"agent_thought_chunk\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.Union(\n          [\n            Schema.Struct({\n              type: Schema.Literal(\"text\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              text: Schema.String,\n            }).annotate({ description: \"Text provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"image\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n              uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            }).annotate({ description: \"An image provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"audio\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              data: Schema.String,\n              mimeType: Schema.String,\n            }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource_link\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              name: Schema.String,\n              size: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                  Schema.Null,\n                ]),\n              ),\n              title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n              uri: Schema.String,\n            }).annotate({\n              description:\n                \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n            }),\n            Schema.Struct({\n              type: Schema.Literal(\"resource\"),\n              _meta: Schema.optionalKey(\n                Schema.Union([\n                  Schema.Record(Schema.String, Schema.Unknown).annotate({\n                    description:\n                      \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                  }),\n                  Schema.Null,\n                ]),\n              ),\n              annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n              resource: EmbeddedResourceResource,\n            }).annotate({\n              description:\n                \"The contents of a resource, embedded into a prompt or tool call result.\",\n            }),\n          ],\n          { mode: \"oneOf\" },\n        ).annotate({\n          description:\n            \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n        }),\n        messageId: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description:\n                \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({ description: \"A streamed item of content\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"tool_call\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.optionalKey(\n          Schema.Array(ToolCallContent).annotate({\n            description: \"Content produced by the tool call.\",\n          }),\n        ),\n        kind: Schema.optionalKey(\n          Schema.Literals([\n            \"read\",\n            \"edit\",\n            \"delete\",\n            \"move\",\n            \"search\",\n            \"execute\",\n            \"think\",\n            \"fetch\",\n            \"switch_mode\",\n            \"other\",\n          ]).annotate({\n            description:\n              \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n          }),\n        ),\n        locations: Schema.optionalKey(\n          Schema.Array(ToolCallLocation).annotate({\n            description:\n              'File locations affected by this tool call.\\nEnables \"follow-along\" features in clients.',\n          }),\n        ),\n        rawInput: Schema.optionalKey(\n          Schema.Unknown.annotate({ description: \"Raw input parameters sent to the tool.\" }),\n        ),\n        rawOutput: Schema.optionalKey(\n          Schema.Unknown.annotate({ description: \"Raw output returned by the tool.\" }),\n        ),\n        status: Schema.optionalKey(\n          Schema.Literals([\"pending\", \"in_progress\", \"completed\", \"failed\"]).annotate({\n            description:\n              \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n          }),\n        ),\n        title: Schema.String.annotate({\n          description: \"Human-readable title describing what the tool is doing.\",\n        }),\n        toolCallId: Schema.String.annotate({\n          description: \"Unique identifier for a tool call within a session.\",\n        }),\n      }).annotate({\n        description:\n          \"Represents a tool call that the language model has requested.\\n\\nTool calls are actions that the agent executes on behalf of the language model,\\nsuch as reading files, executing code, or fetching data from external sources.\\n\\nSee protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/tool-calls)\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"tool_call_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        content: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(ToolCallContent).annotate({\n              description: \"Replace the content collection.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        kind: Schema.optionalKey(\n          Schema.Union([ToolKind, Schema.Null]).annotate({ description: \"Update the tool kind.\" }),\n        ),\n        locations: Schema.optionalKey(\n          Schema.Union([\n            Schema.Array(ToolCallLocation).annotate({\n              description: \"Replace the locations collection.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        rawInput: Schema.optionalKey(\n          Schema.Unknown.annotate({ description: \"Update the raw input.\" }),\n        ),\n        rawOutput: Schema.optionalKey(\n          Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n        ),\n        status: Schema.optionalKey(\n          Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n            description: \"Update the execution status.\",\n          }),\n        ),\n        title: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n            Schema.Null,\n          ]),\n        ),\n        toolCallId: Schema.String.annotate({\n          description: \"Unique identifier for a tool call within a session.\",\n        }),\n      }).annotate({\n        description:\n          \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"plan\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        entries: Schema.Array(PlanEntry).annotate({\n          description:\n            \"The list of tasks to be accomplished.\\n\\nWhen updating a plan, the agent must send a complete list of all entries\\nwith their current status. The client replaces the entire plan with each update.\",\n        }),\n      }).annotate({\n        description:\n          \"An execution plan for accomplishing complex tasks.\\n\\nPlans consist of multiple entries representing individual tasks or goals.\\nAgents report plans to clients to provide visibility into their execution strategy.\\nPlans can evolve during execution as the agent discovers new requirements or completes tasks.\\n\\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/agent-plan)\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"available_commands_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        availableCommands: Schema.Array(AvailableCommand).annotate({\n          description: \"Commands the agent can execute\",\n        }),\n      }).annotate({ description: \"Available commands are ready or have changed\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"current_mode_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        currentModeId: Schema.String.annotate({\n          description: \"Unique identifier for a Session Mode.\",\n        }),\n      }).annotate({\n        description:\n          \"The current mode of the session has changed\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"config_option_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        configOptions: Schema.Array(SessionConfigOption).annotate({\n          description: \"The full set of configuration options and their current values.\",\n        }),\n      }).annotate({ description: \"Session configuration options have been updated.\" }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"session_info_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        title: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description: \"Human-readable title for the session. Set to null to clear.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        updatedAt: Schema.optionalKey(\n          Schema.Union([\n            Schema.String.annotate({\n              description: \"ISO 8601 timestamp of last activity. Set to null to clear.\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n      }).annotate({\n        description:\n          \"Update to session metadata. All fields are optional to support partial updates.\\n\\nAgents send this notification to update session information like title or custom metadata.\\nThis allows clients to display dynamic session names and track session state changes.\",\n      }),\n      Schema.Struct({\n        sessionUpdate: Schema.Literal(\"usage_update\"),\n        _meta: Schema.optionalKey(\n          Schema.Union([\n            Schema.Record(Schema.String, Schema.Unknown).annotate({\n              description:\n                \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n            }),\n            Schema.Null,\n          ]),\n        ),\n        cost: Schema.optionalKey(\n          Schema.Union([Cost, Schema.Null]).annotate({\n            description: \"Cumulative session cost (optional).\",\n          }),\n        ),\n        size: Schema.Number.annotate({\n          description: \"Total context window size in tokens.\",\n          format: \"uint64\",\n        })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n        used: Schema.Number.annotate({\n          description: \"Tokens currently in context.\",\n          format: \"uint64\",\n        })\n          .check(Schema.isInt())\n          .check(Schema.isGreaterThanOrEqualTo(0)),\n      }).annotate({\n        description:\n          \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nContext window and cost update for a session.\",\n      }),\n    ],\n    { mode: \"oneOf\" },\n  ).annotate({\n    description:\n      \"Different types of updates that can be sent during session processing.\\n\\nThese updates provide real-time feedback about the agent's progress.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n  }),\n}).annotate({\n  description:\n    \"Notification containing a session update from the agent.\\n\\nUsed to stream real-time progress and results during prompt processing.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n});\n\nexport type SessionUpdate =\n  | {\n      readonly sessionUpdate: \"user_message_chunk\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content:\n        | {\n            readonly type: \"text\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly text: string;\n          }\n        | {\n            readonly type: \"image\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n            readonly uri?: string | null;\n          }\n        | {\n            readonly type: \"audio\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n          }\n        | {\n            readonly type: \"resource_link\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly description?: string | null;\n            readonly mimeType?: string | null;\n            readonly name: string;\n            readonly size?: number | null;\n            readonly title?: string | null;\n            readonly uri: string;\n          }\n        | {\n            readonly type: \"resource\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly resource: EmbeddedResourceResource;\n          };\n      readonly messageId?: string | null;\n    }\n  | {\n      readonly sessionUpdate: \"agent_message_chunk\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content:\n        | {\n            readonly type: \"text\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly text: string;\n          }\n        | {\n            readonly type: \"image\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n            readonly uri?: string | null;\n          }\n        | {\n            readonly type: \"audio\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n          }\n        | {\n            readonly type: \"resource_link\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly description?: string | null;\n            readonly mimeType?: string | null;\n            readonly name: string;\n            readonly size?: number | null;\n            readonly title?: string | null;\n            readonly uri: string;\n          }\n        | {\n            readonly type: \"resource\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly resource: EmbeddedResourceResource;\n          };\n      readonly messageId?: string | null;\n    }\n  | {\n      readonly sessionUpdate: \"agent_thought_chunk\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content:\n        | {\n            readonly type: \"text\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly text: string;\n          }\n        | {\n            readonly type: \"image\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n            readonly uri?: string | null;\n          }\n        | {\n            readonly type: \"audio\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly data: string;\n            readonly mimeType: string;\n          }\n        | {\n            readonly type: \"resource_link\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly description?: string | null;\n            readonly mimeType?: string | null;\n            readonly name: string;\n            readonly size?: number | null;\n            readonly title?: string | null;\n            readonly uri: string;\n          }\n        | {\n            readonly type: \"resource\";\n            readonly _meta?: { readonly [x: string]: unknown } | null;\n            readonly annotations?: Annotations | null;\n            readonly resource: EmbeddedResourceResource;\n          };\n      readonly messageId?: string | null;\n    }\n  | {\n      readonly sessionUpdate: \"tool_call\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content?: ReadonlyArray<ToolCallContent>;\n      readonly kind?:\n        | \"read\"\n        | \"edit\"\n        | \"delete\"\n        | \"move\"\n        | \"search\"\n        | \"execute\"\n        | \"think\"\n        | \"fetch\"\n        | \"switch_mode\"\n        | \"other\";\n      readonly locations?: ReadonlyArray<ToolCallLocation>;\n      readonly rawInput?: unknown;\n      readonly rawOutput?: unknown;\n      readonly status?: \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n      readonly title: string;\n      readonly toolCallId: string;\n    }\n  | {\n      readonly sessionUpdate: \"tool_call_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly content?: ReadonlyArray<ToolCallContent> | null;\n      readonly kind?: ToolKind | null;\n      readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n      readonly rawInput?: unknown;\n      readonly rawOutput?: unknown;\n      readonly status?: ToolCallStatus | null;\n      readonly title?: string | null;\n      readonly toolCallId: string;\n    }\n  | {\n      readonly sessionUpdate: \"plan\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly entries: ReadonlyArray<PlanEntry>;\n    }\n  | {\n      readonly sessionUpdate: \"available_commands_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly availableCommands: ReadonlyArray<AvailableCommand>;\n    }\n  | {\n      readonly sessionUpdate: \"current_mode_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly currentModeId: string;\n    }\n  | {\n      readonly sessionUpdate: \"config_option_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly configOptions: ReadonlyArray<SessionConfigOption>;\n    }\n  | {\n      readonly sessionUpdate: \"session_info_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly title?: string | null;\n      readonly updatedAt?: string | null;\n    }\n  | {\n      readonly sessionUpdate: \"usage_update\";\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly cost?: Cost | null;\n      readonly size: number;\n      readonly used: number;\n    };\nexport const SessionUpdate = Schema.Union(\n  [\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"user_message_chunk\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.Union(\n        [\n          Schema.Struct({\n            type: Schema.Literal(\"text\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            text: Schema.String,\n          }).annotate({ description: \"Text provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"image\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n            uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n          }).annotate({ description: \"An image provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"audio\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n          }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource_link\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            name: Schema.String,\n            size: Schema.optionalKey(\n              Schema.Union([\n                Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                Schema.Null,\n              ]),\n            ),\n            title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            uri: Schema.String,\n          }).annotate({\n            description:\n              \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n          }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            resource: EmbeddedResourceResource,\n          }).annotate({\n            description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n          }),\n        ],\n        { mode: \"oneOf\" },\n      ).annotate({\n        description:\n          \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n      }),\n      messageId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"A streamed item of content\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"agent_message_chunk\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.Union(\n        [\n          Schema.Struct({\n            type: Schema.Literal(\"text\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            text: Schema.String,\n          }).annotate({ description: \"Text provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"image\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n            uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n          }).annotate({ description: \"An image provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"audio\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n          }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource_link\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            name: Schema.String,\n            size: Schema.optionalKey(\n              Schema.Union([\n                Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                Schema.Null,\n              ]),\n            ),\n            title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            uri: Schema.String,\n          }).annotate({\n            description:\n              \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n          }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            resource: EmbeddedResourceResource,\n          }).annotate({\n            description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n          }),\n        ],\n        { mode: \"oneOf\" },\n      ).annotate({\n        description:\n          \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n      }),\n      messageId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"A streamed item of content\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"agent_thought_chunk\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.Union(\n        [\n          Schema.Struct({\n            type: Schema.Literal(\"text\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            text: Schema.String,\n          }).annotate({ description: \"Text provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"image\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n            uri: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n          }).annotate({ description: \"An image provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"audio\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            data: Schema.String,\n            mimeType: Schema.String,\n          }).annotate({ description: \"Audio provided to or from an LLM.\" }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource_link\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            description: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            name: Schema.String,\n            size: Schema.optionalKey(\n              Schema.Union([\n                Schema.Number.annotate({ format: \"int64\" }).check(Schema.isInt()),\n                Schema.Null,\n              ]),\n            ),\n            title: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n            uri: Schema.String,\n          }).annotate({\n            description:\n              \"A resource that the server is capable of reading, included in a prompt or tool call result.\",\n          }),\n          Schema.Struct({\n            type: Schema.Literal(\"resource\"),\n            _meta: Schema.optionalKey(\n              Schema.Union([\n                Schema.Record(Schema.String, Schema.Unknown).annotate({\n                  description:\n                    \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n                }),\n                Schema.Null,\n              ]),\n            ),\n            annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n            resource: EmbeddedResourceResource,\n          }).annotate({\n            description: \"The contents of a resource, embedded into a prompt or tool call result.\",\n          }),\n        ],\n        { mode: \"oneOf\" },\n      ).annotate({\n        description:\n          \"Content blocks represent displayable information in the Agent Client Protocol.\\n\\nThey provide a structured way to handle various types of user-facing content—whether\\nit's text from language models, images for analysis, or embedded resources for context.\\n\\nContent blocks appear in:\\n- User prompts sent via `session/prompt`\\n- Language model output streamed through `session/update` notifications\\n- Progress updates and results from tool calls\\n\\nThis structure is compatible with the Model Context Protocol (MCP), enabling\\nagents to seamlessly forward content from MCP tool outputs without transformation.\\n\\nSee protocol docs: [Content](https://agentclientprotocol.com/protocol/content)\",\n      }),\n      messageId: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description:\n              \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for the message this chunk belongs to.\\n\\nAll chunks belonging to the same message share the same `messageId`.\\nA change in `messageId` indicates a new message has started.\\nBoth clients and agents MUST use UUID format for message IDs.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({ description: \"A streamed item of content\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"tool_call\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.optionalKey(\n        Schema.Array(ToolCallContent).annotate({\n          description: \"Content produced by the tool call.\",\n        }),\n      ),\n      kind: Schema.optionalKey(\n        Schema.Literals([\n          \"read\",\n          \"edit\",\n          \"delete\",\n          \"move\",\n          \"search\",\n          \"execute\",\n          \"think\",\n          \"fetch\",\n          \"switch_mode\",\n          \"other\",\n        ]).annotate({\n          description:\n            \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n        }),\n      ),\n      locations: Schema.optionalKey(\n        Schema.Array(ToolCallLocation).annotate({\n          description:\n            'File locations affected by this tool call.\\nEnables \"follow-along\" features in clients.',\n        }),\n      ),\n      rawInput: Schema.optionalKey(\n        Schema.Unknown.annotate({ description: \"Raw input parameters sent to the tool.\" }),\n      ),\n      rawOutput: Schema.optionalKey(\n        Schema.Unknown.annotate({ description: \"Raw output returned by the tool.\" }),\n      ),\n      status: Schema.optionalKey(\n        Schema.Literals([\"pending\", \"in_progress\", \"completed\", \"failed\"]).annotate({\n          description:\n            \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n        }),\n      ),\n      title: Schema.String.annotate({\n        description: \"Human-readable title describing what the tool is doing.\",\n      }),\n      toolCallId: Schema.String.annotate({\n        description: \"Unique identifier for a tool call within a session.\",\n      }),\n    }).annotate({\n      description:\n        \"Represents a tool call that the language model has requested.\\n\\nTool calls are actions that the agent executes on behalf of the language model,\\nsuch as reading files, executing code, or fetching data from external sources.\\n\\nSee protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/tool-calls)\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"tool_call_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      content: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(ToolCallContent).annotate({\n            description: \"Replace the content collection.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      kind: Schema.optionalKey(\n        Schema.Union([ToolKind, Schema.Null]).annotate({ description: \"Update the tool kind.\" }),\n      ),\n      locations: Schema.optionalKey(\n        Schema.Union([\n          Schema.Array(ToolCallLocation).annotate({\n            description: \"Replace the locations collection.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      rawInput: Schema.optionalKey(\n        Schema.Unknown.annotate({ description: \"Update the raw input.\" }),\n      ),\n      rawOutput: Schema.optionalKey(\n        Schema.Unknown.annotate({ description: \"Update the raw output.\" }),\n      ),\n      status: Schema.optionalKey(\n        Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n          description: \"Update the execution status.\",\n        }),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n          Schema.Null,\n        ]),\n      ),\n      toolCallId: Schema.String.annotate({\n        description: \"Unique identifier for a tool call within a session.\",\n      }),\n    }).annotate({\n      description:\n        \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"plan\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      entries: Schema.Array(PlanEntry).annotate({\n        description:\n          \"The list of tasks to be accomplished.\\n\\nWhen updating a plan, the agent must send a complete list of all entries\\nwith their current status. The client replaces the entire plan with each update.\",\n      }),\n    }).annotate({\n      description:\n        \"An execution plan for accomplishing complex tasks.\\n\\nPlans consist of multiple entries representing individual tasks or goals.\\nAgents report plans to clients to provide visibility into their execution strategy.\\nPlans can evolve during execution as the agent discovers new requirements or completes tasks.\\n\\nSee protocol docs: [Agent Plan](https://agentclientprotocol.com/protocol/agent-plan)\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"available_commands_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      availableCommands: Schema.Array(AvailableCommand).annotate({\n        description: \"Commands the agent can execute\",\n      }),\n    }).annotate({ description: \"Available commands are ready or have changed\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"current_mode_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      currentModeId: Schema.String.annotate({\n        description: \"Unique identifier for a Session Mode.\",\n      }),\n    }).annotate({\n      description:\n        \"The current mode of the session has changed\\n\\nSee protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"config_option_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      configOptions: Schema.Array(SessionConfigOption).annotate({\n        description: \"The full set of configuration options and their current values.\",\n      }),\n    }).annotate({ description: \"Session configuration options have been updated.\" }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"session_info_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      title: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"Human-readable title for the session. Set to null to clear.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      updatedAt: Schema.optionalKey(\n        Schema.Union([\n          Schema.String.annotate({\n            description: \"ISO 8601 timestamp of last activity. Set to null to clear.\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n    }).annotate({\n      description:\n        \"Update to session metadata. All fields are optional to support partial updates.\\n\\nAgents send this notification to update session information like title or custom metadata.\\nThis allows clients to display dynamic session names and track session state changes.\",\n    }),\n    Schema.Struct({\n      sessionUpdate: Schema.Literal(\"usage_update\"),\n      _meta: Schema.optionalKey(\n        Schema.Union([\n          Schema.Record(Schema.String, Schema.Unknown).annotate({\n            description:\n              \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n          }),\n          Schema.Null,\n        ]),\n      ),\n      cost: Schema.optionalKey(\n        Schema.Union([Cost, Schema.Null]).annotate({\n          description: \"Cumulative session cost (optional).\",\n        }),\n      ),\n      size: Schema.Number.annotate({\n        description: \"Total context window size in tokens.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      used: Schema.Number.annotate({\n        description: \"Tokens currently in context.\",\n        format: \"uint64\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n    }).annotate({\n      description:\n        \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nContext window and cost update for a session.\",\n    }),\n  ],\n  { mode: \"oneOf\" },\n).annotate({\n  description:\n    \"Different types of updates that can be sent during session processing.\\n\\nThese updates provide real-time feedback about the agent's progress.\\n\\nSee protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)\",\n});\n\nexport type SetSessionConfigOptionRequest =\n  | {\n      readonly type: \"boolean\";\n      readonly value: boolean;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly configId: string;\n      readonly sessionId: string;\n    }\n  | {\n      readonly value: string;\n      readonly _meta?: { readonly [x: string]: unknown } | null;\n      readonly configId: string;\n      readonly sessionId: string;\n    };\nexport const SetSessionConfigOptionRequest = Schema.Union([\n  Schema.Struct({\n    type: Schema.Literal(\"boolean\"),\n    value: Schema.Boolean.annotate({ description: \"The boolean value.\" }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    configId: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option.\",\n    }),\n    sessionId: Schema.String.annotate({\n      description:\n        \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n    }),\n  }).annotate({ description: \"Request parameters for setting a session configuration option.\" }),\n  Schema.Struct({\n    value: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option value.\",\n    }),\n    _meta: Schema.optionalKey(\n      Schema.Union([\n        Schema.Record(Schema.String, Schema.Unknown).annotate({\n          description:\n            \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n        }),\n        Schema.Null,\n      ]),\n    ),\n    configId: Schema.String.annotate({\n      description: \"Unique identifier for a session configuration option.\",\n    }),\n    sessionId: Schema.String.annotate({\n      description:\n        \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n    }),\n  }).annotate({\n    title: \"value_id\",\n    description: \"Request parameters for setting a session configuration option.\",\n  }),\n]);\n\nexport type SetSessionConfigOptionResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly configOptions: ReadonlyArray<SessionConfigOption>;\n};\nexport const SetSessionConfigOptionResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  configOptions: Schema.Array(SessionConfigOption).annotate({\n    description: \"The full set of configuration options and their current values.\",\n  }),\n}).annotate({ description: \"Response to `session/set_config_option` method.\" });\n\nexport type SetSessionModelRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly modelId: string;\n  readonly sessionId: string;\n};\nexport const SetSessionModelRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modelId: Schema.String.annotate({\n    description:\n      \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nA unique identifier for a model.\",\n  }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nRequest parameters for setting a session model.\",\n});\n\nexport type SetSessionModelResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const SetSessionModelResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nResponse to `session/set_model` method.\",\n});\n\nexport type SetSessionModeRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly modeId: string;\n  readonly sessionId: string;\n};\nexport const SetSessionModeRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  modeId: Schema.String.annotate({ description: \"Unique identifier for a Session Mode.\" }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({ description: \"Request parameters for setting a session mode.\" });\n\nexport type SetSessionModeResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const SetSessionModeResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to `session/set_mode` method.\" });\n\nexport type StopReason = \"end_turn\" | \"max_tokens\" | \"max_turn_requests\" | \"refusal\" | \"cancelled\";\nexport const StopReason = Schema.Literals([\n  \"end_turn\",\n  \"max_tokens\",\n  \"max_turn_requests\",\n  \"refusal\",\n  \"cancelled\",\n]).annotate({\n  description:\n    \"Reasons why an agent stops processing a prompt turn.\\n\\nSee protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/prompt-turn#stop-reasons)\",\n});\n\nexport type StringPropertySchema = {\n  readonly default?: string | null;\n  readonly description?: string | null;\n  readonly enum?: ReadonlyArray<string> | null;\n  readonly format?: StringFormat | null;\n  readonly maxLength?: number | null;\n  readonly minLength?: number | null;\n  readonly oneOf?: ReadonlyArray<EnumOption> | null;\n  readonly pattern?: string | null;\n  readonly title?: string | null;\n};\nexport const StringPropertySchema = Schema.Struct({\n  default: Schema.optionalKey(\n    Schema.Union([Schema.String.annotate({ description: \"Default value.\" }), Schema.Null]),\n  ),\n  description: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Human-readable description.\" }),\n      Schema.Null,\n    ]),\n  ),\n  enum: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(Schema.String).annotate({\n        description: \"Enum values for untitled single-select enums.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  format: Schema.optionalKey(\n    Schema.Union([StringFormat, Schema.Null]).annotate({ description: \"String format.\" }),\n  ),\n  maxLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Maximum string length.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  minLength: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({ description: \"Minimum string length.\", format: \"uint32\" })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  oneOf: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(EnumOption).annotate({\n        description: \"Titled enum options for titled single-select enums.\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  pattern: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Pattern the string must match.\" }),\n      Schema.Null,\n    ]),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Optional title for the property.\" }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({\n  description:\n    'Schema for string properties in an elicitation form.\\n\\nWhen `enum` or `oneOf` is set, this represents a single-select enum\\nwith `\"type\": \"string\"`.',\n});\n\nexport type Terminal = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly terminalId: string;\n};\nexport const Terminal = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  terminalId: Schema.String,\n}).annotate({\n  description:\n    \"Embed a terminal created with `terminal/create` by its id.\\n\\nThe terminal must be added before calling `terminal/release`.\\n\\nSee protocol docs: [Terminal](https://agentclientprotocol.com/protocol/terminals)\",\n});\n\nexport type TerminalOutputRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly terminalId: string;\n};\nexport const TerminalOutputRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  terminalId: Schema.String.annotate({ description: \"The ID of the terminal to get output from.\" }),\n}).annotate({ description: \"Request to get the current output and status of a terminal.\" });\n\nexport type TerminalOutputResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly exitStatus?: TerminalExitStatus | null;\n  readonly output: string;\n  readonly truncated: boolean;\n};\nexport const TerminalOutputResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  exitStatus: Schema.optionalKey(\n    Schema.Union([TerminalExitStatus, Schema.Null]).annotate({\n      description: \"Exit status if the command has completed.\",\n    }),\n  ),\n  output: Schema.String.annotate({ description: \"The terminal output captured so far.\" }),\n  truncated: Schema.Boolean.annotate({\n    description: \"Whether the output was truncated due to byte limits.\",\n  }),\n}).annotate({ description: \"Response containing the terminal output and exit status.\" });\n\nexport type TextContent = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly annotations?: Annotations | null;\n  readonly text: string;\n};\nexport const TextContent = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  annotations: Schema.optionalKey(Schema.Union([Annotations, Schema.Null])),\n  text: Schema.String,\n}).annotate({ description: \"Text provided to or from an LLM.\" });\n\nexport type TextResourceContents = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly mimeType?: string | null;\n  readonly text: string;\n  readonly uri: string;\n};\nexport const TextResourceContents = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  mimeType: Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])),\n  text: Schema.String,\n  uri: Schema.String,\n}).annotate({ description: \"Text-based resource contents.\" });\n\nexport type TitledMultiSelectItems = { readonly anyOf: ReadonlyArray<EnumOption> };\nexport const TitledMultiSelectItems = Schema.Struct({\n  anyOf: Schema.Array(EnumOption).annotate({ description: \"Titled enum options.\" }),\n}).annotate({ description: \"Items definition for titled multi-select enum properties.\" });\n\nexport type ToolCall = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content?: ReadonlyArray<ToolCallContent>;\n  readonly kind?:\n    | \"read\"\n    | \"edit\"\n    | \"delete\"\n    | \"move\"\n    | \"search\"\n    | \"execute\"\n    | \"think\"\n    | \"fetch\"\n    | \"switch_mode\"\n    | \"other\";\n  readonly locations?: ReadonlyArray<ToolCallLocation>;\n  readonly rawInput?: unknown;\n  readonly rawOutput?: unknown;\n  readonly status?: \"pending\" | \"in_progress\" | \"completed\" | \"failed\";\n  readonly title: string;\n  readonly toolCallId: string;\n};\nexport const ToolCall = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.optionalKey(\n    Schema.Array(ToolCallContent).annotate({ description: \"Content produced by the tool call.\" }),\n  ),\n  kind: Schema.optionalKey(\n    Schema.Literals([\n      \"read\",\n      \"edit\",\n      \"delete\",\n      \"move\",\n      \"search\",\n      \"execute\",\n      \"think\",\n      \"fetch\",\n      \"switch_mode\",\n      \"other\",\n    ]).annotate({\n      description:\n        \"Categories of tools that can be invoked.\\n\\nTool kinds help clients choose appropriate icons and optimize how they\\ndisplay tool execution progress.\\n\\nSee protocol docs: [Creating](https://agentclientprotocol.com/protocol/tool-calls#creating)\",\n    }),\n  ),\n  locations: Schema.optionalKey(\n    Schema.Array(ToolCallLocation).annotate({\n      description:\n        'File locations affected by this tool call.\\nEnables \"follow-along\" features in clients.',\n    }),\n  ),\n  rawInput: Schema.optionalKey(\n    Schema.Unknown.annotate({ description: \"Raw input parameters sent to the tool.\" }),\n  ),\n  rawOutput: Schema.optionalKey(\n    Schema.Unknown.annotate({ description: \"Raw output returned by the tool.\" }),\n  ),\n  status: Schema.optionalKey(\n    Schema.Literals([\"pending\", \"in_progress\", \"completed\", \"failed\"]).annotate({\n      description:\n        \"Execution status of a tool call.\\n\\nTool calls progress through different statuses during their lifecycle.\\n\\nSee protocol docs: [Status](https://agentclientprotocol.com/protocol/tool-calls#status)\",\n    }),\n  ),\n  title: Schema.String.annotate({\n    description: \"Human-readable title describing what the tool is doing.\",\n  }),\n  toolCallId: Schema.String.annotate({\n    description: \"Unique identifier for a tool call within a session.\",\n  }),\n}).annotate({\n  description:\n    \"Represents a tool call that the language model has requested.\\n\\nTool calls are actions that the agent executes on behalf of the language model,\\nsuch as reading files, executing code, or fetching data from external sources.\\n\\nSee protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/tool-calls)\",\n});\n\nexport type ToolCallId = string;\nexport const ToolCallId = Schema.String.annotate({\n  description: \"Unique identifier for a tool call within a session.\",\n});\n\nexport type ToolCallUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content?: ReadonlyArray<ToolCallContent> | null;\n  readonly kind?: ToolKind | null;\n  readonly locations?: ReadonlyArray<ToolCallLocation> | null;\n  readonly rawInput?: unknown;\n  readonly rawOutput?: unknown;\n  readonly status?: ToolCallStatus | null;\n  readonly title?: string | null;\n  readonly toolCallId: string;\n};\nexport const ToolCallUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ToolCallContent).annotate({ description: \"Replace the content collection.\" }),\n      Schema.Null,\n    ]),\n  ),\n  kind: Schema.optionalKey(\n    Schema.Union([ToolKind, Schema.Null]).annotate({ description: \"Update the tool kind.\" }),\n  ),\n  locations: Schema.optionalKey(\n    Schema.Union([\n      Schema.Array(ToolCallLocation).annotate({ description: \"Replace the locations collection.\" }),\n      Schema.Null,\n    ]),\n  ),\n  rawInput: Schema.optionalKey(Schema.Unknown.annotate({ description: \"Update the raw input.\" })),\n  rawOutput: Schema.optionalKey(Schema.Unknown.annotate({ description: \"Update the raw output.\" })),\n  status: Schema.optionalKey(\n    Schema.Union([ToolCallStatus, Schema.Null]).annotate({\n      description: \"Update the execution status.\",\n    }),\n  ),\n  title: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({ description: \"Update the human-readable title.\" }),\n      Schema.Null,\n    ]),\n  ),\n  toolCallId: Schema.String.annotate({\n    description: \"Unique identifier for a tool call within a session.\",\n  }),\n}).annotate({\n  description:\n    \"An update to an existing tool call.\\n\\nUsed to report progress and results as tools execute. All fields except\\nthe tool call ID are optional - only changed fields need to be included.\\n\\nSee protocol docs: [Updating](https://agentclientprotocol.com/protocol/tool-calls#updating)\",\n});\n\nexport type UnstructuredCommandInput = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly hint: string;\n};\nexport const UnstructuredCommandInput = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  hint: Schema.String.annotate({\n    description: \"A hint to display when the input hasn't been provided yet\",\n  }),\n}).annotate({\n  description: \"All text that was typed after the command name is provided as input.\",\n});\n\nexport type UntitledMultiSelectItems = {\n  readonly enum: ReadonlyArray<string>;\n  readonly type: \"string\";\n};\nexport const UntitledMultiSelectItems = Schema.Struct({\n  enum: Schema.Array(Schema.String).annotate({ description: \"Allowed enum values.\" }),\n  type: Schema.Literal(\"string\").annotate({\n    description: \"Items definition for untitled multi-select enum properties.\",\n  }),\n}).annotate({ description: \"Items definition for untitled multi-select enum properties.\" });\n\nexport type UsageUpdate = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly cost?: Cost | null;\n  readonly size: number;\n  readonly used: number;\n};\nexport const UsageUpdate = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  cost: Schema.optionalKey(\n    Schema.Union([Cost, Schema.Null]).annotate({\n      description: \"Cumulative session cost (optional).\",\n    }),\n  ),\n  size: Schema.Number.annotate({\n    description: \"Total context window size in tokens.\",\n    format: \"uint64\",\n  })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n  used: Schema.Number.annotate({ description: \"Tokens currently in context.\", format: \"uint64\" })\n    .check(Schema.isInt())\n    .check(Schema.isGreaterThanOrEqualTo(0)),\n}).annotate({\n  description:\n    \"**UNSTABLE**\\n\\nThis capability is not part of the spec yet, and may be removed or changed at any point.\\n\\nContext window and cost update for a session.\",\n});\n\nexport type WaitForTerminalExitRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly sessionId: string;\n  readonly terminalId: string;\n};\nexport const WaitForTerminalExitRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n  terminalId: Schema.String.annotate({ description: \"The ID of the terminal to wait for.\" }),\n}).annotate({ description: \"Request to wait for a terminal command to exit.\" });\n\nexport type WaitForTerminalExitResponse = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly exitCode?: number | null;\n  readonly signal?: string | null;\n};\nexport const WaitForTerminalExitResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  exitCode: Schema.optionalKey(\n    Schema.Union([\n      Schema.Number.annotate({\n        description: \"The process exit code (may be null if terminated by signal).\",\n        format: \"uint32\",\n      })\n        .check(Schema.isInt())\n        .check(Schema.isGreaterThanOrEqualTo(0)),\n      Schema.Null,\n    ]),\n  ),\n  signal: Schema.optionalKey(\n    Schema.Union([\n      Schema.String.annotate({\n        description: \"The signal that terminated the process (may be null if exited normally).\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response containing the exit status of a terminal command.\" });\n\nexport type WriteTextFileRequest = {\n  readonly _meta?: { readonly [x: string]: unknown } | null;\n  readonly content: string;\n  readonly path: string;\n  readonly sessionId: string;\n};\nexport const WriteTextFileRequest = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n  content: Schema.String.annotate({ description: \"The text content to write to the file.\" }),\n  path: Schema.String.annotate({ description: \"Absolute path to the file to write.\" }),\n  sessionId: Schema.String.annotate({\n    description:\n      \"A unique identifier for a conversation session between a client and agent.\\n\\nSessions maintain their own context, conversation history, and state,\\nallowing multiple independent interactions with the same agent.\\n\\nSee protocol docs: [Session ID](https://agentclientprotocol.com/protocol/session-setup#session-id)\",\n  }),\n}).annotate({\n  description:\n    \"Request to write content to a text file.\\n\\nOnly available if the client supports the `fs.writeTextFile` capability.\",\n});\n\nexport type WriteTextFileResponse = { readonly _meta?: { readonly [x: string]: unknown } | null };\nexport const WriteTextFileResponse = Schema.Struct({\n  _meta: Schema.optionalKey(\n    Schema.Union([\n      Schema.Record(Schema.String, Schema.Unknown).annotate({\n        description:\n          \"The _meta property is reserved by ACP to allow clients and agents to attach additional\\nmetadata to their interactions. Implementations MUST NOT make assumptions about values at\\nthese keys.\\n\\nSee protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)\",\n      }),\n      Schema.Null,\n    ]),\n  ),\n}).annotate({ description: \"Response to `fs/write_text_file`\" });\n","import * as Schema from \"effect/Schema\";\nimport type * as SchemaIssue from \"effect/SchemaIssue\";\n\nimport * as AcpSchema from \"./_generated/schema.gen.ts\";\n\nexport const AcpRequestOperation = Schema.Literals([\n  \"decode-extension-request-payload\",\n  \"encode-extension-response\",\n  \"handle-request\",\n  \"handle-extension-request\",\n  \"receive-response\",\n  \"receive-streaming-response\",\n]);\nexport type AcpRequestOperation = typeof AcpRequestOperation.Type;\n\nexport const AcpRequestId = Schema.Union([Schema.String, Schema.Number]);\nexport type AcpRequestId = typeof AcpRequestId.Type;\n\nexport const AcpSchemaIssueKind = Schema.Literals([\n  \"Filter\",\n  \"Encoding\",\n  \"Pointer\",\n  \"Composite\",\n  \"AnyOf\",\n  \"InvalidType\",\n  \"InvalidValue\",\n  \"MissingKey\",\n  \"UnexpectedKey\",\n  \"Forbidden\",\n  \"OneOf\",\n]);\nexport type AcpSchemaIssueKind = typeof AcpSchemaIssueKind.Type;\n\nexport interface AcpSchemaIssueDiagnostics {\n  readonly issueCount: number;\n  readonly issueKinds: ReadonlyArray<AcpSchemaIssueKind>;\n  readonly maximumPathDepth: number;\n}\n\nconst schemaIssueDiagnostics = (root: SchemaIssue.Issue): AcpSchemaIssueDiagnostics => {\n  let issueCount = 0;\n  let maximumPathDepth = 0;\n  const issueKinds = new Set<AcpSchemaIssueKind>();\n\n  const visit = (issue: SchemaIssue.Issue, pathDepth: number): void => {\n    issueCount += 1;\n    issueKinds.add(issue._tag);\n    maximumPathDepth = Math.max(maximumPathDepth, pathDepth);\n    switch (issue._tag) {\n      case \"Filter\":\n      case \"Encoding\":\n        visit(issue.issue, pathDepth);\n        break;\n      case \"Pointer\":\n        visit(issue.issue, pathDepth + issue.path.length);\n        break;\n      case \"Composite\":\n      case \"AnyOf\":\n        for (const child of issue.issues) visit(child, pathDepth);\n        break;\n    }\n  };\n\n  visit(root, 0);\n  return {\n    issueCount,\n    issueKinds: [...issueKinds],\n    maximumPathDepth,\n  };\n};\n\nexport interface AcpRequestDiagnostics {\n  readonly method?: string;\n  readonly requestId?: AcpRequestId;\n  readonly operation?: AcpRequestOperation;\n  readonly cause?: unknown;\n  readonly issueCount?: number;\n  readonly issueKinds?: ReadonlyArray<AcpSchemaIssueKind>;\n  readonly maximumPathDepth?: number;\n}\n\nexport class AcpSpawnError extends Schema.TaggedErrorClass<AcpSpawnError>()(\"AcpSpawnError\", {\n  command: Schema.optional(Schema.String),\n  cause: Schema.Defect(),\n}) {\n  override get message() {\n    return this.command\n      ? `Failed to spawn ACP process for command: ${this.command}`\n      : \"Failed to spawn ACP process\";\n  }\n}\n\nexport class AcpProcessExitedError extends Schema.TaggedErrorClass<AcpProcessExitedError>()(\n  \"AcpProcessExitedError\",\n  {\n    code: Schema.optional(Schema.Number),\n    pid: Schema.optionalKey(Schema.Int),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message() {\n    return this.code === undefined\n      ? \"ACP process exited\"\n      : `ACP process exited with code ${this.code}`;\n  }\n}\n\nexport const AcpProtocolParseOperation = Schema.Literals([\n  \"encode-message\",\n  \"decode-wire-message\",\n  \"decode-notification-payload\",\n]);\nexport type AcpProtocolParseOperation = typeof AcpProtocolParseOperation.Type;\n\nexport class AcpProtocolParseError extends Schema.TaggedErrorClass<AcpProtocolParseError>()(\n  \"AcpProtocolParseError\",\n  {\n    operation: AcpProtocolParseOperation,\n    method: Schema.optionalKey(Schema.String),\n    requestId: Schema.optionalKey(AcpRequestId),\n    issueCount: Schema.optionalKey(Schema.Number),\n    issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),\n    maximumPathDepth: Schema.optionalKey(Schema.Number),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    const method = this.method === undefined ? \"\" : ` for method '${this.method}'`;\n    return `ACP protocol operation '${this.operation}' failed${method}.`;\n  }\n\n  static fromSchemaError(\n    operation: AcpProtocolParseOperation,\n    method: string,\n    cause: Schema.SchemaError,\n  ) {\n    return new AcpProtocolParseError({\n      operation,\n      method,\n      ...schemaIssueDiagnostics(cause.issue),\n      cause,\n    });\n  }\n\n  static fromEncodingError(\n    method: string | undefined,\n    requestId: AcpRequestId | undefined,\n    cause: unknown,\n  ) {\n    return new AcpProtocolParseError({\n      operation: \"encode-message\",\n      ...(method === undefined ? {} : { method }),\n      ...(requestId === undefined ? {} : { requestId }),\n      cause,\n    });\n  }\n}\n\nexport class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError>()(\n  \"AcpTransportError\",\n  {\n    operation: Schema.optional(\n      Schema.Literals([\"call-rpc\", \"read-input-stream\", \"read-process-exit-status\"]),\n    ),\n    method: Schema.optional(Schema.String),\n    detail: Schema.optional(Schema.String),\n    pid: Schema.optionalKey(Schema.Int),\n    cause: Schema.Defect(),\n  },\n) {\n  override get message() {\n    const method = this.method ? ` for method ${this.method}` : \"\";\n    return this.operation\n      ? `ACP transport operation ${this.operation} failed${method}.`\n      : \"ACP transport operation failed.\";\n  }\n}\n\nexport class AcpInputStreamEndedError extends Schema.TaggedErrorClass<AcpInputStreamEndedError>()(\n  \"AcpInputStreamEndedError\",\n  {},\n) {\n  override get message() {\n    return \"ACP input stream ended.\";\n  }\n}\n\nexport class AcpRequestError extends Schema.TaggedErrorClass<AcpRequestError>()(\"AcpRequestError\", {\n  code: AcpSchema.ErrorCode,\n  errorMessage: Schema.String,\n  data: Schema.optional(Schema.Unknown),\n  method: Schema.optionalKey(Schema.String),\n  requestId: Schema.optionalKey(AcpRequestId),\n  operation: Schema.optionalKey(AcpRequestOperation),\n  issueCount: Schema.optionalKey(Schema.Number),\n  issueKinds: Schema.optionalKey(Schema.Array(AcpSchemaIssueKind)),\n  maximumPathDepth: Schema.optionalKey(Schema.Number),\n  cause: Schema.optionalKey(Schema.Defect()),\n}) {\n  override get message() {\n    return this.errorMessage;\n  }\n\n  static fromProtocolError(\n    error: AcpSchema.Error,\n    context: {\n      readonly method: string;\n      readonly requestId?: AcpRequestId;\n      readonly cause?: unknown;\n    },\n  ) {\n    return new AcpRequestError({\n      code: error.code,\n      errorMessage: error.message,\n      ...(error.data !== undefined ? { data: error.data } : {}),\n      method: context.method,\n      ...(context.requestId === undefined ? {} : { requestId: context.requestId }),\n      operation: \"receive-response\",\n      cause: context.cause ?? error,\n    });\n  }\n\n  static fromExtensionResponseFailure(method: string, requestId: AcpRequestId, cause: unknown) {\n    return AcpRequestError.internalError(\"Extension request failed\", undefined, {\n      method,\n      requestId,\n      operation: \"receive-response\",\n      cause,\n    });\n  }\n\n  static fromExtensionResponseEncodingError(\n    method: string,\n    requestId: AcpRequestId,\n    cause: AcpProtocolParseError,\n  ) {\n    return AcpRequestError.internalError(\"Internal error\", undefined, {\n      method,\n      requestId,\n      operation: \"encode-extension-response\",\n      cause,\n    });\n  }\n\n  static unsupportedStreamingResponse(method: string, requestId: AcpRequestId) {\n    return AcpRequestError.internalError(\n      \"Streaming extension responses are not supported\",\n      undefined,\n      {\n        method,\n        requestId,\n        operation: \"receive-streaming-response\",\n      },\n    );\n  }\n\n  static fromCoreHandlerError(error: AcpError, method: string) {\n    if (error._tag === \"AcpRequestError\") {\n      return error;\n    }\n    return AcpRequestError.internalError(\n      `ACP request handler failed for method '${method}'`,\n      undefined,\n      {\n        method,\n        operation: \"handle-request\",\n        cause: error,\n      },\n    );\n  }\n\n  static fromExtensionHandlerError(error: AcpError, method: string) {\n    if (error._tag === \"AcpRequestError\") {\n      return error;\n    }\n    return AcpRequestError.internalError(\n      `ACP extension request handler failed for method '${method}'`,\n      undefined,\n      {\n        method,\n        operation: \"handle-extension-request\",\n        cause: error,\n      },\n    );\n  }\n\n  static parseError(message = \"Parse error\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32700,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static invalidRequest(message = \"Invalid request\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32600,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static methodNotFound(method: string) {\n    return new AcpRequestError({\n      code: -32601,\n      errorMessage: `Method not found: ${method}`,\n    });\n  }\n\n  static invalidParams(message = \"Invalid params\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32602,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static invalidExtensionPayload(method: string, cause: Schema.SchemaError) {\n    const diagnostics = schemaIssueDiagnostics(cause.issue);\n    return new AcpRequestError({\n      code: -32602,\n      errorMessage: `Invalid payload for ACP extension method '${method}'.`,\n      data: diagnostics,\n      method,\n      operation: \"decode-extension-request-payload\",\n      ...diagnostics,\n      cause,\n    });\n  }\n\n  static internalError(\n    message = \"Internal error\",\n    data?: unknown,\n    diagnostics: AcpRequestDiagnostics = {},\n  ) {\n    return new AcpRequestError({\n      code: -32603,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n      ...diagnostics,\n    });\n  }\n\n  static authRequired(message = \"Authentication required\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32000,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  static resourceNotFound(message = \"Resource not found\", data?: unknown) {\n    return new AcpRequestError({\n      code: -32002,\n      errorMessage: message,\n      ...(data !== undefined ? { data } : {}),\n    });\n  }\n\n  toProtocolError() {\n    return AcpSchema.Error.make({\n      code: this.code,\n      message: this.errorMessage,\n      ...(this.data !== undefined ? { data: this.data } : {}),\n    });\n  }\n}\n\nexport const AcpError = Schema.Union([\n  AcpRequestError,\n  AcpSpawnError,\n  AcpProcessExitedError,\n  AcpProtocolParseError,\n  AcpTransportError,\n  AcpInputStreamEndedError,\n]);\n\nexport type AcpError = typeof AcpError.Type;\n","// This file is generated by the effect-acp package. Do not edit manually.\n// Current ACP schema release: v0.11.3\n\nexport const AGENT_METHODS = {\n  authenticate: \"authenticate\",\n  initialize: \"initialize\",\n  logout: \"logout\",\n  session_cancel: \"session/cancel\",\n  session_close: \"session/close\",\n  session_fork: \"session/fork\",\n  session_list: \"session/list\",\n  session_load: \"session/load\",\n  session_new: \"session/new\",\n  session_prompt: \"session/prompt\",\n  session_resume: \"session/resume\",\n  session_set_config_option: \"session/set_config_option\",\n  session_set_mode: \"session/set_mode\",\n  session_set_model: \"session/set_model\",\n} as const;\n\nexport const CLIENT_METHODS = {\n  fs_read_text_file: \"fs/read_text_file\",\n  fs_write_text_file: \"fs/write_text_file\",\n  session_elicitation: \"session/elicitation\",\n  session_elicitation_complete: \"session/elicitation/complete\",\n  session_request_permission: \"session/request_permission\",\n  session_update: \"session/update\",\n  terminal_create: \"terminal/create\",\n  terminal_kill: \"terminal/kill\",\n  terminal_output: \"terminal/output\",\n  terminal_release: \"terminal/release\",\n  terminal_wait_for_exit: \"terminal/wait_for_exit\",\n} as const;\n\nexport const PROTOCOL_VERSION = 1 as const;\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as RpcClient from \"effect/unstable/rpc/RpcClient\";\nimport * as RpcClientError from \"effect/unstable/rpc/RpcClientError\";\nimport * as RpcMessage from \"effect/unstable/rpc/RpcMessage\";\nimport * as RpcSerialization from \"effect/unstable/rpc/RpcSerialization\";\nimport * as RpcServer from \"effect/unstable/rpc/RpcServer\";\n\nimport * as AcpSchema from \"./_generated/schema.gen.ts\";\nimport { CLIENT_METHODS } from \"./_generated/meta.gen.ts\";\nimport * as AcpError from \"./errors.ts\";\nconst isAcpError = Schema.is(AcpError.AcpError);\n\nexport interface AcpProtocolLogEvent {\n  readonly direction: \"incoming\" | \"outgoing\";\n  readonly stage: \"raw\" | \"decoded\" | \"decode_failed\";\n  readonly payload: unknown;\n}\n\nexport type AcpIncomingNotification =\n  | {\n      readonly _tag: \"SessionUpdate\";\n      readonly method: typeof CLIENT_METHODS.session_update;\n      readonly params: AcpSchema.SessionNotification;\n    }\n  | {\n      readonly _tag: \"ElicitationComplete\";\n      readonly method: typeof CLIENT_METHODS.session_elicitation_complete;\n      readonly params: AcpSchema.ElicitationCompleteNotification;\n    }\n  | {\n      readonly _tag: \"ExtNotification\";\n      readonly method: string;\n      readonly params: unknown;\n    };\n\nexport interface AcpPatchedProtocolOptions {\n  readonly stdio: Stdio.Stdio;\n  readonly terminationError?: Effect.Effect<AcpError.AcpError>;\n  readonly serverRequestMethods: ReadonlySet<string>;\n  readonly logIncoming?: boolean;\n  readonly logOutgoing?: boolean;\n  readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;\n  readonly onNotification?: (\n    notification: AcpIncomingNotification,\n  ) => Effect.Effect<void, AcpError.AcpError, never>;\n  readonly onExtRequest?: (\n    method: string,\n    params: unknown,\n  ) => Effect.Effect<unknown, AcpError.AcpError, never>;\n  readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;\n}\n\nexport interface AcpPatchedProtocol {\n  readonly clientProtocol: RpcClient.Protocol[\"Service\"];\n  readonly serverProtocol: RpcServer.Protocol[\"Service\"];\n  readonly incoming: Stream.Stream<AcpIncomingNotification>;\n  readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;\n  readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;\n}\n\ninterface AcpPendingRequest {\n  readonly deferred: Deferred.Deferred<unknown, AcpError.AcpError>;\n  readonly method: string;\n}\n\nconst decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);\nconst decodeElicitationComplete = Schema.decodeUnknownEffect(\n  AcpSchema.ElicitationCompleteNotification,\n);\nconst parserFactory = RpcSerialization.ndJsonRpc();\n\nexport const makeAcpPatchedProtocol = Effect.fn(\"makeAcpPatchedProtocol\")(function* (\n  options: AcpPatchedProtocolOptions,\n): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {\n  const parser = parserFactory.makeUnsafe();\n  const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();\n  const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();\n  const notificationQueue = yield* Queue.unbounded<AcpIncomingNotification>();\n  const disconnects = yield* Queue.unbounded<number>();\n  const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();\n  const nextRequestId = yield* Ref.make(1);\n  const terminationHandled = yield* Ref.make(false);\n  const extPending = yield* Ref.make(new Map<string, AcpPendingRequest>());\n\n  const logProtocol = (event: AcpProtocolLogEvent) => {\n    if (event.direction === \"incoming\" && !options.logIncoming) {\n      return Effect.void;\n    }\n    if (event.direction === \"outgoing\" && !options.logOutgoing) {\n      return Effect.void;\n    }\n    return (\n      options.logger?.(event) ??\n      Effect.logDebug(\"ACP protocol event\").pipe(Effect.annotateLogs({ event }))\n    );\n  };\n\n  const offerOutgoing = Effect.fn(\"offerOutgoing\")(function* (\n    message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,\n  ) {\n    yield* logProtocol({\n      direction: \"outgoing\",\n      stage: \"decoded\",\n      payload: message,\n    });\n\n    const method = message._tag === \"Request\" ? message.tag : undefined;\n    const encodedRequestId =\n      message._tag === \"Request\"\n        ? message.id\n        : \"requestId\" in message\n          ? message.requestId\n          : undefined;\n    const requestId = encodedRequestId === \"\" ? undefined : encodedRequestId;\n    const encoded = yield* Effect.try({\n      try: () => parser.encode(message),\n      catch: (cause) => AcpError.AcpProtocolParseError.fromEncodingError(method, requestId, cause),\n    });\n\n    if (encoded) {\n      yield* logProtocol({\n        direction: \"outgoing\",\n        stage: \"raw\",\n        payload: typeof encoded === \"string\" ? encoded : new TextDecoder().decode(encoded),\n      });\n\n      yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);\n    }\n  });\n\n  const resolveExtPending = (\n    requestId: AcpError.AcpRequestId,\n    onFound: (pendingRequest: AcpPendingRequest) => Effect.Effect<void>,\n  ) =>\n    Ref.modify(extPending, (pending) => {\n      const pendingKey = String(requestId);\n      const pendingRequest = pending.get(pendingKey);\n      if (!pendingRequest) {\n        return [Effect.void, pending] as const;\n      }\n      const next = new Map(pending);\n      next.delete(pendingKey);\n      return [onFound(pendingRequest), next] as const;\n    }).pipe(Effect.flatten);\n\n  const removeExtPending = (requestId: AcpError.AcpRequestId) =>\n    Ref.update(extPending, (pending) => {\n      const pendingKey = String(requestId);\n      if (!pending.has(pendingKey)) {\n        return pending;\n      }\n      const next = new Map(pending);\n      next.delete(pendingKey);\n      return next;\n    });\n\n  const completeExtPendingFailure = (requestId: AcpError.AcpRequestId, error: AcpError.AcpError) =>\n    resolveExtPending(requestId, ({ deferred }) => Deferred.fail(deferred, error));\n\n  const completeExtPendingSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>\n    resolveExtPending(requestId, ({ deferred }) => Deferred.succeed(deferred, value));\n\n  const failAllExtPending = (error: AcpError.AcpError) =>\n    Ref.getAndSet(extPending, new Map()).pipe(\n      Effect.flatMap((pending) =>\n        Effect.forEach([...pending.values()], ({ deferred }) => Deferred.fail(deferred, error), {\n          discard: true,\n        }),\n      ),\n    );\n\n  const dispatchNotification = (notification: AcpIncomingNotification) =>\n    Queue.offer(notificationQueue, notification).pipe(\n      Effect.andThen(\n        options.onNotification\n          ? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))\n          : Effect.void,\n      ),\n      Effect.asVoid,\n    );\n\n  const emitClientProtocolError = (error: AcpError.AcpError) =>\n    Queue.offer(clientQueue, {\n      _tag: \"ClientProtocolError\",\n      error: new RpcClientError.RpcClientError({\n        reason: new RpcClientError.RpcClientDefect({\n          message: \"ACP protocol terminated.\",\n          cause: error,\n        }),\n      }),\n    }).pipe(Effect.asVoid);\n\n  const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError | undefined>) =>\n    Ref.modify(terminationHandled, (handled) => {\n      if (handled) {\n        return [Effect.void, true] as const;\n      }\n      return [\n        Effect.gen(function* () {\n          yield* Queue.offer(disconnects, 0);\n          const error = yield* classify();\n          if (!error) {\n            return;\n          }\n          yield* failAllExtPending(error);\n          yield* emitClientProtocolError(error);\n          if (options.onTermination) {\n            yield* options.onTermination(error);\n          }\n        }),\n        true,\n      ] as const;\n    }).pipe(Effect.flatten);\n\n  const respondWithSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>\n    offerOutgoing({\n      _tag: \"Exit\",\n      requestId,\n      exit: {\n        _tag: \"Success\",\n        value,\n      },\n    });\n\n  const respondWithError = (requestId: AcpError.AcpRequestId, error: AcpError.AcpRequestError) =>\n    offerOutgoing({\n      _tag: \"Exit\",\n      requestId,\n      exit: {\n        _tag: \"Failure\",\n        cause: [\n          {\n            _tag: \"Fail\",\n            error: error.toProtocolError(),\n          },\n        ],\n      },\n    });\n\n  const handleExtRequest = (message: RpcMessage.RequestEncoded) => {\n    if (!options.onExtRequest) {\n      return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));\n    }\n    return options.onExtRequest(message.tag, message.payload).pipe(\n      Effect.matchEffect({\n        onFailure: (error) =>\n          respondWithError(\n            message.id,\n            AcpError.AcpRequestError.fromExtensionHandlerError(error, message.tag),\n          ),\n        onSuccess: (value) => respondWithSuccess(message.id, value),\n      }),\n    );\n  };\n\n  const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {\n    if (message.id === \"\") {\n      if (message.tag === CLIENT_METHODS.session_update) {\n        return decodeSessionUpdate(message.payload).pipe(\n          Effect.map(\n            (params) =>\n              ({\n                _tag: \"SessionUpdate\",\n                method: CLIENT_METHODS.session_update,\n                params,\n              }) satisfies AcpIncomingNotification,\n          ),\n          Effect.mapError((cause) =>\n            AcpError.AcpProtocolParseError.fromSchemaError(\n              \"decode-notification-payload\",\n              CLIENT_METHODS.session_update,\n              cause,\n            ),\n          ),\n          Effect.flatMap(dispatchNotification),\n        );\n      }\n      if (message.tag === CLIENT_METHODS.session_elicitation_complete) {\n        return decodeElicitationComplete(message.payload).pipe(\n          Effect.map(\n            (params) =>\n              ({\n                _tag: \"ElicitationComplete\",\n                method: CLIENT_METHODS.session_elicitation_complete,\n                params,\n              }) satisfies AcpIncomingNotification,\n          ),\n          Effect.mapError((cause) =>\n            AcpError.AcpProtocolParseError.fromSchemaError(\n              \"decode-notification-payload\",\n              CLIENT_METHODS.session_elicitation_complete,\n              cause,\n            ),\n          ),\n          Effect.flatMap(dispatchNotification),\n        );\n      }\n      return dispatchNotification({\n        _tag: \"ExtNotification\",\n        method: message.tag,\n        params: message.payload,\n      });\n    }\n\n    if (!options.serverRequestMethods.has(message.tag)) {\n      return handleExtRequest(message).pipe(\n        Effect.catchTags({\n          AcpProtocolParseError: (error) =>\n            Effect.logWarning(error).pipe(\n              Effect.annotateLogs({\n                method: message.tag,\n                requestId: message.id,\n                operation: error.operation,\n              }),\n              Effect.andThen(\n                respondWithError(\n                  message.id,\n                  AcpError.AcpRequestError.fromExtensionResponseEncodingError(\n                    message.tag,\n                    message.id,\n                    error,\n                  ),\n                ),\n              ),\n            ),\n        }),\n        Effect.asVoid,\n      );\n    }\n\n    return Queue.offer(serverQueue, message).pipe(Effect.asVoid);\n  };\n\n  const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>\n    Ref.get(extPending).pipe(\n      Effect.flatMap((pending) => {\n        const pendingRequest = pending.get(String(message.requestId));\n        if (!pendingRequest) {\n          return Queue.offer(clientQueue, message).pipe(Effect.asVoid);\n        }\n        if (message.exit._tag === \"Success\") {\n          return completeExtPendingSuccess(message.requestId, message.exit.value);\n        }\n        const failure = message.exit.cause.find((entry) => entry._tag === \"Fail\");\n        if (failure && isProtocolError(failure.error)) {\n          return completeExtPendingFailure(\n            message.requestId,\n            AcpError.AcpRequestError.fromProtocolError(failure.error, {\n              method: pendingRequest.method,\n              requestId: message.requestId,\n              cause: message.exit.cause,\n            }),\n          );\n        }\n        return completeExtPendingFailure(\n          message.requestId,\n          AcpError.AcpRequestError.fromExtensionResponseFailure(\n            pendingRequest.method,\n            message.requestId,\n            message.exit.cause,\n          ),\n        );\n      }),\n    );\n\n  const routeDecodedMessage = (\n    message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,\n  ): Effect.Effect<void, AcpError.AcpError> => {\n    switch (message._tag) {\n      case \"Request\":\n        return handleRequestEncoded(message);\n      case \"Exit\":\n        return handleExitEncoded(message);\n      case \"Chunk\":\n        return Ref.get(extPending).pipe(\n          Effect.flatMap((pending) => {\n            const pendingRequest = pending.get(String(message.requestId));\n            return pendingRequest\n              ? completeExtPendingFailure(\n                  message.requestId,\n                  AcpError.AcpRequestError.unsupportedStreamingResponse(\n                    pendingRequest.method,\n                    message.requestId,\n                  ),\n                )\n              : Queue.offer(clientQueue, message).pipe(Effect.asVoid);\n          }),\n        );\n      case \"Defect\":\n      case \"ClientProtocolError\":\n      case \"Pong\":\n        return Queue.offer(clientQueue, message).pipe(Effect.asVoid);\n      case \"Ack\":\n      case \"Interrupt\":\n      case \"Ping\":\n      case \"Eof\":\n        return Queue.offer(serverQueue, message).pipe(Effect.asVoid);\n    }\n  };\n\n  yield* options.stdio.stdin.pipe(\n    Stream.runForEach((data) =>\n      logProtocol({\n        direction: \"incoming\",\n        stage: \"raw\",\n        payload: typeof data === \"string\" ? data : new TextDecoder().decode(data),\n      }).pipe(\n        Effect.flatMap(() =>\n          Effect.try({\n            try: () =>\n              parser.decode(data) as ReadonlyArray<\n                RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded\n              >,\n            catch: (cause) =>\n              new AcpError.AcpProtocolParseError({\n                operation: \"decode-wire-message\",\n                cause,\n              }),\n          }),\n        ),\n        Effect.tap((messages) =>\n          logProtocol({\n            direction: \"incoming\",\n            stage: \"decoded\",\n            payload: messages,\n          }),\n        ),\n        Effect.tapErrorTag(\"AcpProtocolParseError\", (error) =>\n          logProtocol({\n            direction: \"incoming\",\n            stage: \"decode_failed\",\n            payload: {\n              operation: error.operation,\n              ...(error.method === undefined ? {} : { method: error.method }),\n              ...(error.requestId === undefined ? {} : { requestId: error.requestId }),\n              ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),\n              ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),\n              ...(error.maximumPathDepth === undefined\n                ? {}\n                : { maximumPathDepth: error.maximumPathDepth }),\n            },\n          }),\n        ),\n        Effect.flatMap((messages) =>\n          Effect.forEach(messages, routeDecodedMessage, {\n            discard: true,\n          }),\n        ),\n      ),\n    ),\n    Effect.matchEffect({\n      onFailure: (error) => {\n        const normalized: AcpError.AcpError = isAcpError(error)\n          ? error\n          : new AcpError.AcpTransportError({\n              operation: \"read-input-stream\",\n              cause: error,\n            });\n        return handleTermination(() => Effect.succeed(normalized));\n      },\n      onSuccess: () =>\n        handleTermination(\n          () =>\n            options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),\n        ),\n    }),\n    Effect.forkScoped,\n  );\n\n  yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);\n\n  const clientProtocol = RpcClient.Protocol.of({\n    run: (_clientId, f) =>\n      Stream.fromQueue(clientQueue).pipe(\n        Stream.runForEach((message) => f(message)),\n        Effect.forever,\n      ),\n    send: (_clientId, request) =>\n      offerOutgoing(request).pipe(\n        Effect.mapError(\n          (error) =>\n            new RpcClientError.RpcClientError({\n              reason: new RpcClientError.RpcClientDefect({\n                message: \"Failed to send ACP protocol message.\",\n                cause: error,\n              }),\n            }),\n        ),\n      ),\n    supportsAck: true,\n    supportsTransferables: false,\n  });\n\n  const serverProtocol = RpcServer.Protocol.of({\n    run: (f) =>\n      Stream.fromQueue(serverQueue).pipe(\n        Stream.runForEach((message) => f(0, message)),\n        Effect.forever,\n      ),\n    disconnects,\n    send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),\n    end: (_clientId) => Queue.end(outgoing),\n    clientIds: Effect.succeed(new Set([0])),\n    initialMessage: Effect.succeedNone,\n    supportsAck: true,\n    supportsTransferables: false,\n    supportsSpanPropagation: true,\n  });\n\n  const sendNotification = Effect.fn(\"sendNotification\")(function* (\n    method: string,\n    payload: unknown,\n  ) {\n    yield* offerOutgoing({\n      _tag: \"Request\",\n      id: \"\",\n      tag: method,\n      payload,\n      headers: [],\n    });\n  });\n\n  const sendRequest = Effect.fn(\"sendRequest\")(function* (method: string, payload: unknown) {\n    const requestId = yield* Ref.modify(\n      nextRequestId,\n      (current) => [current, current + 1] as const,\n    );\n    const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();\n    yield* Ref.update(extPending, (pending) =>\n      new Map(pending).set(String(requestId), { deferred, method }),\n    );\n    yield* offerOutgoing({\n      _tag: \"Request\",\n      id: requestId,\n      tag: method,\n      payload,\n      headers: [],\n    }).pipe(Effect.tapError(() => removeExtPending(requestId)));\n    return yield* Deferred.await(deferred).pipe(\n      Effect.onInterrupt(() => removeExtPending(requestId)),\n    );\n  });\n\n  return {\n    clientProtocol,\n    serverProtocol,\n    get incoming() {\n      return Stream.fromQueue(notificationQueue);\n    },\n    request: sendRequest,\n    notify: sendNotification,\n  } satisfies AcpPatchedProtocol;\n});\n\nfunction isProtocolError(\n  value: unknown,\n): value is { code: number; message: string; data?: unknown } {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"code\" in value &&\n    typeof value.code === \"number\" &&\n    \"message\" in value &&\n    typeof value.message === \"string\"\n  );\n}\n","import * as Rpc from \"effect/unstable/rpc/Rpc\";\nimport * as RpcGroup from \"effect/unstable/rpc/RpcGroup\";\n\nimport * as AcpSchema from \"./_generated/schema.gen.ts\";\nimport { AGENT_METHODS, CLIENT_METHODS } from \"./_generated/meta.gen.ts\";\n\nexport const InitializeRpc = Rpc.make(AGENT_METHODS.initialize, {\n  payload: AcpSchema.InitializeRequest,\n  success: AcpSchema.InitializeResponse,\n  error: AcpSchema.Error,\n});\n\nexport const AuthenticateRpc = Rpc.make(AGENT_METHODS.authenticate, {\n  payload: AcpSchema.AuthenticateRequest,\n  success: AcpSchema.AuthenticateResponse,\n  error: AcpSchema.Error,\n});\n\nexport const LogoutRpc = Rpc.make(AGENT_METHODS.logout, {\n  payload: AcpSchema.LogoutRequest,\n  success: AcpSchema.LogoutResponse,\n  error: AcpSchema.Error,\n});\n\nexport const NewSessionRpc = Rpc.make(AGENT_METHODS.session_new, {\n  payload: AcpSchema.NewSessionRequest,\n  success: AcpSchema.NewSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const LoadSessionRpc = Rpc.make(AGENT_METHODS.session_load, {\n  payload: AcpSchema.LoadSessionRequest,\n  success: AcpSchema.LoadSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ListSessionsRpc = Rpc.make(AGENT_METHODS.session_list, {\n  payload: AcpSchema.ListSessionsRequest,\n  success: AcpSchema.ListSessionsResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ForkSessionRpc = Rpc.make(AGENT_METHODS.session_fork, {\n  payload: AcpSchema.ForkSessionRequest,\n  success: AcpSchema.ForkSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ResumeSessionRpc = Rpc.make(AGENT_METHODS.session_resume, {\n  payload: AcpSchema.ResumeSessionRequest,\n  success: AcpSchema.ResumeSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const CloseSessionRpc = Rpc.make(AGENT_METHODS.session_close, {\n  payload: AcpSchema.CloseSessionRequest,\n  success: AcpSchema.CloseSessionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const PromptRpc = Rpc.make(AGENT_METHODS.session_prompt, {\n  payload: AcpSchema.PromptRequest,\n  success: AcpSchema.PromptResponse,\n  error: AcpSchema.Error,\n});\n\nexport const SetSessionModelRpc = Rpc.make(AGENT_METHODS.session_set_model, {\n  payload: AcpSchema.SetSessionModelRequest,\n  success: AcpSchema.SetSessionModelResponse,\n  error: AcpSchema.Error,\n});\n\nexport const SetSessionConfigOptionRpc = Rpc.make(AGENT_METHODS.session_set_config_option, {\n  payload: AcpSchema.SetSessionConfigOptionRequest,\n  success: AcpSchema.SetSessionConfigOptionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ReadTextFileRpc = Rpc.make(CLIENT_METHODS.fs_read_text_file, {\n  payload: AcpSchema.ReadTextFileRequest,\n  success: AcpSchema.ReadTextFileResponse,\n  error: AcpSchema.Error,\n});\n\nexport const WriteTextFileRpc = Rpc.make(CLIENT_METHODS.fs_write_text_file, {\n  payload: AcpSchema.WriteTextFileRequest,\n  success: AcpSchema.WriteTextFileResponse,\n  error: AcpSchema.Error,\n});\n\nexport const RequestPermissionRpc = Rpc.make(CLIENT_METHODS.session_request_permission, {\n  payload: AcpSchema.RequestPermissionRequest,\n  success: AcpSchema.RequestPermissionResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ElicitationRpc = Rpc.make(CLIENT_METHODS.session_elicitation, {\n  payload: AcpSchema.ElicitationRequest,\n  success: AcpSchema.ElicitationResponse,\n  error: AcpSchema.Error,\n});\n\nexport const CreateTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_create, {\n  payload: AcpSchema.CreateTerminalRequest,\n  success: AcpSchema.CreateTerminalResponse,\n  error: AcpSchema.Error,\n});\n\nexport const TerminalOutputRpc = Rpc.make(CLIENT_METHODS.terminal_output, {\n  payload: AcpSchema.TerminalOutputRequest,\n  success: AcpSchema.TerminalOutputResponse,\n  error: AcpSchema.Error,\n});\n\nexport const ReleaseTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_release, {\n  payload: AcpSchema.ReleaseTerminalRequest,\n  success: AcpSchema.ReleaseTerminalResponse,\n  error: AcpSchema.Error,\n});\n\nexport const WaitForTerminalExitRpc = Rpc.make(CLIENT_METHODS.terminal_wait_for_exit, {\n  payload: AcpSchema.WaitForTerminalExitRequest,\n  success: AcpSchema.WaitForTerminalExitResponse,\n  error: AcpSchema.Error,\n});\n\nexport const KillTerminalRpc = Rpc.make(CLIENT_METHODS.terminal_kill, {\n  payload: AcpSchema.KillTerminalRequest,\n  success: AcpSchema.KillTerminalResponse,\n  error: AcpSchema.Error,\n});\n\nexport const AgentRpcs = RpcGroup.make(\n  InitializeRpc,\n  AuthenticateRpc,\n  LogoutRpc,\n  NewSessionRpc,\n  LoadSessionRpc,\n  ListSessionsRpc,\n  ForkSessionRpc,\n  ResumeSessionRpc,\n  CloseSessionRpc,\n  PromptRpc,\n  SetSessionModelRpc,\n  SetSessionConfigOptionRpc,\n);\n\nexport const ClientRpcs = RpcGroup.make(\n  ReadTextFileRpc,\n  WriteTextFileRpc,\n  RequestPermissionRpc,\n  ElicitationRpc,\n  CreateTerminalRpc,\n  TerminalOutputRpc,\n  ReleaseTerminalRpc,\n  WaitForTerminalExitRpc,\n  KillTerminalRpc,\n);\n","import * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport { RpcClientError } from \"effect/unstable/rpc\";\n\nimport * as AcpSchema from \"../_generated/schema.gen.ts\";\nimport * as AcpError from \"../errors.ts\";\nconst isError = Schema.is(AcpSchema.Error);\n\nexport const callRpc = <A>(\n  method: string,\n  effect: Effect.Effect<A, RpcClientError.RpcClientError | AcpSchema.Error>,\n): Effect.Effect<A, AcpError.AcpError> =>\n  effect.pipe(\n    Effect.catchIf(isError, (error) =>\n      Effect.fail(AcpError.AcpRequestError.fromProtocolError(error, { method })),\n    ),\n    Effect.catchTags({\n      RpcClientError: (cause) =>\n        Effect.fail(\n          new AcpError.AcpTransportError({\n            operation: \"call-rpc\",\n            method,\n            cause,\n          }),\n        ),\n    }),\n  );\n\nexport const runHandler = Effect.fnUntraced(function* <A, B>(\n  handler: ((payload: A) => Effect.Effect<B, AcpError.AcpError>) | undefined,\n  payload: A,\n  method: string,\n) {\n  if (!handler) {\n    return yield* Effect.fail(AcpError.AcpRequestError.methodNotFound(method).toProtocolError());\n  }\n  return yield* handler(payload).pipe(\n    Effect.mapError((error) =>\n      AcpError.AcpRequestError.fromCoreHandlerError(error, method).toProtocolError(),\n    ),\n  );\n});\n\nexport function decodeExtRequestRegistration<A, I>(\n  method: string,\n  payload: Schema.Codec<A, I>,\n  handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,\n) {\n  return (params: unknown): Effect.Effect<unknown, AcpError.AcpError> =>\n    Schema.decodeUnknownEffect(payload)(params).pipe(\n      Effect.mapError((error) => AcpError.AcpRequestError.invalidExtensionPayload(method, error)),\n      Effect.flatMap((decoded) => handler(decoded)),\n    );\n}\n\nexport function decodeExtNotificationRegistration<A, I>(\n  method: string,\n  payload: Schema.Codec<A, I>,\n  handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,\n) {\n  return (params: unknown): Effect.Effect<void, AcpError.AcpError> =>\n    Schema.decodeUnknownEffect(payload)(params).pipe(\n      Effect.mapError((error) =>\n        AcpError.AcpProtocolParseError.fromSchemaError(\n          \"decode-notification-payload\",\n          method,\n          error,\n        ),\n      ),\n      Effect.flatMap((decoded) => handler(decoded)),\n    );\n}\n\nconst encoder = new TextEncoder();\n\nconst JsonRpcId = Schema.Union([Schema.Number, Schema.String]);\nconst JsonRpcHeaders = Schema.Array(Schema.Unknown);\n\nexport const jsonRpcRequest = <A, I>(method: string, params: Schema.Codec<A, I>) =>\n  Schema.Struct({\n    jsonrpc: Schema.Literal(\"2.0\"),\n    id: JsonRpcId,\n    method: Schema.Literal(method),\n    params,\n    headers: JsonRpcHeaders,\n  });\n\nexport const jsonRpcNotification = <A, I>(method: string, params: Schema.Codec<A, I>) =>\n  Schema.Struct({\n    jsonrpc: Schema.Literal(\"2.0\"),\n    method: Schema.Literal(method),\n    params,\n  });\n\nexport const jsonRpcResponse = <A, I>(result: Schema.Codec<A, I>) =>\n  Schema.Struct({\n    jsonrpc: Schema.Literal(\"2.0\"),\n    id: JsonRpcId,\n    result,\n  });\n\nexport const encodeJsonl = <A, I>(schema: Schema.Codec<A, I>, value: A) =>\n  Effect.map(Schema.encodeEffect(Schema.fromJsonString(schema))(value), (encoded) =>\n    encoder.encode(`${encoded}\\n`),\n  );\n","import * as Queue from \"effect/Queue\";\nimport * as Stream from \"effect/Stream\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stdio from \"effect/Stdio\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport * as AcpError from \"../errors.ts\";\n\nconst encoder = new TextEncoder();\n\nexport const makeChildStdio = (handle: ChildProcessSpawner.ChildProcessHandle) =>\n  Stdio.make({\n    args: Effect.succeed([]),\n    stdin: handle.stdout,\n    stdout: () =>\n      Sink.mapInput(handle.stdin, (chunk: string | Uint8Array) =>\n        typeof chunk === \"string\" ? encoder.encode(chunk) : chunk,\n      ),\n    stderr: () => Sink.drain,\n  });\n\nexport const makeInMemoryStdio = Effect.fn(\"makeInMemoryStdio\")(function* () {\n  const input = yield* Queue.unbounded<Uint8Array, Cause.Done<void>>();\n  const output = yield* Queue.unbounded<string>();\n  const decoder = new TextDecoder();\n\n  return {\n    stdio: Stdio.make({\n      args: Effect.succeed([]),\n      stdin: Stream.fromQueue(input),\n      stdout: () =>\n        Sink.forEach((chunk: string | Uint8Array) =>\n          Queue.offer(\n            output,\n            typeof chunk === \"string\" ? chunk : decoder.decode(chunk, { stream: true }),\n          ),\n        ),\n      stderr: () => Sink.drain,\n    }),\n    input,\n    output,\n  };\n});\n\ntype ChildProcessTerminationHandle = Pick<\n  ChildProcessSpawner.ChildProcessHandle,\n  \"exitCode\" | \"pid\"\n>;\n\nexport const makeTerminationError = (\n  handle: ChildProcessTerminationHandle,\n): Effect.Effect<AcpError.AcpError> =>\n  Effect.match(handle.exitCode, {\n    onFailure: (cause) =>\n      new AcpError.AcpTransportError({\n        operation: \"read-process-exit-status\",\n        pid: handle.pid,\n        cause,\n      }),\n    onSuccess: (code) => new AcpError.AcpProcessExitedError({ code, pid: handle.pid }),\n  });\n","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Stdio from \"effect/Stdio\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as RpcClient from \"effect/unstable/rpc/RpcClient\";\nimport * as RpcMessage from \"effect/unstable/rpc/RpcMessage\";\nimport * as RpcServer from \"effect/unstable/rpc/RpcServer\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\n\nimport * as AcpError from \"./errors.ts\";\nimport * as AcpProtocol from \"./protocol.ts\";\nimport * as AcpRpcs from \"./rpc.ts\";\nimport * as AcpSchema from \"./_generated/schema.gen.ts\";\nimport { AGENT_METHODS, CLIENT_METHODS } from \"./_generated/meta.gen.ts\";\nimport {\n  callRpc,\n  decodeExtNotificationRegistration,\n  decodeExtRequestRegistration,\n  runHandler,\n} from \"./_internal/shared.ts\";\nimport { makeChildStdio, makeTerminationError } from \"./_internal/stdio.ts\";\n\nexport interface AcpClientOptions {\n  readonly logIncoming?: boolean;\n  readonly logOutgoing?: boolean;\n  readonly logger?: (event: AcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;\n}\n\ntype AcpClientRaw = {\n  readonly notifications: Stream.Stream<AcpProtocol.AcpIncomingNotification>;\n  readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;\n  readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;\n};\n\nexport class AcpClient extends Context.Service<\n  AcpClient,\n  {\n    readonly raw: AcpClientRaw;\n    readonly agent: {\n      /**\n       * Initializes the ACP session and negotiates capabilities.\n       * @see https://agentclientprotocol.com/protocol/schema#initialize\n       */\n      readonly initialize: (\n        payload: AcpSchema.InitializeRequest,\n      ) => Effect.Effect<AcpSchema.InitializeResponse, AcpError.AcpError>;\n      /**\n       * Performs ACP authentication when the agent requires it.\n       * @see https://agentclientprotocol.com/protocol/schema#authenticate\n       */\n      readonly authenticate: (\n        payload: AcpSchema.AuthenticateRequest,\n      ) => Effect.Effect<AcpSchema.AuthenticateResponse, AcpError.AcpError>;\n      /**\n       * Logs out the current ACP identity.\n       * @see https://agentclientprotocol.com/protocol/schema#logout\n       */\n      readonly logout: (\n        payload: AcpSchema.LogoutRequest,\n      ) => Effect.Effect<AcpSchema.LogoutResponse, AcpError.AcpError>;\n      /**\n       * Starts a new ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/new\n       */\n      readonly createSession: (\n        payload: AcpSchema.NewSessionRequest,\n      ) => Effect.Effect<AcpSchema.NewSessionResponse, AcpError.AcpError>;\n      /**\n       * Loads a previously saved ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/load\n       */\n      readonly loadSession: (\n        payload: AcpSchema.LoadSessionRequest,\n      ) => Effect.Effect<AcpSchema.LoadSessionResponse, AcpError.AcpError>;\n      /**\n       * Lists available ACP sessions.\n       * @see https://agentclientprotocol.com/protocol/schema#session/list\n       */\n      readonly listSessions: (\n        payload: AcpSchema.ListSessionsRequest,\n      ) => Effect.Effect<AcpSchema.ListSessionsResponse, AcpError.AcpError>;\n      /**\n       * Forks an ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/fork\n       */\n      readonly forkSession: (\n        payload: AcpSchema.ForkSessionRequest,\n      ) => Effect.Effect<AcpSchema.ForkSessionResponse, AcpError.AcpError>;\n      /**\n       * Resumes an ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/resume\n       */\n      readonly resumeSession: (\n        payload: AcpSchema.ResumeSessionRequest,\n      ) => Effect.Effect<AcpSchema.ResumeSessionResponse, AcpError.AcpError>;\n      /**\n       * Closes an ACP session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/close\n       */\n      readonly closeSession: (\n        payload: AcpSchema.CloseSessionRequest,\n      ) => Effect.Effect<AcpSchema.CloseSessionResponse, AcpError.AcpError>;\n      /**\n       * Selects the active model for a session.\n       * @see https://agentclientprotocol.com/protocol/schema#session/set_model\n       */\n      readonly setSessionModel: (\n        payload: AcpSchema.SetSessionModelRequest,\n      ) => Effect.Effect<AcpSchema.SetSessionModelResponse, AcpError.AcpError>;\n      /**\n       * Updates a session configuration option.\n       * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option\n       */\n      readonly setSessionConfigOption: (\n        payload: AcpSchema.SetSessionConfigOptionRequest,\n      ) => Effect.Effect<AcpSchema.SetSessionConfigOptionResponse, AcpError.AcpError>;\n      /**\n       * Sends a prompt turn to the agent.\n       * @see https://agentclientprotocol.com/protocol/schema#session/prompt\n       */\n      readonly prompt: (\n        payload: AcpSchema.PromptRequest,\n      ) => Effect.Effect<AcpSchema.PromptResponse, AcpError.AcpError>;\n      /**\n       * Sends a real ACP `session/cancel` notification.\n       * @see https://agentclientprotocol.com/protocol/schema#session/cancel\n       */\n      readonly cancel: (\n        payload: AcpSchema.CancelNotification,\n      ) => Effect.Effect<void, AcpError.AcpError>;\n    };\n    /**\n     * Registers a handler for `session/request_permission`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/request_permission\n     */\n    readonly handleRequestPermission: (\n      handler: (\n        request: AcpSchema.RequestPermissionRequest,\n      ) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `session/elicitation`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/elicitation\n     */\n    readonly handleElicitation: (\n      handler: (\n        request: AcpSchema.ElicitationRequest,\n      ) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `fs/read_text_file`.\n     * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file\n     */\n    readonly handleReadTextFile: (\n      handler: (\n        request: AcpSchema.ReadTextFileRequest,\n      ) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `fs/write_text_file`.\n     * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file\n     */\n    readonly handleWriteTextFile: (\n      handler: (\n        request: AcpSchema.WriteTextFileRequest,\n      ) => Effect.Effect<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/create`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/create\n     */\n    readonly handleCreateTerminal: (\n      handler: (\n        request: AcpSchema.CreateTerminalRequest,\n      ) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/output`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/output\n     */\n    readonly handleTerminalOutput: (\n      handler: (\n        request: AcpSchema.TerminalOutputRequest,\n      ) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/wait_for_exit`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit\n     */\n    readonly handleTerminalWaitForExit: (\n      handler: (\n        request: AcpSchema.WaitForTerminalExitRequest,\n      ) => Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/kill`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/kill\n     */\n    readonly handleTerminalKill: (\n      handler: (\n        request: AcpSchema.KillTerminalRequest,\n      ) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `terminal/release`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/release\n     */\n    readonly handleTerminalRelease: (\n      handler: (\n        request: AcpSchema.ReleaseTerminalRequest,\n      ) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `session/update`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/update\n     */\n    readonly handleSessionUpdate: (\n      handler: (\n        notification: AcpSchema.SessionNotification,\n      ) => Effect.Effect<void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a handler for `session/elicitation/complete`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete\n     */\n    readonly handleElicitationComplete: (\n      handler: (\n        notification: AcpSchema.ElicitationCompleteNotification,\n      ) => Effect.Effect<void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a fallback extension request handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleUnknownExtRequest: (\n      handler: (method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a fallback extension notification handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleUnknownExtNotification: (\n      handler: (method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a typed extension request handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleExtRequest: <A, I>(\n      method: string,\n      payload: Schema.Codec<A, I>,\n      handler: (payload: A) => Effect.Effect<unknown, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n    /**\n     * Registers a typed extension notification handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleExtNotification: <A, I>(\n      method: string,\n      payload: Schema.Codec<A, I>,\n      handler: (payload: A) => Effect.Effect<void, AcpError.AcpError>,\n    ) => Effect.Effect<void>;\n  }\n>()(\"effect-acp/client/AcpClient\") {}\n\ninterface AcpCoreRequestHandlers {\n  requestPermission?: (\n    request: AcpSchema.RequestPermissionRequest,\n  ) => Effect.Effect<AcpSchema.RequestPermissionResponse, AcpError.AcpError>;\n  elicitation?: (\n    request: AcpSchema.ElicitationRequest,\n  ) => Effect.Effect<AcpSchema.ElicitationResponse, AcpError.AcpError>;\n  readTextFile?: (\n    request: AcpSchema.ReadTextFileRequest,\n  ) => Effect.Effect<AcpSchema.ReadTextFileResponse, AcpError.AcpError>;\n  writeTextFile?: (\n    request: AcpSchema.WriteTextFileRequest,\n  ) => Effect.Effect<AcpSchema.WriteTextFileResponse | void, AcpError.AcpError>;\n  createTerminal?: (\n    request: AcpSchema.CreateTerminalRequest,\n  ) => Effect.Effect<AcpSchema.CreateTerminalResponse, AcpError.AcpError>;\n  terminalOutput?: (\n    request: AcpSchema.TerminalOutputRequest,\n  ) => Effect.Effect<AcpSchema.TerminalOutputResponse, AcpError.AcpError>;\n  terminalWaitForExit?: (\n    request: AcpSchema.WaitForTerminalExitRequest,\n  ) => Effect.Effect<AcpSchema.WaitForTerminalExitResponse, AcpError.AcpError>;\n  terminalKill?: (\n    request: AcpSchema.KillTerminalRequest,\n  ) => Effect.Effect<AcpSchema.KillTerminalResponse | void, AcpError.AcpError>;\n  terminalRelease?: (\n    request: AcpSchema.ReleaseTerminalRequest,\n  ) => Effect.Effect<AcpSchema.ReleaseTerminalResponse | void, AcpError.AcpError>;\n}\n\ninterface AcpNotificationHandlers {\n  readonly sessionUpdate: BufferedNotificationHandler<AcpSchema.SessionNotification>;\n  readonly elicitationComplete: BufferedNotificationHandler<AcpSchema.ElicitationCompleteNotification>;\n}\n\ninterface BufferedNotificationHandler<A> {\n  readonly handlers: Array<(notification: A) => Effect.Effect<void, AcpError.AcpError>>;\n  readonly pending: Array<A>;\n}\n\nexport const make = Effect.fn(\"effect-acp/AcpClient.make\")(function* (\n  stdio: Stdio.Stdio,\n  options: AcpClientOptions = {},\n  terminationError?: Effect.Effect<AcpError.AcpError>,\n): Effect.fn.Return<AcpClient[\"Service\"], never, Scope.Scope> {\n  const coreHandlers: AcpCoreRequestHandlers = {};\n  const notificationHandlers: AcpNotificationHandlers = {\n    sessionUpdate: { handlers: [], pending: [] },\n    elicitationComplete: { handlers: [], pending: [] },\n  };\n  const extRequestHandlers = new Map<\n    string,\n    (params: unknown) => Effect.Effect<unknown, AcpError.AcpError>\n  >();\n  const extNotificationHandlers = new Map<\n    string,\n    (params: unknown) => Effect.Effect<void, AcpError.AcpError>\n  >();\n  let unknownExtRequestHandler:\n    | ((method: string, params: unknown) => Effect.Effect<unknown, AcpError.AcpError>)\n    | undefined;\n  let unknownExtNotificationHandler:\n    | ((method: string, params: unknown) => Effect.Effect<void, AcpError.AcpError>)\n    | undefined;\n\n  const runNotificationHandlers = <A>(\n    registration: BufferedNotificationHandler<A>,\n    notification: A,\n  ) =>\n    Effect.forEach(\n      registration.handlers,\n      (handler) => handler(notification).pipe(Effect.catch(() => Effect.void)),\n      { discard: true },\n    );\n\n  const flushBufferedNotifications = <A>(registration: BufferedNotificationHandler<A>) =>\n    Effect.suspend(() => {\n      if (registration.handlers.length === 0 || registration.pending.length === 0) {\n        return Effect.void;\n      }\n      const pending = registration.pending.splice(0, registration.pending.length);\n      return Effect.forEach(\n        pending,\n        (notification) => runNotificationHandlers(registration, notification),\n        {\n          discard: true,\n        },\n      );\n    });\n\n  const dispatchNotification = (notification: AcpProtocol.AcpIncomingNotification) => {\n    switch (notification._tag) {\n      case \"SessionUpdate\": {\n        if (notificationHandlers.sessionUpdate.handlers.length === 0) {\n          notificationHandlers.sessionUpdate.pending.push(notification.params);\n          return Effect.void;\n        }\n        return runNotificationHandlers(notificationHandlers.sessionUpdate, notification.params);\n      }\n      case \"ElicitationComplete\": {\n        if (notificationHandlers.elicitationComplete.handlers.length === 0) {\n          notificationHandlers.elicitationComplete.pending.push(notification.params);\n          return Effect.void;\n        }\n        return runNotificationHandlers(\n          notificationHandlers.elicitationComplete,\n          notification.params,\n        );\n      }\n      case \"ExtNotification\": {\n        const handler = extNotificationHandlers.get(notification.method);\n        if (handler) {\n          return handler(notification.params);\n        }\n        return unknownExtNotificationHandler\n          ? unknownExtNotificationHandler(notification.method, notification.params)\n          : Effect.void;\n      }\n    }\n  };\n\n  const dispatchExtRequest = (method: string, params: unknown) => {\n    const handler = extRequestHandlers.get(method);\n    if (handler) {\n      return handler(params);\n    }\n    return unknownExtRequestHandler\n      ? unknownExtRequestHandler(method, params)\n      : Effect.fail(AcpError.AcpRequestError.methodNotFound(method));\n  };\n\n  const transport = yield* AcpProtocol.makeAcpPatchedProtocol({\n    stdio: stdio,\n    ...(terminationError ? { terminationError } : {}),\n    serverRequestMethods: new Set(AcpRpcs.ClientRpcs.requests.keys()),\n    ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}),\n    ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}),\n    ...(options.logger ? { logger: options.logger } : {}),\n    onNotification: dispatchNotification,\n    onExtRequest: dispatchExtRequest,\n  });\n\n  const clientHandlerLayer = AcpRpcs.ClientRpcs.toLayer(\n    AcpRpcs.ClientRpcs.of({\n      [CLIENT_METHODS.session_request_permission]: (payload) =>\n        runHandler(\n          coreHandlers.requestPermission,\n          payload,\n          CLIENT_METHODS.session_request_permission,\n        ),\n      [CLIENT_METHODS.session_elicitation]: (payload) =>\n        runHandler(coreHandlers.elicitation, payload, CLIENT_METHODS.session_elicitation),\n      [CLIENT_METHODS.fs_read_text_file]: (payload) =>\n        runHandler(coreHandlers.readTextFile, payload, CLIENT_METHODS.fs_read_text_file),\n      [CLIENT_METHODS.fs_write_text_file]: (payload) =>\n        runHandler(coreHandlers.writeTextFile, payload, CLIENT_METHODS.fs_write_text_file).pipe(\n          Effect.map((result) => result ?? {}),\n        ),\n      [CLIENT_METHODS.terminal_create]: (payload) =>\n        runHandler(coreHandlers.createTerminal, payload, CLIENT_METHODS.terminal_create),\n      [CLIENT_METHODS.terminal_output]: (payload) =>\n        runHandler(coreHandlers.terminalOutput, payload, CLIENT_METHODS.terminal_output),\n      [CLIENT_METHODS.terminal_wait_for_exit]: (payload) =>\n        runHandler(\n          coreHandlers.terminalWaitForExit,\n          payload,\n          CLIENT_METHODS.terminal_wait_for_exit,\n        ),\n      [CLIENT_METHODS.terminal_kill]: (payload) =>\n        runHandler(coreHandlers.terminalKill, payload, CLIENT_METHODS.terminal_kill).pipe(\n          Effect.map((result) => result ?? {}),\n        ),\n      [CLIENT_METHODS.terminal_release]: (payload) =>\n        runHandler(coreHandlers.terminalRelease, payload, CLIENT_METHODS.terminal_release).pipe(\n          Effect.map((result) => result ?? {}),\n        ),\n    }),\n  );\n\n  yield* RpcServer.make(AcpRpcs.ClientRpcs).pipe(\n    Effect.provideService(RpcServer.Protocol, transport.serverProtocol),\n    Effect.provide(clientHandlerLayer),\n    Effect.forkScoped,\n  );\n\n  let nextRpcRequestId = 2 ** 32;\n  const rpc = yield* RpcClient.make(AcpRpcs.AgentRpcs, {\n    generateRequestId: () => RpcMessage.RequestId(nextRpcRequestId++),\n  }).pipe(Effect.provideService(RpcClient.Protocol, transport.clientProtocol));\n\n  return AcpClient.of({\n    raw: {\n      notifications: transport.incoming,\n      request: transport.request,\n      notify: transport.notify,\n    },\n    agent: {\n      initialize: (payload) =>\n        callRpc(AGENT_METHODS.initialize, rpc[AGENT_METHODS.initialize](payload)),\n      authenticate: (payload) =>\n        callRpc(AGENT_METHODS.authenticate, rpc[AGENT_METHODS.authenticate](payload)),\n      logout: (payload) => callRpc(AGENT_METHODS.logout, rpc[AGENT_METHODS.logout](payload)),\n      createSession: (payload) =>\n        callRpc(AGENT_METHODS.session_new, rpc[AGENT_METHODS.session_new](payload)),\n      loadSession: (payload) =>\n        callRpc(AGENT_METHODS.session_load, rpc[AGENT_METHODS.session_load](payload)),\n      listSessions: (payload) =>\n        callRpc(AGENT_METHODS.session_list, rpc[AGENT_METHODS.session_list](payload)),\n      forkSession: (payload) =>\n        callRpc(AGENT_METHODS.session_fork, rpc[AGENT_METHODS.session_fork](payload)),\n      resumeSession: (payload) =>\n        callRpc(AGENT_METHODS.session_resume, rpc[AGENT_METHODS.session_resume](payload)),\n      closeSession: (payload) =>\n        callRpc(AGENT_METHODS.session_close, rpc[AGENT_METHODS.session_close](payload)),\n      setSessionModel: (payload) =>\n        callRpc(AGENT_METHODS.session_set_model, rpc[AGENT_METHODS.session_set_model](payload)),\n      setSessionConfigOption: (payload) =>\n        callRpc(\n          AGENT_METHODS.session_set_config_option,\n          rpc[AGENT_METHODS.session_set_config_option](payload),\n        ),\n      prompt: (payload) =>\n        callRpc(AGENT_METHODS.session_prompt, rpc[AGENT_METHODS.session_prompt](payload)),\n      cancel: (payload) => transport.notify(AGENT_METHODS.session_cancel, payload),\n    },\n    handleRequestPermission: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.requestPermission = handler;\n        return Effect.void;\n      }),\n    handleElicitation: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.elicitation = handler;\n        return Effect.void;\n      }),\n    handleReadTextFile: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.readTextFile = handler;\n        return Effect.void;\n      }),\n    handleWriteTextFile: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.writeTextFile = handler;\n        return Effect.void;\n      }),\n    handleCreateTerminal: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.createTerminal = handler;\n        return Effect.void;\n      }),\n    handleTerminalOutput: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.terminalOutput = handler;\n        return Effect.void;\n      }),\n    handleTerminalWaitForExit: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.terminalWaitForExit = handler;\n        return Effect.void;\n      }),\n    handleTerminalKill: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.terminalKill = handler;\n        return Effect.void;\n      }),\n    handleTerminalRelease: (handler) =>\n      Effect.suspend(() => {\n        coreHandlers.terminalRelease = handler;\n        return Effect.void;\n      }),\n    handleSessionUpdate: (handler) =>\n      Effect.suspend(() => {\n        notificationHandlers.sessionUpdate.handlers.push(handler);\n        return flushBufferedNotifications(notificationHandlers.sessionUpdate);\n      }),\n    handleElicitationComplete: (handler) =>\n      Effect.suspend(() => {\n        notificationHandlers.elicitationComplete.handlers.push(handler);\n        return flushBufferedNotifications(notificationHandlers.elicitationComplete);\n      }),\n    handleUnknownExtRequest: (handler) =>\n      Effect.suspend(() => {\n        unknownExtRequestHandler = handler;\n        return Effect.void;\n      }),\n    handleUnknownExtNotification: (handler) =>\n      Effect.suspend(() => {\n        unknownExtNotificationHandler = handler;\n        return Effect.void;\n      }),\n    handleExtRequest: (method, payload, handler) =>\n      Effect.suspend(() => {\n        extRequestHandlers.set(method, decodeExtRequestRegistration(method, payload, handler));\n        return Effect.void;\n      }),\n    handleExtNotification: (method, payload, handler) =>\n      Effect.suspend(() => {\n        extNotificationHandlers.set(\n          method,\n          decodeExtNotificationRegistration(method, payload, handler),\n        );\n        return Effect.void;\n      }),\n  });\n});\n\nexport const layer = (stdio: Stdio.Stdio, options: AcpClientOptions = {}): Layer.Layer<AcpClient> =>\n  Layer.effect(AcpClient, make(stdio, options));\n\nexport const layerChildProcess = (\n  handle: ChildProcessSpawner.ChildProcessHandle,\n  options: AcpClientOptions = {},\n): Layer.Layer<AcpClient> => {\n  const stdio = makeChildStdio(handle);\n  const terminationError = makeTerminationError(handle);\n  return Layer.effect(AcpClient, make(stdio, options, terminationError));\n};\n","import type { ToolLifecycleItemType } from \"@t3tools/contracts\";\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value)\n    ? (value as Record<string, unknown>)\n    : undefined;\n}\n\nfunction asTrimmedString(value: unknown): string | undefined {\n  if (typeof value !== \"string\") {\n    return undefined;\n  }\n  const trimmed = value.trim();\n  return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizeCommandValue(value: unknown): string | undefined {\n  const direct = asTrimmedString(value);\n  if (direct) {\n    return direct;\n  }\n  if (!Array.isArray(value)) {\n    return undefined;\n  }\n  const parts: string[] = [];\n  for (const entry of value) {\n    const part = asTrimmedString(entry);\n    if (part !== undefined) {\n      parts.push(part);\n    }\n  }\n  return parts.length > 0 ? parts.join(\" \") : undefined;\n}\n\nfunction stripTrailingExitCode(value: string | undefined): string | undefined {\n  const trimmed = value?.trim();\n  if (!trimmed) {\n    return undefined;\n  }\n  const match = /^(?<output>[\\s\\S]*?)(?:\\s*<exited with exit code \\d+>)\\s*$/iu.exec(trimmed);\n  const output = match?.groups?.output?.trim() ?? trimmed;\n  return output.length > 0 ? output : undefined;\n}\n\nfunction extractCommandFromTitle(title: string | undefined): string | undefined {\n  if (!title) {\n    return undefined;\n  }\n  const backtickMatch = /`([^`]+)`/u.exec(title);\n  return backtickMatch?.[1]?.trim() || undefined;\n}\n\nfunction extractToolCommand(data: Record<string, unknown> | undefined, title: string | undefined) {\n  const item = asRecord(data?.item);\n  const itemInput = asRecord(item?.input);\n  const itemResult = asRecord(item?.result);\n  const rawInput = asRecord(data?.rawInput);\n  const candidates = [\n    normalizeCommandValue(item?.command),\n    normalizeCommandValue(itemInput?.command),\n    normalizeCommandValue(itemResult?.command),\n    normalizeCommandValue(data?.command),\n    normalizeCommandValue(rawInput?.command),\n  ];\n  const direct = candidates.find((candidate) => candidate !== undefined);\n  if (direct) {\n    return direct;\n  }\n  const executable = asTrimmedString(rawInput?.executable);\n  const args = normalizeCommandValue(rawInput?.args);\n  if (executable && args) {\n    return `${executable} ${args}`;\n  }\n  if (executable) {\n    return executable;\n  }\n  return extractCommandFromTitle(title);\n}\n\nfunction maybePathLike(value: string | undefined): string | undefined {\n  if (!value) {\n    return undefined;\n  }\n  if (\n    value.includes(\"/\") ||\n    value.includes(\"\\\\\") ||\n    value.startsWith(\".\") ||\n    /\\.(?:[a-z0-9]{1,12})$/iu.test(value)\n  ) {\n    return value;\n  }\n  return undefined;\n}\n\nfunction collectPaths(value: unknown, paths: string[], seen: Set<string>, depth: number): void {\n  if (depth > 4 || paths.length >= 8) {\n    return;\n  }\n  if (Array.isArray(value)) {\n    for (const entry of value) {\n      collectPaths(entry, paths, seen, depth + 1);\n      if (paths.length >= 8) {\n        return;\n      }\n    }\n    return;\n  }\n  const record = asRecord(value);\n  if (!record) {\n    return;\n  }\n  for (const key of [\"path\", \"filePath\", \"relativePath\", \"filename\", \"newPath\", \"oldPath\"]) {\n    const candidate = maybePathLike(asTrimmedString(record[key]));\n    if (!candidate || seen.has(candidate)) {\n      continue;\n    }\n    seen.add(candidate);\n    paths.push(candidate);\n    if (paths.length >= 8) {\n      return;\n    }\n  }\n  for (const nestedKey of [\"locations\", \"item\", \"input\", \"result\", \"rawInput\", \"data\", \"changes\"]) {\n    if (!(nestedKey in record)) {\n      continue;\n    }\n    collectPaths(record[nestedKey], paths, seen, depth + 1);\n    if (paths.length >= 8) {\n      return;\n    }\n  }\n}\n\nfunction extractPrimaryPath(data: Record<string, unknown> | undefined): string | undefined {\n  const paths: string[] = [];\n  collectPaths(data, paths, new Set<string>(), 0);\n  return paths[0];\n}\n\nfunction normalizeEquivalentValue(value: string | undefined): string | undefined {\n  const trimmed = asTrimmedString(value);\n  if (!trimmed) {\n    return undefined;\n  }\n  return trimmed\n    .replace(/\\s+/gu, \" \")\n    .replace(/\\s+(?:complete|completed|started)\\s*$/iu, \"\")\n    .trim();\n}\n\nfunction isEquivalent(left: string | undefined, right: string | undefined): boolean {\n  const normalizedLeft = normalizeEquivalentValue(left)?.toLowerCase();\n  const normalizedRight = normalizeEquivalentValue(right)?.toLowerCase();\n  return normalizedLeft !== undefined && normalizedLeft === normalizedRight;\n}\n\nfunction classifyToolAction(input: {\n  readonly itemType?: ToolLifecycleItemType | null | undefined;\n  readonly title?: string | undefined;\n  readonly data?: Record<string, unknown> | undefined;\n}): \"command\" | \"read\" | \"file_change\" | \"search\" | \"other\" {\n  const itemType = input.itemType ?? undefined;\n  const kind = asTrimmedString(input.data?.kind)?.toLowerCase();\n  const title = asTrimmedString(input.title)?.toLowerCase();\n  if (itemType === \"command_execution\" || kind === \"execute\" || title === \"terminal\") {\n    return \"command\";\n  }\n  if (kind === \"read\" || title === \"read file\") {\n    return \"read\";\n  }\n  if (\n    itemType === \"file_change\" ||\n    kind === \"edit\" ||\n    kind === \"move\" ||\n    kind === \"delete\" ||\n    kind === \"write\"\n  ) {\n    return \"file_change\";\n  }\n  if (itemType === \"web_search\" || kind === \"search\" || title === \"find\" || title === \"grep\") {\n    return \"search\";\n  }\n  return \"other\";\n}\n\nexport interface ToolActivityPresentationInput {\n  readonly itemType?: ToolLifecycleItemType | null | undefined;\n  readonly title?: string | null | undefined;\n  readonly detail?: string | null | undefined;\n  readonly data?: unknown;\n  readonly fallbackSummary?: string | null | undefined;\n}\n\nexport interface ToolActivityPresentation {\n  readonly summary: string;\n  readonly detail?: string | undefined;\n}\n\nexport function deriveToolActivityPresentation(\n  input: ToolActivityPresentationInput,\n): ToolActivityPresentation {\n  const title = asTrimmedString(input.title);\n  const detail = stripTrailingExitCode(asTrimmedString(input.detail));\n  const fallbackSummary = asTrimmedString(input.fallbackSummary) ?? \"Tool\";\n  const data = asRecord(input.data);\n  const command = extractToolCommand(data, title);\n  const primaryPath = extractPrimaryPath(data);\n  const action = classifyToolAction({\n    itemType: input.itemType,\n    title,\n    data,\n  });\n\n  if (action === \"command\") {\n    return {\n      summary: \"Ran command\",\n      ...(command ? { detail: command } : {}),\n    };\n  }\n\n  if (action === \"read\") {\n    if (primaryPath) {\n      return {\n        summary: \"Read file\",\n        detail: primaryPath,\n      };\n    }\n    return {\n      summary: \"Read file\",\n    };\n  }\n\n  if (action === \"file_change\") {\n    return {\n      summary: \"Changed files\",\n      ...(primaryPath ? { detail: primaryPath } : {}),\n    };\n  }\n\n  if (action === \"search\") {\n    const query =\n      asTrimmedString(asRecord(data?.rawInput)?.query) ??\n      asTrimmedString(asRecord(data?.rawInput)?.pattern) ??\n      asTrimmedString(asRecord(data?.rawInput)?.searchTerm);\n    return {\n      summary: \"Searched files\",\n      ...(query ? { detail: query } : {}),\n    };\n  }\n\n  if (detail && !isEquivalent(detail, title) && !isEquivalent(detail, fallbackSummary)) {\n    return {\n      summary: title ?? fallbackSummary,\n      detail,\n    };\n  }\n\n  return {\n    summary: title ?? fallbackSummary,\n  };\n}\n","import * as Clock from \"effect/Clock\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\nimport { deriveToolActivityPresentation } from \"@t3tools/shared/toolActivity\";\nimport type { ToolLifecycleItemType } from \"@t3tools/contracts\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isSessionModelState(value: unknown): value is EffectAcpSchema.SessionModelState {\n  if (!isRecord(value) || typeof value.currentModelId !== \"string\") {\n    return false;\n  }\n  if (!Array.isArray(value.availableModels)) {\n    return false;\n  }\n  return value.availableModels.every(\n    (model) =>\n      isRecord(model) &&\n      typeof model.modelId === \"string\" &&\n      typeof model.name === \"string\" &&\n      (model.description === undefined ||\n        model.description === null ||\n        typeof model.description === \"string\"),\n  );\n}\n\nfunction isSessionModeState(value: unknown): value is EffectAcpSchema.SessionModeState {\n  if (!isRecord(value) || typeof value.currentModeId !== \"string\") {\n    return false;\n  }\n  if (!Array.isArray(value.availableModes)) {\n    return false;\n  }\n  return value.availableModes.every(\n    (mode) =>\n      isRecord(mode) &&\n      typeof mode.id === \"string\" &&\n      typeof mode.name === \"string\" &&\n      (mode.description === undefined || typeof mode.description === \"string\"),\n  );\n}\n\nexport interface AcpSessionMode {\n  readonly id: string;\n  readonly name: string;\n  readonly description?: string;\n}\n\nexport interface AcpSessionModeState {\n  readonly currentModeId: string;\n  readonly availableModes: ReadonlyArray<AcpSessionMode>;\n}\n\nexport interface AcpToolCallState {\n  readonly toolCallId: string;\n  readonly kind?: string;\n  readonly title?: string;\n  readonly status?: \"pending\" | \"inProgress\" | \"completed\" | \"failed\";\n  readonly command?: string;\n  readonly detail?: string;\n  readonly data: Record<string, unknown>;\n}\n\nexport interface AcpPlanUpdate {\n  readonly explanation?: string | null;\n  readonly plan: ReadonlyArray<{\n    readonly step: string;\n    readonly status: \"pending\" | \"inProgress\" | \"completed\";\n  }>;\n}\n\nexport interface AcpPermissionRequest {\n  readonly kind: string | \"unknown\";\n  readonly detail?: string;\n  readonly toolCall?: AcpToolCallState;\n}\n\nexport type AcpParsedSessionEvent =\n  | {\n      readonly _tag: \"ModeChanged\";\n      readonly modeId: string;\n    }\n  | {\n      readonly _tag: \"AssistantItemStarted\";\n      readonly itemId: string;\n    }\n  | {\n      readonly _tag: \"AssistantItemCompleted\";\n      readonly itemId: string;\n    }\n  | {\n      readonly _tag: \"PlanUpdated\";\n      readonly payload: AcpPlanUpdate;\n      readonly rawPayload: unknown;\n    }\n  | {\n      readonly _tag: \"ToolCallUpdated\";\n      readonly toolCall: AcpToolCallState;\n      readonly rawPayload: unknown;\n    }\n  | {\n      readonly _tag: \"ContentDelta\";\n      readonly itemId?: string;\n      readonly text: string;\n      readonly rawPayload: unknown;\n    };\n\ntype AcpSessionSetupResponse =\n  | EffectAcpSchema.LoadSessionResponse\n  | EffectAcpSchema.NewSessionResponse\n  | EffectAcpSchema.ResumeSessionResponse;\n\ntype AcpToolCallUpdate = Extract<\n  EffectAcpSchema.SessionNotification[\"update\"],\n  { readonly sessionUpdate: \"tool_call\" | \"tool_call_update\" }\n>;\n\nexport function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {\n  const configOptions = sessionResponse.configOptions;\n  if (!configOptions) return undefined;\n  for (const opt of configOptions) {\n    if (opt.category === \"model\" && opt.id.trim().length > 0) {\n      return opt.id.trim();\n    }\n  }\n  return undefined;\n}\n\nexport function findSessionConfigOption(\n  configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,\n  configId: string,\n): EffectAcpSchema.SessionConfigOption | undefined {\n  if (!configOptions) {\n    return undefined;\n  }\n  const normalizedConfigId = configId.trim();\n  if (!normalizedConfigId) {\n    return undefined;\n  }\n  return configOptions.find((option) => option.id.trim() === normalizedConfigId);\n}\n\nexport function collectSessionConfigOptionValues(\n  configOption: EffectAcpSchema.SessionConfigOption,\n): ReadonlyArray<string> {\n  if (configOption.type !== \"select\") {\n    return [];\n  }\n  return configOption.options.flatMap((entry) =>\n    \"value\" in entry ? [entry.value] : entry.options.map((option) => option.value),\n  );\n}\n\nexport function parseSessionModeState(\n  sessionResponse: AcpSessionSetupResponse,\n): AcpSessionModeState | undefined {\n  const modes = sessionResponse.modes;\n  if (!modes) return undefined;\n  const currentModeId = modes.currentModeId.trim();\n  if (!currentModeId) {\n    return undefined;\n  }\n  const availableModes: Array<AcpSessionMode> = [];\n  for (const mode of modes.availableModes) {\n    const id = mode.id.trim();\n    const name = mode.name.trim();\n    if (!id || !name) {\n      continue;\n    }\n    const description = mode.description?.trim() || undefined;\n    availableModes.push(\n      description !== undefined\n        ? ({ id, name, description } satisfies AcpSessionMode)\n        : ({ id, name } satisfies AcpSessionMode),\n    );\n  }\n  if (availableModes.length === 0) {\n    return undefined;\n  }\n  return {\n    currentModeId,\n    availableModes,\n  };\n}\n\nfunction normalizePlanStepStatus(raw: unknown): \"pending\" | \"inProgress\" | \"completed\" {\n  switch (raw) {\n    case \"completed\":\n      return \"completed\";\n    case \"in_progress\":\n    case \"inProgress\":\n      return \"inProgress\";\n    default:\n      return \"pending\";\n  }\n}\n\nfunction normalizeToolCallStatus(\n  raw: unknown,\n  fallback?: \"pending\" | \"inProgress\" | \"completed\" | \"failed\",\n): \"pending\" | \"inProgress\" | \"completed\" | \"failed\" | undefined {\n  switch (raw) {\n    case \"pending\":\n      return \"pending\";\n    case \"in_progress\":\n    case \"inProgress\":\n      return \"inProgress\";\n    case \"completed\":\n      return \"completed\";\n    case \"failed\":\n      return \"failed\";\n    default:\n      return fallback;\n  }\n}\n\nfunction normalizeCommandValue(value: unknown): string | undefined {\n  if (typeof value === \"string\" && value.trim().length > 0) {\n    return value.trim();\n  }\n  if (!Array.isArray(value)) {\n    return undefined;\n  }\n  const parts: Array<string> = [];\n  for (const entry of value) {\n    if (typeof entry === \"string\") {\n      const part = entry.trim();\n      if (part.length > 0) {\n        parts.push(part);\n      }\n    }\n  }\n  return parts.length > 0 ? parts.join(\" \") : undefined;\n}\n\nfunction extractCommandFromTitle(title: string | undefined): string | undefined {\n  if (!title) {\n    return undefined;\n  }\n  const match = /`([^`]+)`/.exec(title);\n  return match?.[1]?.trim() || undefined;\n}\n\nfunction extractToolCallCommand(rawInput: unknown, title: string | undefined): string | undefined {\n  if (isRecord(rawInput)) {\n    const directCommand = normalizeCommandValue(rawInput.command);\n    if (directCommand) {\n      return directCommand;\n    }\n    const executable = typeof rawInput.executable === \"string\" ? rawInput.executable.trim() : \"\";\n    const args = normalizeCommandValue(rawInput.args);\n    if (executable && args) {\n      return `${executable} ${args}`;\n    }\n    if (executable) {\n      return executable;\n    }\n  }\n  return extractCommandFromTitle(title);\n}\n\nfunction extractTextContentFromToolCallContent(\n  content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,\n): string | undefined {\n  if (!content) return undefined;\n  const chunks: Array<string> = [];\n  for (const entry of content) {\n    if (entry.type !== \"content\") {\n      continue;\n    }\n    const nestedContent = entry.content;\n    if (nestedContent.type !== \"text\") {\n      continue;\n    }\n    const text = nestedContent.text.trim();\n    if (text.length > 0) {\n      chunks.push(text);\n    }\n  }\n  return chunks.length > 0 ? chunks.join(\"\\n\") : undefined;\n}\n\nfunction normalizeToolKind(kind: unknown): string | undefined {\n  return typeof kind === \"string\" && kind.trim().length > 0 ? kind.trim() : undefined;\n}\n\nfunction canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {\n  switch (kind) {\n    case \"execute\":\n      return \"command_execution\";\n    case \"edit\":\n    case \"delete\":\n    case \"move\":\n      return \"file_change\";\n    case \"search\":\n    case \"fetch\":\n      return \"web_search\";\n    default:\n      return \"dynamic_tool_call\";\n  }\n}\n\nfunction makeToolCallState(\n  input: {\n    readonly toolCallId: string;\n    readonly title?: string | null | undefined;\n    readonly kind?: EffectAcpSchema.ToolKind | null | undefined;\n    readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;\n    readonly rawInput?: unknown;\n    readonly rawOutput?: unknown;\n    readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;\n    readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;\n  },\n  options?: {\n    readonly fallbackStatus?: \"pending\" | \"inProgress\" | \"completed\" | \"failed\";\n  },\n): AcpToolCallState | undefined {\n  const toolCallId = input.toolCallId.trim();\n  if (!toolCallId) {\n    return undefined;\n  }\n  const title = input.title?.trim() || undefined;\n  const command = extractToolCallCommand(input.rawInput, title);\n  const textContent = extractTextContentFromToolCallContent(input.content);\n  const normalizedTitle =\n    title && title.toLowerCase() !== \"terminal\" && title.toLowerCase() !== \"tool call\"\n      ? title\n      : undefined;\n  const data: Record<string, unknown> = { toolCallId };\n  const kind = normalizeToolKind(input.kind);\n  if (kind) {\n    data.kind = kind;\n  }\n  if (command) {\n    data.command = command;\n  }\n  if (input.rawInput !== undefined) {\n    data.rawInput = input.rawInput;\n  }\n  if (input.rawOutput !== undefined) {\n    data.rawOutput = input.rawOutput;\n  }\n  if (input.content !== undefined) {\n    data.content = input.content;\n  }\n  if (input.locations !== undefined) {\n    data.locations = input.locations;\n  }\n  const fallbackDetail = command ?? normalizedTitle ?? textContent;\n  const hasPresentationSeed =\n    title !== undefined ||\n    kind !== undefined ||\n    command !== undefined ||\n    normalizedTitle !== undefined ||\n    textContent !== undefined;\n  const presentation = hasPresentationSeed\n    ? deriveToolActivityPresentation({\n        itemType: canonicalItemTypeFromAcpToolKind(kind),\n        title,\n        detail: fallbackDetail,\n        data,\n        fallbackSummary: title ?? \"Tool\",\n      })\n    : undefined;\n  const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);\n  return {\n    toolCallId,\n    ...(kind ? { kind } : {}),\n    ...(presentation?.summary ? { title: presentation.summary } : {}),\n    ...(status ? { status } : {}),\n    ...(command ? { command } : {}),\n    ...(presentation?.detail ? { detail: presentation.detail } : {}),\n    data,\n  };\n}\n\nfunction parseTypedToolCallState(\n  event: AcpToolCallUpdate,\n  options?: {\n    readonly fallbackStatus?: \"pending\" | \"inProgress\" | \"completed\" | \"failed\";\n  },\n): AcpToolCallState | undefined {\n  return makeToolCallState(\n    {\n      toolCallId: event.toolCallId,\n      title: event.title,\n      kind: event.kind,\n      status: event.status,\n      rawInput: event.rawInput,\n      rawOutput: event.rawOutput,\n      content: event.content,\n      locations: event.locations,\n    },\n    options,\n  );\n}\n\nexport function mergeToolCallState(\n  previous: AcpToolCallState | undefined,\n  next: AcpToolCallState,\n): AcpToolCallState {\n  const nextKind = typeof next.data.kind === \"string\" ? next.data.kind : undefined;\n  const kind = nextKind ?? previous?.kind;\n  const title = next.title ?? previous?.title;\n  const status = next.status ?? previous?.status;\n  const command = next.command ?? previous?.command;\n  const detail = next.detail ?? previous?.detail;\n  return {\n    toolCallId: next.toolCallId,\n    ...(kind ? { kind } : {}),\n    ...(title ? { title } : {}),\n    ...(status ? { status } : {}),\n    ...(command ? { command } : {}),\n    ...(detail ? { detail } : {}),\n    data: {\n      ...previous?.data,\n      ...next.data,\n    },\n  };\n}\n\nexport function parsePermissionRequest(\n  params: EffectAcpSchema.RequestPermissionRequest,\n): AcpPermissionRequest {\n  const toolCall = makeToolCallState(\n    {\n      toolCallId: params.toolCall.toolCallId,\n      title: params.toolCall.title,\n      kind: params.toolCall.kind,\n      status: params.toolCall.status,\n      rawInput: params.toolCall.rawInput,\n      rawOutput: params.toolCall.rawOutput,\n      content: params.toolCall.content,\n      locations: params.toolCall.locations,\n    },\n    { fallbackStatus: \"pending\" },\n  );\n  const kind = normalizeToolKind(params.toolCall.kind) ?? \"unknown\";\n  const detail =\n    toolCall?.command ??\n    toolCall?.title ??\n    toolCall?.detail ??\n    (typeof params.sessionId === \"string\" ? `Session ${params.sessionId}` : undefined);\n  return {\n    kind,\n    ...(detail ? { detail } : {}),\n    ...(toolCall ? { toolCall } : {}),\n  };\n}\n\nexport function sessionUpdateIsReplay(params: EffectAcpSchema.SessionNotification): boolean {\n  const meta = params._meta;\n  return isRecord(meta) && meta.isReplay === true;\n}\n\nexport interface SessionLoadGate {\n  readonly active: boolean;\n  readonly lastActivityAtMillis: number | undefined;\n  readonly idleGap: Duration.Duration;\n  readonly initializeResult: EffectAcpSchema.InitializeResponse;\n}\n\nexport const waitForSessionLoadReplayIdle = (input: {\n  readonly gateRef: Ref.Ref<Option.Option<SessionLoadGate>>;\n}): Effect.Effect<EffectAcpSchema.LoadSessionResponse, never> =>\n  Effect.gen(function* () {\n    const pollInterval = Duration.millis(25);\n    while (true) {\n      const gate = yield* Ref.get(input.gateRef);\n      if (\n        Option.isSome(gate) &&\n        gate.value.active &&\n        gate.value.lastActivityAtMillis !== undefined\n      ) {\n        const idleGapMillis = Duration.toMillis(gate.value.idleGap);\n        const nowMillis = yield* Clock.currentTimeMillis;\n        if (nowMillis - gate.value.lastActivityAtMillis >= idleGapMillis) {\n          return syntheticLoadSessionResponseFromInitialize(gate.value.initializeResult);\n        }\n      }\n      yield* Effect.sleep(pollInterval);\n    }\n  });\n\nexport function syntheticLoadSessionResponseFromInitialize(\n  initializeResult: EffectAcpSchema.InitializeResponse,\n): EffectAcpSchema.LoadSessionResponse {\n  const meta = initializeResult._meta;\n  const modelState = isRecord(meta) ? meta.modelState : undefined;\n  const modeState = isRecord(meta) ? meta.modeState : undefined;\n  const models = isSessionModelState(modelState) ? modelState : undefined;\n  const modes = isSessionModeState(modeState) ? modeState : undefined;\n\n  return {\n    ...(models ? { models } : {}),\n    ...(modes ? { modes } : {}),\n    _meta: {\n      t3SessionLoadReady: \"replay_idle\",\n    },\n  };\n}\n\nexport function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {\n  readonly modeId?: string;\n  readonly events: ReadonlyArray<AcpParsedSessionEvent>;\n} {\n  const upd = params.update;\n  const events: Array<AcpParsedSessionEvent> = [];\n  let modeId: string | undefined;\n\n  switch (upd.sessionUpdate) {\n    case \"current_mode_update\": {\n      modeId = upd.currentModeId.trim();\n      if (modeId) {\n        events.push({\n          _tag: \"ModeChanged\",\n          modeId,\n        });\n      }\n      break;\n    }\n    case \"plan\": {\n      const plan = upd.entries.map((entry, index) => ({\n        step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,\n        status: normalizePlanStepStatus(entry.status),\n      }));\n      if (plan.length > 0) {\n        events.push({\n          _tag: \"PlanUpdated\",\n          payload: {\n            plan,\n          },\n          rawPayload: params,\n        });\n      }\n      break;\n    }\n    case \"tool_call\": {\n      const toolCall = parseTypedToolCallState(upd, {\n        fallbackStatus: \"pending\",\n      });\n      if (toolCall) {\n        events.push({\n          _tag: \"ToolCallUpdated\",\n          toolCall,\n          rawPayload: params,\n        });\n      }\n      break;\n    }\n    case \"tool_call_update\": {\n      const toolCall = parseTypedToolCallState(upd);\n      if (toolCall) {\n        events.push({\n          _tag: \"ToolCallUpdated\",\n          toolCall,\n          rawPayload: params,\n        });\n      }\n      break;\n    }\n    case \"agent_message_chunk\": {\n      if (upd.content.type === \"text\" && upd.content.text.length > 0) {\n        events.push({\n          _tag: \"ContentDelta\",\n          text: upd.content.text,\n          rawPayload: params,\n        });\n      }\n      break;\n    }\n    default:\n      break;\n  }\n\n  return { ...(modeId !== undefined ? { modeId } : {}), events };\n}\n","import * as Cause from \"effect/Cause\";\nimport * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as EffectAcpClient from \"effect-acp/client\";\nimport * as EffectAcpErrors from \"effect-acp/errors\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\nimport type * as EffectAcpProtocol from \"effect-acp/protocol\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\nimport {\n  collectSessionConfigOptionValues,\n  extractModelConfigId,\n  findSessionConfigOption,\n  mergeToolCallState,\n  parseSessionModeState,\n  parseSessionUpdateEvent,\n  sessionUpdateIsReplay,\n  waitForSessionLoadReplayIdle,\n  type SessionLoadGate,\n  type AcpParsedSessionEvent,\n  type AcpSessionModeState,\n  type AcpToolCallState,\n} from \"./AcpRuntimeModel.ts\";\n\nfunction formatConfigOptionValue(value: string | boolean): string {\n  return JSON.stringify(value);\n}\n\nexport interface AcpSessionEventStreamBarrier {\n  readonly _tag: \"EventStreamBarrier\";\n  readonly acknowledge: Deferred.Deferred<void>;\n}\n\nexport type AcpSessionRuntimeEvent = AcpParsedSessionEvent | AcpSessionEventStreamBarrier;\n\nconst defaultSessionLoadTimeout = Duration.seconds(90);\nconst defaultSessionLoadReplayIdleGap = Duration.seconds(2);\n\nexport interface AcpSpawnInput {\n  readonly command: string;\n  readonly args: ReadonlyArray<string>;\n  readonly cwd?: string;\n  readonly env?: NodeJS.ProcessEnv;\n}\n\nexport interface AcpSessionRuntimeOptions {\n  readonly spawn: AcpSpawnInput;\n  readonly cwd: string;\n  readonly resumeSessionId?: string;\n  readonly sessionLoadTimeout?: Duration.Input;\n  readonly sessionLoadReplayIdleGap?: Duration.Input;\n  readonly clientCapabilities?: EffectAcpSchema.InitializeRequest[\"clientCapabilities\"];\n  readonly clientInfo: {\n    readonly name: string;\n    readonly version: string;\n  };\n  readonly authMethodId: string;\n  readonly mcpServers?: ReadonlyArray<EffectAcpSchema.McpServer>;\n  readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;\n  readonly protocolLogging?: {\n    readonly logIncoming?: boolean;\n    readonly logOutgoing?: boolean;\n    readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;\n  };\n}\n\nexport interface AcpSessionRequestLogEvent {\n  readonly method: string;\n  readonly payload: unknown;\n  readonly status: \"started\" | \"succeeded\" | \"failed\";\n  readonly result?: unknown;\n  readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;\n}\n\nexport interface AcpSessionRuntimeStartResult {\n  readonly sessionId: string;\n  readonly initializeResult: EffectAcpSchema.InitializeResponse;\n  readonly sessionSetupResult:\n    | EffectAcpSchema.LoadSessionResponse\n    | EffectAcpSchema.NewSessionResponse\n    | EffectAcpSchema.ResumeSessionResponse;\n  readonly modelConfigId: string | undefined;\n}\n\nexport class AcpSessionRuntime extends Context.Service<\n  AcpSessionRuntime,\n  {\n    /**\n     * Registers a handler for `session/request_permission`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/request_permission\n     */\n    readonly handleRequestPermission: EffectAcpClient.AcpClient[\"Service\"][\"handleRequestPermission\"];\n    /**\n     * Registers a handler for `session/elicitation`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/elicitation\n     */\n    readonly handleElicitation: EffectAcpClient.AcpClient[\"Service\"][\"handleElicitation\"];\n    /**\n     * Registers a handler for `fs/read_text_file`.\n     * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file\n     */\n    readonly handleReadTextFile: EffectAcpClient.AcpClient[\"Service\"][\"handleReadTextFile\"];\n    /**\n     * Registers a handler for `fs/write_text_file`.\n     * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file\n     */\n    readonly handleWriteTextFile: EffectAcpClient.AcpClient[\"Service\"][\"handleWriteTextFile\"];\n    /**\n     * Registers a handler for `terminal/create`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/create\n     */\n    readonly handleCreateTerminal: EffectAcpClient.AcpClient[\"Service\"][\"handleCreateTerminal\"];\n    /**\n     * Registers a handler for `terminal/output`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/output\n     */\n    readonly handleTerminalOutput: EffectAcpClient.AcpClient[\"Service\"][\"handleTerminalOutput\"];\n    /**\n     * Registers a handler for `terminal/wait_for_exit`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit\n     */\n    readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient[\"Service\"][\"handleTerminalWaitForExit\"];\n    /**\n     * Registers a handler for `terminal/kill`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/kill\n     */\n    readonly handleTerminalKill: EffectAcpClient.AcpClient[\"Service\"][\"handleTerminalKill\"];\n    /**\n     * Registers a handler for `terminal/release`.\n     * @see https://agentclientprotocol.com/protocol/schema#terminal/release\n     */\n    readonly handleTerminalRelease: EffectAcpClient.AcpClient[\"Service\"][\"handleTerminalRelease\"];\n    /**\n     * Registers a handler for `session/update`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/update\n     */\n    readonly handleSessionUpdate: EffectAcpClient.AcpClient[\"Service\"][\"handleSessionUpdate\"];\n    /**\n     * Registers a handler for `session/elicitation/complete`.\n     * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete\n     */\n    readonly handleElicitationComplete: EffectAcpClient.AcpClient[\"Service\"][\"handleElicitationComplete\"];\n    /**\n     * Registers a fallback extension request handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleUnknownExtRequest: EffectAcpClient.AcpClient[\"Service\"][\"handleUnknownExtRequest\"];\n    /**\n     * Registers a fallback extension notification handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleUnknownExtNotification: EffectAcpClient.AcpClient[\"Service\"][\"handleUnknownExtNotification\"];\n    /**\n     * Registers a typed extension request handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleExtRequest: EffectAcpClient.AcpClient[\"Service\"][\"handleExtRequest\"];\n    /**\n     * Registers a typed extension notification handler.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly handleExtNotification: EffectAcpClient.AcpClient[\"Service\"][\"handleExtNotification\"];\n    /**\n     * Initializes the ACP connection, authenticates, and loads, resumes, or creates the session.\n     * Concurrent calls share the same in-flight startup and a failed startup may be retried.\n     */\n    readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;\n    /** Stream of parsed ACP session events emitted after startup. */\n    readonly getEvents: () => Stream.Stream<AcpSessionRuntimeEvent, never>;\n    /** Waits until the current event consumer has processed every queued event. */\n    readonly drainEvents: Effect.Effect<void>;\n    /** Latest mode state observed from session setup and `session/update` notifications. */\n    readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;\n    /** Latest configuration options observed from session setup and configuration writes. */\n    readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;\n    /**\n     * Sends a prompt turn to the active session.\n     * @see https://agentclientprotocol.com/protocol/schema#session/prompt\n     */\n    readonly prompt: (\n      payload: Omit<EffectAcpSchema.PromptRequest, \"sessionId\">,\n    ) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;\n    /**\n     * Sends a real ACP `session/cancel` notification for the active session.\n     * @see https://agentclientprotocol.com/protocol/schema#session/cancel\n     */\n    readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;\n    /**\n     * Selects the active mode through the negotiated `mode` configuration option.\n     * This is a no-op when the requested mode is already active.\n     * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option\n     */\n    readonly setMode: (\n      modeId: string,\n    ) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;\n    /**\n     * Updates a session configuration option and the runtime configuration snapshot.\n     * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option\n     */\n    readonly setConfigOption: (\n      configId: string,\n      value: string | boolean,\n    ) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;\n    /**\n     * Selects the base model through the negotiated model configuration option.\n     * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option\n     */\n    readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;\n    /**\n     * Selects the active model through the unstable ACP `session/set_model` capability.\n     * @see https://agentclientprotocol.com/protocol/schema#session/set_model\n     */\n    readonly setSessionModel: (\n      modelId: string,\n    ) => Effect.Effect<EffectAcpSchema.SetSessionModelResponse, EffectAcpErrors.AcpError>;\n    /**\n     * Sends a generic ACP extension request and records it through the request logger.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly request: (\n      method: string,\n      payload: unknown,\n    ) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;\n    /**\n     * Sends a generic ACP extension notification.\n     * @see https://agentclientprotocol.com/protocol/extensibility\n     */\n    readonly notify: (\n      method: string,\n      payload: unknown,\n    ) => Effect.Effect<void, EffectAcpErrors.AcpError>;\n  }\n>()(\"t3/provider/acp/AcpSessionRuntime\") {}\n\ninterface AcpStartedState extends AcpSessionRuntimeStartResult {}\n\ntype AcpStartState =\n  | { readonly _tag: \"NotStarted\" }\n  | {\n      readonly _tag: \"Starting\";\n      readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;\n    }\n  | { readonly _tag: \"Started\"; readonly result: AcpStartedState };\n\ninterface AcpAssistantSegmentState {\n  readonly nextSegmentIndex: number;\n  readonly activeItemId?: string;\n}\n\ninterface EnsureActiveAssistantSegmentResult {\n  readonly itemId: string;\n  readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: \"AssistantItemStarted\" }>;\n}\n\nexport const make = (\n  options: AcpSessionRuntimeOptions,\n): Effect.Effect<\n  AcpSessionRuntime[\"Service\"],\n  EffectAcpErrors.AcpError,\n  ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope\n> =>\n  Effect.gen(function* () {\n    const crypto = yield* Crypto.Crypto;\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const runtimeScope = yield* Scope.Scope;\n    const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();\n    const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);\n    const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());\n    const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new EffectAcpErrors.AcpTransportError({\n            detail: \"Failed to generate an ACP assistant item runtime identifier.\",\n            cause,\n          }),\n      ),\n    );\n    const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });\n    const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));\n    const startStateRef = yield* Ref.make<AcpStartState>({ _tag: \"NotStarted\" });\n    const promptSerializationSemaphore = yield* Semaphore.make(1);\n    const activePromptFiberRef = yield* Ref.make<\n      Option.Option<Fiber.Fiber<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>>\n    >(Option.none());\n    const sessionLoadGateRef = yield* Ref.make<Option.Option<SessionLoadGate>>(Option.none());\n\n    const logRequest = (event: AcpSessionRequestLogEvent) =>\n      options.requestLogger ? options.requestLogger(event) : Effect.void;\n\n    const runLoggedRequest = <A>(\n      method: string,\n      payload: unknown,\n      effect: Effect.Effect<A, EffectAcpErrors.AcpError>,\n    ): Effect.Effect<A, EffectAcpErrors.AcpError> =>\n      logRequest({ method, payload, status: \"started\" }).pipe(\n        Effect.flatMap(() =>\n          effect.pipe(\n            Effect.tap((result) =>\n              logRequest({\n                method,\n                payload,\n                status: \"succeeded\",\n                result,\n              }),\n            ),\n            Effect.onError((cause) =>\n              logRequest({\n                method,\n                payload,\n                status: \"failed\",\n                cause,\n              }),\n            ),\n          ),\n        ),\n      );\n\n    const spawnCommand = yield* resolveSpawnCommand(\n      options.spawn.command,\n      options.spawn.args,\n      options.spawn.env ? { env: options.spawn.env, extendEnv: true } : {},\n    );\n    const child = yield* spawner\n      .spawn(\n        ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n          ...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),\n          ...(options.spawn.env ? { env: options.spawn.env, extendEnv: true } : {}),\n          shell: spawnCommand.shell,\n        }),\n      )\n      .pipe(\n        Effect.provideService(Scope.Scope, runtimeScope),\n        Effect.mapError(\n          (cause) =>\n            new EffectAcpErrors.AcpSpawnError({\n              command: options.spawn.command,\n              cause,\n            }),\n        ),\n      );\n\n    const acpContext = yield* Layer.build(\n      EffectAcpClient.layerChildProcess(child, {\n        ...(options.protocolLogging?.logIncoming !== undefined\n          ? { logIncoming: options.protocolLogging.logIncoming }\n          : {}),\n        ...(options.protocolLogging?.logOutgoing !== undefined\n          ? { logOutgoing: options.protocolLogging.logOutgoing }\n          : {}),\n        ...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),\n      }),\n    ).pipe(Effect.provideService(Scope.Scope, runtimeScope));\n\n    const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));\n\n    yield* acp.handleSessionUpdate((notification) =>\n      Effect.gen(function* () {\n        const gate = yield* Ref.get(sessionLoadGateRef);\n        if (Option.isSome(gate) && gate.value.active) {\n          const lastActivityAtMillis = yield* Clock.currentTimeMillis;\n          yield* Ref.set(\n            sessionLoadGateRef,\n            Option.some({\n              ...gate.value,\n              lastActivityAtMillis,\n            }),\n          );\n          return;\n        }\n        if (sessionUpdateIsReplay(notification)) {\n          return;\n        }\n        const startState = yield* Ref.get(startStateRef);\n        // One runtime projects one root ACP session. Child-session updates need\n        // explicit lineage routing and must never be flattened into this stream.\n        if (\n          startState._tag !== \"Started\" ||\n          notification.sessionId !== startState.result.sessionId\n        ) {\n          return;\n        }\n        yield* handleSessionUpdate({\n          queue: eventQueue,\n          modeStateRef,\n          toolCallsRef,\n          assistantSegmentRef,\n          assistantItemRuntimeId,\n          params: notification,\n        });\n      }),\n    );\n    const initializeClientCapabilities = {\n      fs: {\n        readTextFile: false,\n        writeTextFile: false,\n        ...options.clientCapabilities?.fs,\n      },\n      terminal: options.clientCapabilities?.terminal ?? false,\n      ...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),\n      ...(options.clientCapabilities?.elicitation\n        ? { elicitation: options.clientCapabilities.elicitation }\n        : {}),\n      ...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),\n    } satisfies NonNullable<EffectAcpSchema.InitializeRequest[\"clientCapabilities\"]>;\n\n    const getStartedState = Effect.gen(function* () {\n      const state = yield* Ref.get(startStateRef);\n      if (state._tag === \"Started\") {\n        return state.result;\n      }\n      return yield* new EffectAcpErrors.AcpTransportError({\n        detail: \"ACP session runtime has not been started\",\n        cause: \"ACP session runtime has not been started\",\n      });\n    });\n\n    const validateConfigOptionValue = (\n      configId: string,\n      value: string | boolean,\n    ): Effect.Effect<void, EffectAcpErrors.AcpError> =>\n      Effect.gen(function* () {\n        const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);\n        if (!configOption) {\n          return;\n        }\n        if (configOption.type === \"boolean\") {\n          if (typeof value === \"boolean\") {\n            return;\n          }\n          return yield* new EffectAcpErrors.AcpRequestError({\n            code: -32602,\n            errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option \"${configOption.id}\": expected boolean`,\n            data: {\n              configId: configOption.id,\n              expectedType: \"boolean\",\n              receivedValue: value,\n            },\n          });\n        }\n        if (typeof value !== \"string\") {\n          return yield* new EffectAcpErrors.AcpRequestError({\n            code: -32602,\n            errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option \"${configOption.id}\": expected string`,\n            data: {\n              configId: configOption.id,\n              expectedType: \"string\",\n              receivedValue: value,\n            },\n          });\n        }\n        const allowedValues = collectSessionConfigOptionValues(configOption);\n        if (allowedValues.includes(value)) {\n          return;\n        }\n        return yield* new EffectAcpErrors.AcpRequestError({\n          code: -32602,\n          errorMessage: `Invalid value ${formatConfigOptionValue(value)} for session config option \"${configOption.id}\": expected one of ${allowedValues.join(\", \")}`,\n          data: {\n            configId: configOption.id,\n            allowedValues,\n            receivedValue: value,\n          },\n        });\n      });\n\n    const updateConfigOptions = (\n      response:\n        | EffectAcpSchema.SetSessionConfigOptionResponse\n        | EffectAcpSchema.LoadSessionResponse\n        | EffectAcpSchema.NewSessionResponse\n        | EffectAcpSchema.ResumeSessionResponse,\n    ): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));\n\n    const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>\n      Ref.update(modeStateRef, (current) =>\n        current ? { ...current, currentModeId: modeId } : current,\n      );\n\n    const setConfigOption = (\n      configId: string,\n      value: string | boolean,\n    ): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>\n      validateConfigOptionValue(configId, value).pipe(\n        Effect.flatMap(() => getStartedState),\n        Effect.flatMap((started) =>\n          Ref.get(configOptionsRef).pipe(\n            Effect.flatMap((configOptions) => {\n              const existing = findSessionConfigOption(configOptions, configId);\n              if (existing && configOptionCurrentValueMatches(existing, value)) {\n                return Effect.succeed({\n                  configOptions,\n                } satisfies EffectAcpSchema.SetSessionConfigOptionResponse);\n              }\n              const requestPayload =\n                typeof value === \"boolean\"\n                  ? ({\n                      sessionId: started.sessionId,\n                      configId,\n                      type: \"boolean\",\n                      value,\n                    } satisfies EffectAcpSchema.SetSessionConfigOptionRequest)\n                  : ({\n                      sessionId: started.sessionId,\n                      configId,\n                      value: String(value),\n                    } satisfies EffectAcpSchema.SetSessionConfigOptionRequest);\n              return runLoggedRequest(\n                \"session/set_config_option\",\n                requestPayload,\n                acp.agent.setSessionConfigOption(requestPayload),\n              ).pipe(Effect.tap((response) => updateConfigOptions(response)));\n            }),\n          ),\n        ),\n      );\n\n    const startOnce = Effect.gen(function* () {\n      const initializePayload = {\n        protocolVersion: 1,\n        clientCapabilities: initializeClientCapabilities,\n        clientInfo: options.clientInfo,\n      } satisfies EffectAcpSchema.InitializeRequest;\n\n      const initializeResult = yield* runLoggedRequest(\n        \"initialize\",\n        initializePayload,\n        acp.agent.initialize(initializePayload),\n      );\n\n      const authenticatePayload = {\n        methodId: options.authMethodId,\n      } satisfies EffectAcpSchema.AuthenticateRequest;\n\n      yield* runLoggedRequest(\n        \"authenticate\",\n        authenticatePayload,\n        acp.agent.authenticate(authenticatePayload),\n      );\n\n      let sessionId: string;\n      let sessionSetupResult:\n        | EffectAcpSchema.LoadSessionResponse\n        | EffectAcpSchema.NewSessionResponse\n        | EffectAcpSchema.ResumeSessionResponse;\n      if (options.resumeSessionId) {\n        const loadPayload = {\n          sessionId: options.resumeSessionId,\n          cwd: options.cwd,\n          mcpServers: options.mcpServers ?? [],\n        } satisfies EffectAcpSchema.LoadSessionRequest;\n        const sessionLoadTimeout = Duration.fromInputUnsafe(\n          options.sessionLoadTimeout ?? defaultSessionLoadTimeout,\n        );\n        const sessionLoadReplayIdleGap = Duration.fromInputUnsafe(\n          options.sessionLoadReplayIdleGap ?? defaultSessionLoadReplayIdleGap,\n        );\n\n        yield* Ref.set(\n          sessionLoadGateRef,\n          Option.some({\n            active: true,\n            lastActivityAtMillis: undefined,\n            idleGap: sessionLoadReplayIdleGap,\n            initializeResult,\n          }),\n        );\n\n        sessionId = options.resumeSessionId;\n        sessionSetupResult = yield* Effect.gen(function* () {\n          yield* logRequest({\n            method: \"session/load\",\n            payload: loadPayload,\n            status: \"started\",\n          });\n\n          const idleFiber = yield* waitForSessionLoadReplayIdle({\n            gateRef: sessionLoadGateRef,\n          }).pipe(Effect.forkIn(runtimeScope));\n          const loaded = yield* Effect.raceFirst(\n            acp.agent.loadSession(loadPayload),\n            Fiber.join(idleFiber),\n          ).pipe(\n            Effect.ensuring(Fiber.interrupt(idleFiber).pipe(Effect.ignore)),\n            Effect.timeoutOption(sessionLoadTimeout),\n            Effect.flatMap((result) =>\n              Option.match(result, {\n                onNone: () =>\n                  Effect.fail(\n                    new EffectAcpErrors.AcpTransportError({\n                      operation: \"call-rpc\",\n                      method: \"session/load\",\n                      detail: \"session/load timed out waiting for RPC response or replay idle gap\",\n                      cause: undefined,\n                    }),\n                  ),\n                onSome: Effect.succeed,\n              }),\n            ),\n            Effect.tap((result) =>\n              logRequest({\n                method: \"session/load\",\n                payload: loadPayload,\n                status: \"succeeded\",\n                result,\n              }),\n            ),\n            Effect.onError((cause) =>\n              logRequest({\n                method: \"session/load\",\n                payload: loadPayload,\n                status: \"failed\",\n                cause,\n              }),\n            ),\n          );\n\n          return loaded;\n        }).pipe(Effect.ensuring(Ref.set(sessionLoadGateRef, Option.none())));\n      } else {\n        const createPayload = {\n          cwd: options.cwd,\n          mcpServers: options.mcpServers ?? [],\n        } satisfies EffectAcpSchema.NewSessionRequest;\n        const created = yield* runLoggedRequest(\n          \"session/new\",\n          createPayload,\n          acp.agent.createSession(createPayload),\n        );\n        sessionId = created.sessionId;\n        sessionSetupResult = created;\n      }\n\n      yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));\n      yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));\n\n      const nextState = {\n        sessionId,\n        initializeResult,\n        sessionSetupResult,\n        modelConfigId: extractModelConfigId(sessionSetupResult),\n      } satisfies AcpStartedState;\n      return nextState;\n    });\n\n    const start = Effect.gen(function* () {\n      const deferred = yield* Deferred.make<\n        AcpSessionRuntimeStartResult,\n        EffectAcpErrors.AcpError\n      >();\n      const effect = yield* Ref.modify(startStateRef, (state) => {\n        switch (state._tag) {\n          case \"Started\":\n            return [Effect.succeed(state.result), state] as const;\n          case \"Starting\":\n            return [Deferred.await(state.deferred), state] as const;\n          case \"NotStarted\":\n            return [\n              startOnce.pipe(\n                Effect.tap((result) =>\n                  Ref.set(startStateRef, { _tag: \"Started\", result }).pipe(\n                    Effect.andThen(Deferred.succeed(deferred, result)),\n                  ),\n                ),\n                Effect.onError((cause) =>\n                  Deferred.failCause(deferred, cause).pipe(\n                    Effect.andThen(Ref.set(startStateRef, { _tag: \"NotStarted\" })),\n                  ),\n                ),\n              ),\n              { _tag: \"Starting\", deferred } satisfies AcpStartState,\n            ] as const;\n        }\n      });\n      return yield* effect;\n    });\n\n    return {\n      handleRequestPermission: acp.handleRequestPermission,\n      handleElicitation: acp.handleElicitation,\n      handleReadTextFile: acp.handleReadTextFile,\n      handleWriteTextFile: acp.handleWriteTextFile,\n      handleCreateTerminal: acp.handleCreateTerminal,\n      handleTerminalOutput: acp.handleTerminalOutput,\n      handleTerminalWaitForExit: acp.handleTerminalWaitForExit,\n      handleTerminalKill: acp.handleTerminalKill,\n      handleTerminalRelease: acp.handleTerminalRelease,\n      handleSessionUpdate: acp.handleSessionUpdate,\n      handleElicitationComplete: acp.handleElicitationComplete,\n      handleUnknownExtRequest: acp.handleUnknownExtRequest,\n      handleUnknownExtNotification: acp.handleUnknownExtNotification,\n      handleExtRequest: acp.handleExtRequest,\n      handleExtNotification: acp.handleExtNotification,\n      start: () => start,\n      getEvents: () => Stream.fromQueue(eventQueue),\n      drainEvents: Effect.gen(function* () {\n        const acknowledge = yield* Deferred.make<void>();\n        yield* Queue.offer(eventQueue, {\n          _tag: \"EventStreamBarrier\",\n          acknowledge,\n        });\n        yield* Deferred.await(acknowledge);\n      }),\n      getModeState: Ref.get(modeStateRef),\n      getConfigOptions: Ref.get(configOptionsRef),\n      prompt: (payload) =>\n        promptSerializationSemaphore.withPermit(\n          Effect.gen(function* () {\n            const started = yield* getStartedState;\n            yield* closeActiveAssistantSegment({\n              queue: eventQueue,\n              assistantSegmentRef,\n            });\n            const requestPayload = {\n              sessionId: started.sessionId,\n              ...payload,\n            } satisfies EffectAcpSchema.PromptRequest;\n            const cancelledResponse = {\n              stopReason: \"cancelled\",\n            } satisfies EffectAcpSchema.PromptResponse;\n            const promptRpcFiber = yield* runLoggedRequest(\n              \"session/prompt\",\n              requestPayload,\n              acp.agent.prompt(requestPayload),\n            ).pipe(Effect.forkIn(runtimeScope));\n            yield* Ref.set(activePromptFiberRef, Option.some(promptRpcFiber));\n            return yield* Fiber.join(promptRpcFiber).pipe(\n              Effect.catchCause((cause) =>\n                Cause.hasInterruptsOnly(cause)\n                  ? Effect.succeed(cancelledResponse)\n                  : Effect.failCause(cause),\n              ),\n              Effect.ensuring(\n                Effect.gen(function* () {\n                  yield* Fiber.interrupt(promptRpcFiber).pipe(Effect.ignore);\n                  yield* Ref.set(activePromptFiberRef, Option.none());\n                }),\n              ),\n              Effect.tap(() =>\n                closeActiveAssistantSegment({\n                  queue: eventQueue,\n                  assistantSegmentRef,\n                }),\n              ),\n            );\n          }),\n        ),\n      cancel: getStartedState.pipe(\n        Effect.flatMap((started) =>\n          Effect.gen(function* () {\n            const activePromptFiber = yield* Ref.get(activePromptFiberRef);\n            if (Option.isSome(activePromptFiber)) {\n              yield* Fiber.interrupt(activePromptFiber.value).pipe(Effect.ignore);\n            }\n            yield* acp.agent\n              .cancel({ sessionId: started.sessionId })\n              .pipe(Effect.ignore, Effect.forkIn(runtimeScope));\n          }),\n        ),\n      ),\n      setMode: (modeId) =>\n        Ref.get(modeStateRef).pipe(\n          Effect.flatMap((modeState) => {\n            if (modeState?.currentModeId === modeId) {\n              return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);\n            }\n            return setConfigOption(\"mode\", modeId).pipe(\n              Effect.tap(() => updateCurrentModeId(modeId)),\n              Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),\n            );\n          }),\n        ),\n      setConfigOption,\n      setModel: (model) =>\n        getStartedState.pipe(\n          Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? \"model\", model)),\n          Effect.asVoid,\n        ),\n      setSessionModel: (modelId) =>\n        getStartedState.pipe(\n          Effect.flatMap((started) => {\n            const requestPayload = {\n              sessionId: started.sessionId,\n              modelId,\n            } satisfies EffectAcpSchema.SetSessionModelRequest;\n            return runLoggedRequest(\n              \"session/set_model\",\n              requestPayload,\n              acp.agent.setSessionModel(requestPayload),\n            );\n          }),\n        ),\n      request: (method, payload) =>\n        runLoggedRequest(method, payload, acp.raw.request(method, payload)),\n      notify: acp.raw.notify,\n    } satisfies AcpSessionRuntime[\"Service\"];\n  });\n\nexport const layer = (\n  options: AcpSessionRuntimeOptions,\n): Layer.Layer<\n  AcpSessionRuntime,\n  EffectAcpErrors.AcpError,\n  ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto\n> => Layer.effect(AcpSessionRuntime, make(options));\n\nfunction sessionConfigOptionsFromSetup(\n  response:\n    | {\n        readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;\n      }\n    | undefined,\n): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {\n  return response?.configOptions ?? [];\n}\n\nfunction configOptionCurrentValueMatches(\n  configOption: EffectAcpSchema.SessionConfigOption,\n  value: string | boolean,\n): boolean {\n  const currentValue = configOption.currentValue;\n  if (configOption.type === \"boolean\") {\n    return currentValue === value;\n  }\n  if (typeof currentValue !== \"string\") {\n    return false;\n  }\n  return currentValue.trim() === String(value).trim();\n}\n\nconst handleSessionUpdate = ({\n  queue,\n  modeStateRef,\n  toolCallsRef,\n  assistantSegmentRef,\n  assistantItemRuntimeId,\n  params,\n}: {\n  readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;\n  readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;\n  readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;\n  readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;\n  readonly assistantItemRuntimeId: string;\n  readonly params: EffectAcpSchema.SessionNotification;\n}): Effect.Effect<void> =>\n  Effect.gen(function* () {\n    const parsed = parseSessionUpdateEvent(params);\n    if (parsed.modeId) {\n      yield* Ref.update(modeStateRef, (current) =>\n        current === undefined ? current : updateModeState(current, parsed.modeId!),\n      );\n    }\n    for (const event of parsed.events) {\n      if (event._tag === \"ToolCallUpdated\") {\n        yield* closeActiveAssistantSegment({\n          queue,\n          assistantSegmentRef,\n        });\n        const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => {\n          const previous = current.get(event.toolCall.toolCallId);\n          const nextToolCall = mergeToolCallState(previous, event.toolCall);\n          const next = new Map(current);\n          if (nextToolCall.status === \"completed\" || nextToolCall.status === \"failed\") {\n            next.delete(nextToolCall.toolCallId);\n          } else {\n            next.set(nextToolCall.toolCallId, nextToolCall);\n          }\n          return [{ previous, merged: nextToolCall }, next] as const;\n        });\n        if (!shouldEmitToolCallUpdate(previous, merged)) {\n          continue;\n        }\n        yield* Queue.offer(queue, {\n          _tag: \"ToolCallUpdated\",\n          toolCall: merged,\n          rawPayload: event.rawPayload,\n        });\n        continue;\n      }\n      if (event._tag === \"ContentDelta\") {\n        if (event.text.trim().length === 0) {\n          const assistantSegmentState = yield* Ref.get(assistantSegmentRef);\n          if (!assistantSegmentState.activeItemId) {\n            continue;\n          }\n        }\n        const itemId = yield* ensureActiveAssistantSegment({\n          queue,\n          assistantSegmentRef,\n          sessionId: params.sessionId,\n          assistantItemRuntimeId,\n        });\n        yield* Queue.offer(queue, {\n          ...event,\n          itemId,\n        });\n        continue;\n      }\n      yield* Queue.offer(queue, event);\n    }\n  });\n\nfunction updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {\n  const normalized = nextModeId.trim();\n  if (!normalized) {\n    return modeState;\n  }\n  return modeState.availableModes.some((mode) => mode.id === normalized)\n    ? {\n        ...modeState,\n        currentModeId: normalized,\n      }\n    : modeState;\n}\n\nfunction shouldEmitToolCallUpdate(\n  previous: AcpToolCallState | undefined,\n  next: AcpToolCallState,\n): boolean {\n  if (next.status === \"completed\" || next.status === \"failed\") {\n    return true;\n  }\n  if (!next.detail) {\n    return false;\n  }\n  return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;\n}\n\nconst assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) =>\n  `assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`;\n\nconst ensureActiveAssistantSegment = ({\n  queue,\n  assistantSegmentRef,\n  sessionId,\n  assistantItemRuntimeId,\n}: {\n  readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;\n  readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;\n  readonly sessionId: string;\n  readonly assistantItemRuntimeId: string;\n}) =>\n  Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(\n    assistantSegmentRef,\n    (current) => {\n      if (current.activeItemId) {\n        return [{ itemId: current.activeItemId }, current] as const;\n      }\n      const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex);\n      return [\n        {\n          itemId,\n          startedEvent: {\n            _tag: \"AssistantItemStarted\",\n            itemId,\n          } satisfies Extract<AcpParsedSessionEvent, { readonly _tag: \"AssistantItemStarted\" }>,\n        },\n        {\n          nextSegmentIndex: current.nextSegmentIndex + 1,\n          activeItemId: itemId,\n        } satisfies AcpAssistantSegmentState,\n      ] as const;\n    },\n  ).pipe(\n    Effect.flatMap((result) =>\n      result.startedEvent\n        ? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))\n        : Effect.succeed(result.itemId),\n    ),\n  );\n\nconst closeActiveAssistantSegment = ({\n  queue,\n  assistantSegmentRef,\n}: {\n  readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;\n  readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;\n}) =>\n  Ref.modify(assistantSegmentRef, (current) => {\n    if (!current.activeItemId) {\n      return [undefined, current] as const;\n    }\n    return [\n      {\n        _tag: \"AssistantItemCompleted\",\n        itemId: current.activeItemId,\n      } satisfies AcpParsedSessionEvent,\n      {\n        nextSegmentIndex: current.nextSegmentIndex,\n      } satisfies AcpAssistantSegmentState,\n    ] as const;\n  }).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));\n","/**\n * Public Docs: https://cursor.com/docs/cli/acp#cursor-extension-methods\n * Additional reference provided by the Cursor team: https://anysphere.enterprise.slack.com/files/U068SSJE141/F0APT1HSZRP/cursor-acp-extension-method-schemas.md\n */\nimport type { UserInputQuestion } from \"@t3tools/contracts\";\nimport * as AcpSchema from \"effect-acp/schema\";\nimport * as Schema from \"effect/Schema\";\n\nconst CursorAskQuestionOption = Schema.Struct({\n  id: Schema.String,\n  label: Schema.String,\n});\n\nconst CursorAskQuestion = Schema.Struct({\n  id: Schema.String,\n  prompt: Schema.String,\n  options: Schema.Array(CursorAskQuestionOption),\n  allowMultiple: Schema.optional(Schema.Boolean),\n});\n\nexport const CursorAskQuestionRequest = Schema.Struct({\n  toolCallId: Schema.String,\n  title: Schema.optional(Schema.String),\n  questions: Schema.Array(CursorAskQuestion),\n});\n\nconst CursorTodoStatus = Schema.String;\n\nconst CursorTodo = Schema.Struct({\n  id: Schema.optional(Schema.String),\n  content: Schema.optional(Schema.String),\n  title: Schema.optional(Schema.String),\n  status: Schema.optional(CursorTodoStatus),\n});\n\nconst CursorPlanPhase = Schema.Struct({\n  name: Schema.String,\n  todos: Schema.Array(CursorTodo),\n});\n\nexport const CursorCreatePlanRequest = Schema.Struct({\n  toolCallId: Schema.String,\n  name: Schema.optional(Schema.String),\n  overview: Schema.optional(Schema.String),\n  plan: Schema.String,\n  todos: Schema.Array(CursorTodo),\n  isProject: Schema.optional(Schema.Boolean),\n  phases: Schema.optional(Schema.Array(CursorPlanPhase)),\n});\n\nexport const CursorUpdateTodosRequest = Schema.Struct({\n  toolCallId: Schema.String,\n  todos: Schema.Array(CursorTodo),\n  merge: Schema.Boolean,\n});\n\nconst CursorAvailableModel = Schema.Struct({\n  value: Schema.String,\n  name: Schema.String,\n  configOptions: Schema.optional(Schema.Array(AcpSchema.SessionConfigOption)),\n});\n\nexport const CursorListAvailableModelsResponse = Schema.Struct({\n  models: Schema.Array(CursorAvailableModel),\n});\n\nexport function extractAskQuestions(\n  params: typeof CursorAskQuestionRequest.Type,\n): ReadonlyArray<UserInputQuestion> {\n  return params.questions.map((question) => ({\n    id: question.id,\n    header: \"Question\",\n    question: question.prompt,\n    multiSelect: question.allowMultiple === true,\n    options:\n      question.options.length > 0\n        ? question.options.map((option) => ({\n            label: option.label,\n            description: option.label,\n          }))\n        : [{ label: \"OK\", description: \"Continue\" }],\n  }));\n}\n\nexport function extractPlanMarkdown(params: typeof CursorCreatePlanRequest.Type): string {\n  return params.plan || \"# Plan\\n\\n(Cursor did not supply plan text.)\";\n}\n\nexport function extractTodosAsPlan(params: typeof CursorUpdateTodosRequest.Type): {\n  readonly explanation?: string;\n  readonly plan: ReadonlyArray<{\n    readonly step: string;\n    readonly status: \"pending\" | \"inProgress\" | \"completed\";\n  }>;\n} {\n  const plan = params.todos.flatMap((todo) => {\n    // Fall back to the title when content is missing OR blank. `??` only\n    // covers a missing content, so a present-but-empty content (\"\" or\n    // whitespace) would shadow a real title and drop the step below.\n    const step = todo.content?.trim() || todo.title?.trim() || \"\";\n    if (step === \"\") {\n      return [];\n    }\n    const status: \"pending\" | \"inProgress\" | \"completed\" =\n      todo.status === \"completed\"\n        ? \"completed\"\n        : todo.status === \"in_progress\" || todo.status === \"inProgress\"\n          ? \"inProgress\"\n          : \"pending\";\n    return [{ step, status }];\n  });\n  return { plan };\n}\n","import * as NodeOS from \"node:os\";\nimport type {\n  CursorSettings,\n  ModelCapabilities,\n  ProviderOptionSelection,\n  ServerProvider,\n  ServerProviderAuth,\n  ServerProviderModel,\n  ServerProviderState,\n} from \"@t3tools/contracts\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\nimport { causeErrorTag } from \"@t3tools/shared/observability\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport {\n  createModelCapabilities,\n  getProviderOptionBooleanSelectionValue,\n  getProviderOptionStringSelectionValue,\n} from \"@t3tools/shared/model\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\nimport {\n  buildBooleanOptionDescriptor,\n  buildSelectOptionDescriptor,\n  buildServerProvider,\n  collectStreamAsString,\n  isCommandMissingCause,\n  providerModelsFromSettings,\n  type CommandResult,\n  type ServerProviderDraft,\n} from \"../providerSnapshot.ts\";\nimport {\n  enrichProviderSnapshotWithVersionAdvisory,\n  type ProviderMaintenanceCapabilities,\n} from \"../providerMaintenance.ts\";\nimport * as AcpSessionRuntime from \"../acp/AcpSessionRuntime.ts\";\nimport { CursorListAvailableModelsResponse } from \"../acp/CursorAcpExtension.ts\";\n\nconst decodeCursorListAvailableModelsResponse = Schema.decodeUnknownEffect(\n  CursorListAvailableModelsResponse,\n);\nconst CURSOR_PRESENTATION = {\n  displayName: \"Cursor\",\n  badgeLabel: \"Early Access\",\n  showInteractionModeToggle: true,\n} as const;\nconst EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({\n  optionDescriptors: [],\n});\n\nconst CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;\nconst CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE = 2026_04_08;\nconst CURSOR_CLI_INSTALLATION_DOCS_URL = \"https://cursor.com/docs/cli/installation\";\nconst CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE = [\n  \"Cursor ACP model discovery failed.\",\n  \"Cursor CLI setup may be incomplete; install or enable the Cursor CLI, restart Synaptic Code, and try again.\",\n  `See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,\n  \"Check server logs for ACP details.\",\n].join(\" \");\nexport const CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES = {\n  _meta: {\n    parameterizedModelPicker: true,\n  },\n} satisfies NonNullable<EffectAcpSchema.InitializeRequest[\"clientCapabilities\"]>;\n\nexport function buildInitialCursorProviderSnapshot(\n  cursorSettings: CursorSettings,\n): Effect.Effect<ServerProviderDraft> {\n  return Effect.gen(function* () {\n    const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);\n    const models = getCursorFallbackModels(cursorSettings);\n\n    if (!cursorSettings.enabled) {\n      return buildServerProvider({\n        presentation: CURSOR_PRESENTATION,\n        enabled: false,\n        checkedAt,\n        models,\n        probe: {\n          installed: false,\n          version: null,\n          status: \"warning\",\n          auth: { status: \"unknown\" },\n          message: \"Cursor is disabled in Synaptic Code settings.\",\n        },\n      });\n    }\n\n    return buildServerProvider({\n      presentation: CURSOR_PRESENTATION,\n      enabled: true,\n      checkedAt,\n      models,\n      probe: {\n        installed: true,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Checking Cursor Agent availability...\",\n      },\n    });\n  });\n}\n\ninterface CursorSessionSelectOption {\n  readonly value: string;\n  readonly name: string;\n}\n\ninterface CursorAcpDiscoveredModel {\n  readonly slug: string;\n  readonly name: string;\n  readonly capabilities: ModelCapabilities;\n}\n\nfunction flattenSessionConfigSelectOptions(\n  configOption: EffectAcpSchema.SessionConfigOption | undefined,\n): ReadonlyArray<CursorSessionSelectOption> {\n  if (!configOption || configOption.type !== \"select\") {\n    return [];\n  }\n  return configOption.options.flatMap((entry) =>\n    \"value\" in entry\n      ? [\n          {\n            value: entry.value.trim(),\n            name: entry.name.trim(),\n          } satisfies CursorSessionSelectOption,\n        ]\n      : entry.options.map(\n          (option) =>\n            ({\n              value: option.value.trim(),\n              name: option.name.trim(),\n            }) satisfies CursorSessionSelectOption,\n        ),\n  );\n}\n\nfunction normalizeCursorReasoningValue(value: string | null | undefined): string | undefined {\n  const normalized = value?.trim().toLowerCase();\n  switch (normalized) {\n    case \"low\":\n    case \"medium\":\n    case \"high\":\n    case \"max\":\n      return normalized;\n    case \"xhigh\":\n    case \"extra-high\":\n    case \"extra high\":\n      return \"xhigh\";\n    default:\n      return undefined;\n  }\n}\n\nfunction getCursorConfigOptionCategory(option: EffectAcpSchema.SessionConfigOption): string {\n  return option.category?.trim().toLowerCase() ?? \"\";\n}\n\nfunction isCursorEffortConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {\n  const id = option.id.trim().toLowerCase();\n  const name = option.name.trim().toLowerCase();\n  return (\n    id === \"effort\" ||\n    id === \"reasoning\" ||\n    name === \"effort\" ||\n    name === \"reasoning\" ||\n    name.includes(\"effort\") ||\n    name.includes(\"reasoning\")\n  );\n}\n\nfunction findCursorEffortConfigOption(\n  configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,\n): EffectAcpSchema.SessionConfigOption | undefined {\n  const candidates = configOptions.filter(\n    (option) => option.type === \"select\" && isCursorEffortConfigOption(option),\n  );\n  return (\n    candidates.find((option) => getCursorConfigOptionCategory(option) === \"model_option\") ??\n    candidates.find((option) => option.id.trim().toLowerCase() === \"effort\") ??\n    candidates.find((option) => getCursorConfigOptionCategory(option) === \"thought_level\") ??\n    candidates[0]\n  );\n}\n\nfunction isCursorContextConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {\n  const id = option.id.trim().toLowerCase();\n  const name = option.name.trim().toLowerCase();\n  return id === \"context\" || id === \"context_size\" || name.includes(\"context\");\n}\n\nfunction isCursorFastConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {\n  const id = option.id.trim().toLowerCase();\n  const name = option.name.trim().toLowerCase();\n  return id === \"fast\" || name === \"fast\" || name.includes(\"fast mode\");\n}\n\nfunction isCursorThinkingConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {\n  const id = option.id.trim().toLowerCase();\n  const name = option.name.trim().toLowerCase();\n  return id === \"thinking\" || name.includes(\"thinking\");\n}\n\nfunction isBooleanLikeConfigOption(option: EffectAcpSchema.SessionConfigOption): boolean {\n  if (option.type === \"boolean\") {\n    return true;\n  }\n  if (option.type !== \"select\") {\n    return false;\n  }\n  const values = new Set(\n    flattenSessionConfigSelectOptions(option).map((entry) => entry.value.trim().toLowerCase()),\n  );\n  return values.has(\"true\") && values.has(\"false\");\n}\n\nfunction getBooleanCurrentValue(\n  option: EffectAcpSchema.SessionConfigOption | undefined,\n): boolean | undefined {\n  if (!option) {\n    return undefined;\n  }\n  if (option.type === \"boolean\") {\n    return option.currentValue;\n  }\n  if (option.type !== \"select\") {\n    return undefined;\n  }\n  const normalized = option.currentValue?.trim().toLowerCase();\n  if (normalized === \"true\") {\n    return true;\n  }\n  if (normalized === \"false\") {\n    return false;\n  }\n  return undefined;\n}\n\nexport function buildCursorCapabilitiesFromConfigOptions(\n  configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,\n): ModelCapabilities {\n  if (!configOptions || configOptions.length === 0) {\n    return EMPTY_CAPABILITIES;\n  }\n\n  const reasoningConfig = findCursorEffortConfigOption(configOptions);\n  const reasoningEffortLevels =\n    reasoningConfig?.type === \"select\"\n      ? flattenSessionConfigSelectOptions(reasoningConfig).flatMap((entry) => {\n          const normalizedValue = normalizeCursorReasoningValue(entry.value);\n          if (!normalizedValue) {\n            return [];\n          }\n          return [\n            {\n              value: normalizedValue,\n              label: entry.name,\n              ...(normalizeCursorReasoningValue(reasoningConfig.currentValue) === normalizedValue\n                ? { isDefault: true }\n                : {}),\n            },\n          ];\n        })\n      : [];\n\n  const contextOption = configOptions.find(\n    (option) => option.category === \"model_config\" && isCursorContextConfigOption(option),\n  );\n  const contextWindowOptions =\n    contextOption?.type === \"select\"\n      ? flattenSessionConfigSelectOptions(contextOption).map((entry) => {\n          if (contextOption.currentValue === entry.value) {\n            return {\n              value: entry.value,\n              label: entry.name,\n              isDefault: true,\n            };\n          }\n          return {\n            value: entry.value,\n            label: entry.name,\n          };\n        })\n      : [];\n\n  const fastOption = configOptions.find(\n    (option) => option.category === \"model_config\" && isCursorFastConfigOption(option),\n  );\n  const thinkingOption = configOptions.find(\n    (option) => option.category === \"model_config\" && isCursorThinkingConfigOption(option),\n  );\n  const fastCurrentValue = getBooleanCurrentValue(fastOption);\n  const thinkingCurrentValue = getBooleanCurrentValue(thinkingOption);\n  const optionDescriptors = [\n    ...(reasoningEffortLevels.length > 0\n      ? [\n          buildSelectOptionDescriptor({\n            id: \"reasoning\",\n            label: reasoningConfig?.name?.trim() || \"Reasoning\",\n            options: reasoningEffortLevels,\n          }),\n        ]\n      : []),\n    ...(contextWindowOptions.length > 0\n      ? [\n          buildSelectOptionDescriptor({\n            id: \"contextWindow\",\n            label: contextOption?.name?.trim() || \"Context Window\",\n            options: contextWindowOptions,\n          }),\n        ]\n      : []),\n    ...(fastOption && isBooleanLikeConfigOption(fastOption)\n      ? [\n          typeof fastCurrentValue === \"boolean\"\n            ? buildBooleanOptionDescriptor({\n                id: \"fastMode\",\n                label: fastOption.name?.trim() || \"Fast Mode\",\n                currentValue: fastCurrentValue,\n              })\n            : buildBooleanOptionDescriptor({\n                id: \"fastMode\",\n                label: fastOption.name?.trim() || \"Fast Mode\",\n              }),\n        ]\n      : []),\n    ...(thinkingOption && isBooleanLikeConfigOption(thinkingOption)\n      ? [\n          typeof thinkingCurrentValue === \"boolean\"\n            ? buildBooleanOptionDescriptor({\n                id: \"thinking\",\n                label: thinkingOption.name?.trim() || \"Thinking\",\n                currentValue: thinkingCurrentValue,\n              })\n            : buildBooleanOptionDescriptor({\n                id: \"thinking\",\n                label: thinkingOption.name?.trim() || \"Thinking\",\n              }),\n        ]\n      : []),\n  ];\n\n  return createModelCapabilities({\n    optionDescriptors,\n  });\n}\n\nfunction buildCursorDiscoveredModels(\n  discoveredModels: ReadonlyArray<CursorAcpDiscoveredModel>,\n): ReadonlyArray<ServerProviderModel> {\n  const seen = new Set<string>();\n  return discoveredModels.flatMap((model) => {\n    if (!model.slug || seen.has(model.slug)) {\n      return [];\n    }\n    seen.add(model.slug);\n    return [\n      {\n        slug: model.slug,\n        name: model.name,\n        isCustom: false,\n        capabilities: model.capabilities,\n      } satisfies ServerProviderModel,\n    ];\n  });\n}\n\nfunction buildCursorDiscoveredModelsFromAvailableModelsResponse(\n  response: typeof CursorListAvailableModelsResponse.Type,\n): ReadonlyArray<ServerProviderModel> {\n  return buildCursorDiscoveredModels(\n    response.models.flatMap((model) => {\n      const slug = model.value.trim();\n      const name = model.name.trim();\n      if (!slug || !name) {\n        return [];\n      }\n\n      return [\n        {\n          slug,\n          name,\n          capabilities: buildCursorCapabilitiesFromConfigOptions(model.configOptions),\n        },\n      ];\n    }),\n  );\n}\n\nconst makeCursorAcpProbeRuntime = (\n  cursorSettings: CursorSettings,\n  environment?: NodeJS.ProcessEnv,\n) =>\n  Effect.gen(function* () {\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const acpContext = yield* Layer.build(\n      AcpSessionRuntime.layer({\n        spawn: {\n          command: cursorSettings.binaryPath,\n          args: [\n            ...(cursorSettings.apiEndpoint ? ([\"-e\", cursorSettings.apiEndpoint] as const) : []),\n            \"acp\",\n          ],\n          cwd: process.cwd(),\n          ...(environment ? { env: environment } : {}),\n        },\n        cwd: process.cwd(),\n        clientInfo: { name: \"synaptic-code-provider-probe\", version: \"0.0.0\" },\n        authMethodId: \"cursor_login\",\n        clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,\n      }).pipe(Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner))),\n    );\n    return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(\n      Effect.provide(acpContext),\n    );\n  });\n\nconst withCursorAcpProbeRuntime = <A, E, R>(\n  cursorSettings: CursorSettings,\n  useRuntime: (acp: AcpSessionRuntime.AcpSessionRuntime[\"Service\"]) => Effect.Effect<A, E, R>,\n  environment?: NodeJS.ProcessEnv,\n) =>\n  makeCursorAcpProbeRuntime(cursorSettings, environment).pipe(\n    Effect.flatMap(useRuntime),\n    Effect.scoped,\n  );\n\nfunction normalizeCursorConfigOptionToken(value: string | null | undefined): string {\n  return (\n    value\n      ?.trim()\n      .toLowerCase()\n      .replace(/[\\s_-]+/g, \"-\") ?? \"\"\n  );\n}\n\nfunction findCursorSelectOptionValue(\n  configOption: EffectAcpSchema.SessionConfigOption | undefined,\n  matcher: (option: CursorSessionSelectOption) => boolean,\n): string | undefined {\n  return flattenSessionConfigSelectOptions(configOption).find(matcher)?.value;\n}\n\nfunction findCursorBooleanConfigValue(\n  configOption: EffectAcpSchema.SessionConfigOption | undefined,\n  requested: boolean,\n): string | boolean | undefined {\n  if (!configOption) {\n    return undefined;\n  }\n  if (configOption.type === \"boolean\") {\n    return requested;\n  }\n  return findCursorSelectOptionValue(\n    configOption,\n    (option) => normalizeCursorConfigOptionToken(option.value) === String(requested),\n  );\n}\n\nexport function resolveCursorAcpBaseModelId(model: string | null | undefined): string {\n  const trimmed = model?.trim();\n  const base = trimmed && trimmed.length > 0 ? trimmed : \"default\";\n  return base.includes(\"[\") ? base.slice(0, base.indexOf(\"[\")) : base;\n}\n\nexport function resolveCursorAcpConfigUpdates(\n  configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,\n  selections: ReadonlyArray<ProviderOptionSelection> | null | undefined,\n): ReadonlyArray<{\n  readonly configId: string;\n  readonly value: string | boolean;\n}> {\n  if (!configOptions || configOptions.length === 0) {\n    return [];\n  }\n\n  const updates: Array<{\n    readonly configId: string;\n    readonly value: string | boolean;\n  }> = [];\n\n  const reasoningOption = findCursorEffortConfigOption(configOptions);\n  const requestedReasoning = normalizeCursorReasoningValue(\n    getProviderOptionStringSelectionValue(selections, \"reasoning\"),\n  );\n  if (reasoningOption && requestedReasoning) {\n    const value = findCursorSelectOptionValue(reasoningOption, (option) => {\n      const normalizedValue = normalizeCursorReasoningValue(option.value);\n      const normalizedName = normalizeCursorReasoningValue(option.name);\n      return normalizedValue === requestedReasoning || normalizedName === requestedReasoning;\n    });\n    if (value) {\n      updates.push({ configId: reasoningOption.id, value });\n    }\n  }\n\n  const contextOption = configOptions.find(\n    (option) => option.category === \"model_config\" && isCursorContextConfigOption(option),\n  );\n  const requestedContextWindow = getProviderOptionStringSelectionValue(selections, \"contextWindow\");\n  if (contextOption && requestedContextWindow) {\n    const value = findCursorSelectOptionValue(\n      contextOption,\n      (option) =>\n        normalizeCursorConfigOptionToken(option.value) ===\n          normalizeCursorConfigOptionToken(requestedContextWindow) ||\n        normalizeCursorConfigOptionToken(option.name) ===\n          normalizeCursorConfigOptionToken(requestedContextWindow),\n    );\n    if (value) {\n      updates.push({ configId: contextOption.id, value });\n    }\n  }\n\n  const fastOption = configOptions.find(\n    (option) => option.category === \"model_config\" && isCursorFastConfigOption(option),\n  );\n  const requestedFastMode = getProviderOptionBooleanSelectionValue(selections, \"fastMode\");\n  if (fastOption && typeof requestedFastMode === \"boolean\") {\n    const value = findCursorBooleanConfigValue(fastOption, requestedFastMode);\n    if (value !== undefined) {\n      updates.push({ configId: fastOption.id, value });\n    }\n  }\n\n  const thinkingOption = configOptions.find(\n    (option) => option.category === \"model_config\" && isCursorThinkingConfigOption(option),\n  );\n  const requestedThinking = getProviderOptionBooleanSelectionValue(selections, \"thinking\");\n  if (thinkingOption && typeof requestedThinking === \"boolean\") {\n    const value = findCursorBooleanConfigValue(thinkingOption, requestedThinking);\n    if (value !== undefined) {\n      updates.push({ configId: thinkingOption.id, value });\n    }\n  }\n\n  return updates;\n}\n\nconst discoverCursorModelsViaListAvailableModels = (\n  cursorSettings: CursorSettings,\n  environment?: NodeJS.ProcessEnv,\n) =>\n  withCursorAcpProbeRuntime(\n    cursorSettings,\n    (acp) =>\n      Effect.gen(function* () {\n        yield* acp.start();\n        const response = yield* acp.request(\"cursor/list_available_models\", {});\n        const decoded = yield* decodeCursorListAvailableModelsResponse(response);\n        return buildCursorDiscoveredModelsFromAvailableModelsResponse(decoded);\n      }),\n    environment,\n  );\n\nexport const discoverCursorModelsViaAcp = (\n  cursorSettings: CursorSettings,\n  environment?: NodeJS.ProcessEnv,\n) => discoverCursorModelsViaListAvailableModels(cursorSettings, environment);\n\nexport function getCursorFallbackModels(\n  cursorSettings: Pick<CursorSettings, \"customModels\">,\n): ReadonlyArray<ServerProviderModel> {\n  return providerModelsFromSettings([], cursorSettings.customModels, EMPTY_CAPABILITIES);\n}\n\n/** Timeout for `agent about` — it's slower than a simple `--version` probe. */\nconst ABOUT_TIMEOUT_MS = 8_000;\n\n/** Strip ANSI escape sequences so we can parse plain key-value lines. */\nfunction stripAnsi(text: string): string {\n  // eslint-disable-next-line no-control-regex\n  return text.replace(/\\x1b\\[[0-9;]*[A-Za-z]|\\x1b\\].*?\\x07/g, \"\");\n}\n\n/**\n * Extract a value from `agent about` key-value output.\n * Lines look like: `CLI Version         2026.03.20-44cb435`\n */\nfunction extractAboutField(plain: string, key: string): string | undefined {\n  const regex = new RegExp(`^${key}\\\\s{2,}(.+)$`, \"mi\");\n  const match = regex.exec(plain);\n  return match?.[1]?.trim();\n}\n\nexport interface CursorAboutResult {\n  readonly version: string | null;\n  readonly status: Exclude<ServerProviderState, \"disabled\">;\n  readonly auth: ServerProviderAuth;\n  readonly message?: string;\n}\n\nfunction joinProviderMessages(...messages: ReadonlyArray<string | undefined>): string | undefined {\n  const parts: Array<string> = [];\n  for (const message of messages) {\n    const trimmed = message?.trim();\n    if (trimmed) {\n      parts.push(trimmed);\n    }\n  }\n  return parts.length > 0 ? parts.join(\" \") : undefined;\n}\n\nfunction buildCursorCliCommandMissingMessage(binaryPath: string): string {\n  return [\n    `Cursor CLI command \\`${binaryPath}\\` was not found.`,\n    `Install or enable the Cursor CLI, make sure \\`${binaryPath}\\` is on PATH, then restart Synaptic Code.`,\n    `See ${CURSOR_CLI_INSTALLATION_DOCS_URL}.`,\n  ].join(\" \");\n}\n\nexport function buildCursorProviderSnapshot(input: {\n  readonly checkedAt: string;\n  readonly cursorSettings: CursorSettings;\n  readonly parsed: CursorAboutResult;\n  readonly discoveredModels?: ReadonlyArray<ServerProviderModel>;\n  readonly discoveryWarning?: string;\n}): ServerProviderDraft {\n  const message = joinProviderMessages(input.parsed.message, input.discoveryWarning);\n  return buildServerProvider({\n    presentation: CURSOR_PRESENTATION,\n    enabled: input.cursorSettings.enabled,\n    checkedAt: input.checkedAt,\n    models: providerModelsFromSettings(\n      input.discoveredModels ?? [],\n      input.cursorSettings.customModels,\n      EMPTY_CAPABILITIES,\n    ),\n    probe: {\n      installed: true,\n      version: input.parsed.version,\n      status:\n        input.discoveryWarning && input.parsed.status === \"ready\" ? \"warning\" : input.parsed.status,\n      auth: input.parsed.auth,\n      ...(message ? { message } : {}),\n    },\n  });\n}\n\ninterface CursorAboutJsonPayload {\n  readonly cliVersion?: unknown;\n  readonly subscriptionTier?: unknown;\n  readonly userEmail?: unknown;\n}\n\nexport function parseCursorVersionDate(version: string | null | undefined): number | undefined {\n  const match = version?.trim().match(/^(\\d{4})\\.(\\d{2})\\.(\\d{2})(?:\\b|-|$)/);\n  if (!match) {\n    return undefined;\n  }\n  const [, year, month, day] = match;\n  return Number(`${year}${month}${day}`);\n}\n\nexport function parseCursorCliConfigChannel(raw: string): string | undefined {\n  try {\n    const parsed = JSON.parse(raw) as unknown;\n    if (\n      typeof parsed === \"object\" &&\n      parsed !== null &&\n      \"channel\" in parsed &&\n      typeof parsed.channel === \"string\"\n    ) {\n      const channel = parsed.channel.trim().toLowerCase();\n      return channel.length > 0 ? channel : undefined;\n    }\n  } catch {\n    return undefined;\n  }\n  return undefined;\n}\n\nfunction toTitleCaseWords(value: string): string {\n  const parts: Array<string> = [];\n  for (const part of value.split(/[\\s_-]+/g)) {\n    if (part.length > 0) {\n      parts.push(part.charAt(0).toUpperCase() + part.slice(1).toLowerCase());\n    }\n  }\n  return parts.join(\" \");\n}\n\nfunction cursorSubscriptionLabel(subscriptionType: string | undefined): string | undefined {\n  const normalized = subscriptionType?.toLowerCase().replace(/[\\s_-]+/g, \"\");\n  if (!normalized) return undefined;\n\n  switch (normalized) {\n    case \"team\":\n      return \"Team\";\n    case \"pro\":\n      return \"Pro\";\n    case \"free\":\n      return \"Free\";\n    case \"business\":\n      return \"Business\";\n    case \"enterprise\":\n      return \"Enterprise\";\n    default:\n      return toTitleCaseWords(subscriptionType!);\n  }\n}\n\nfunction cursorAuthMetadata(\n  subscriptionType: string | undefined,\n): Pick<ServerProviderAuth, \"label\" | \"type\"> | undefined {\n  if (!subscriptionType) {\n    return undefined;\n  }\n  const subscriptionLabel = cursorSubscriptionLabel(subscriptionType);\n  return {\n    type: subscriptionType,\n    label: `Cursor ${subscriptionLabel ?? toTitleCaseWords(subscriptionType)} Subscription`,\n  };\n}\n\nfunction parseCursorAboutJsonPayload(raw: string): CursorAboutJsonPayload | undefined {\n  const trimmed = raw.trim();\n  if (!trimmed.startsWith(\"{\")) {\n    return undefined;\n  }\n  try {\n    const parsed = JSON.parse(trimmed) as unknown;\n    if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n      return undefined;\n    }\n    return parsed as CursorAboutJsonPayload;\n  } catch {\n    return undefined;\n  }\n}\n\nfunction hasOwn(record: object, key: string): boolean {\n  return Object.prototype.hasOwnProperty.call(record, key);\n}\n\nfunction isCursorAboutJsonFormatUnsupported(result: CommandResult): boolean {\n  const lowerOutput = `${result.stdout}\\n${result.stderr}`.toLowerCase();\n  return (\n    lowerOutput.includes(\"unknown option '--format'\") ||\n    lowerOutput.includes(\"unexpected argument '--format'\") ||\n    lowerOutput.includes(\"unrecognized option '--format'\") ||\n    lowerOutput.includes(\"unknown argument '--format'\")\n  );\n}\n\nconst readCursorCliConfigChannel = Effect.fn(\"readCursorCliConfigChannel\")(function* () {\n  const fileSystem = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const configPath = path.join(NodeOS.homedir(), \".cursor\", \"cli-config.json\");\n  const raw = yield* fileSystem.readFileString(configPath).pipe(Effect.orElseSucceed(() => \"\"));\n  return parseCursorCliConfigChannel(raw);\n});\n\nexport function getCursorParameterizedModelPickerUnsupportedMessage(input: {\n  readonly version: string | null | undefined;\n  readonly channel: string | null | undefined;\n}): string | undefined {\n  const reasons: Array<string> = [];\n  const versionDate = parseCursorVersionDate(input.version);\n  if (\n    versionDate !== undefined &&\n    versionDate < CURSOR_PARAMETERIZED_MODEL_PICKER_MIN_VERSION_DATE\n  ) {\n    reasons.push(\n      `Cursor Agent CLI version ${input.version} is too old for Cursor ACP parameterized model picker`,\n    );\n  }\n\n  const normalizedChannel = input.channel?.trim().toLowerCase();\n  if (\n    normalizedChannel !== undefined &&\n    normalizedChannel.length > 0 &&\n    normalizedChannel !== \"lab\"\n  ) {\n    reasons.push(\n      `Cursor Agent CLI channel is ${JSON.stringify(input.channel)}, but parameterized model picker is only available on the lab channel`,\n    );\n  }\n\n  if (reasons.length === 0) {\n    return undefined;\n  }\n\n  return `${reasons.join(\". \")}. Run \\`agent set-channel lab && agent update\\` and use Cursor Agent CLI 2026.04.08 or newer.`;\n}\n\n/**\n * Parse the output of `agent about` to extract version and authentication\n * status in a single probe.\n *\n * Example output (logged in):\n * ```\n * About Cursor CLI\n *\n * CLI Version         2026.03.20-44cb435\n * User Email          user@example.com\n * ```\n *\n * Example output (logged out):\n * ```\n * About Cursor CLI\n *\n * CLI Version         2026.03.20-44cb435\n * User Email          Not logged in\n * ```\n */\nexport function parseCursorAboutOutput(result: CommandResult): CursorAboutResult {\n  const jsonPayload = parseCursorAboutJsonPayload(result.stdout);\n  if (jsonPayload) {\n    const version =\n      typeof jsonPayload.cliVersion === \"string\" ? jsonPayload.cliVersion.trim() : null;\n    const hasUserEmailField = hasOwn(jsonPayload, \"userEmail\");\n    const userEmail =\n      typeof jsonPayload.userEmail === \"string\" ? jsonPayload.userEmail.trim() : undefined;\n    const subscriptionType =\n      typeof jsonPayload.subscriptionTier === \"string\"\n        ? jsonPayload.subscriptionTier.trim()\n        : undefined;\n    const authMetadata = cursorAuthMetadata(subscriptionType);\n\n    if (hasUserEmailField && jsonPayload.userEmail == null) {\n      return {\n        version,\n        status: \"error\",\n        auth: { status: \"unauthenticated\" },\n        message: \"Cursor Agent is not authenticated. Run `agent login` and try again.\",\n      };\n    }\n\n    if (!userEmail) {\n      if (result.code === 0) {\n        return {\n          version,\n          status: \"ready\",\n          auth: {\n            status: \"unknown\",\n            ...authMetadata,\n          },\n        };\n      }\n      return {\n        version,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Could not verify Cursor Agent authentication status.\",\n      };\n    }\n\n    const lowerEmail = userEmail.toLowerCase();\n    if (\n      lowerEmail === \"not logged in\" ||\n      lowerEmail.includes(\"login required\") ||\n      lowerEmail.includes(\"authentication required\")\n    ) {\n      return {\n        version,\n        status: \"error\",\n        auth: { status: \"unauthenticated\" },\n        message: \"Cursor Agent is not authenticated. Run `agent login` and try again.\",\n      };\n    }\n\n    return {\n      version,\n      status: \"ready\",\n      auth: {\n        status: \"authenticated\",\n        email: userEmail,\n        ...authMetadata,\n      },\n    };\n  }\n\n  const combined = `${result.stdout}\\n${result.stderr}`;\n  const lowerOutput = combined.toLowerCase();\n\n  // If the command itself isn't recognised, we're on an old CLI version.\n  if (\n    lowerOutput.includes(\"unknown command\") ||\n    lowerOutput.includes(\"unrecognized command\") ||\n    lowerOutput.includes(\"unexpected argument\")\n  ) {\n    return {\n      version: null,\n      status: \"warning\",\n      auth: { status: \"unknown\" },\n      message: \"The `agent about` command is unavailable in this version of the Cursor Agent CLI.\",\n    };\n  }\n\n  const plain = stripAnsi(combined);\n  const version = extractAboutField(plain, \"CLI Version\") ?? null;\n  const userEmail = extractAboutField(plain, \"User Email\");\n\n  // Determine auth from the User Email field.\n  if (userEmail === undefined) {\n    // Field missing entirely — can't determine auth.\n    if (result.code === 0) {\n      return { version, status: \"ready\", auth: { status: \"unknown\" } };\n    }\n    return {\n      version,\n      status: \"warning\",\n      auth: { status: \"unknown\" },\n      message: \"Could not verify Cursor Agent authentication status.\",\n    };\n  }\n\n  const lowerEmail = userEmail.toLowerCase();\n  if (\n    lowerEmail === \"not logged in\" ||\n    lowerEmail.includes(\"login required\") ||\n    lowerEmail.includes(\"authentication required\")\n  ) {\n    return {\n      version,\n      status: \"error\",\n      auth: { status: \"unauthenticated\" },\n      message: \"Cursor Agent is not authenticated. Run `agent login` and try again.\",\n    };\n  }\n\n  // Any non-empty email value means authenticated.\n  return {\n    version,\n    status: \"ready\",\n    auth: { status: \"authenticated\", email: userEmail },\n  };\n}\n\nconst runCursorCommand = (\n  cursorSettings: CursorSettings,\n  args: ReadonlyArray<string>,\n  environment?: NodeJS.ProcessEnv,\n) =>\n  Effect.gen(function* () {\n    const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const spawnCommand = yield* resolveSpawnCommand(\n      cursorSettings.binaryPath,\n      args,\n      environment ? { env: environment } : {},\n    );\n    const command = ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n      ...(environment ? { env: environment } : { extendEnv: true }),\n      shell: spawnCommand.shell,\n    });\n\n    const child = yield* spawner.spawn(command);\n    const [stdout, stderr, exitCode] = yield* Effect.all(\n      [\n        collectStreamAsString(child.stdout),\n        collectStreamAsString(child.stderr),\n        child.exitCode.pipe(Effect.map(Number)),\n      ],\n      { concurrency: \"unbounded\" },\n    );\n\n    return { stdout, stderr, code: exitCode } satisfies CommandResult;\n  }).pipe(Effect.scoped);\n\nconst runCursorAboutCommand = (cursorSettings: CursorSettings, environment?: NodeJS.ProcessEnv) =>\n  Effect.gen(function* () {\n    const jsonResult = yield* runCursorCommand(\n      cursorSettings,\n      [\"about\", \"--format\", \"json\"],\n      environment,\n    );\n    if (!isCursorAboutJsonFormatUnsupported(jsonResult)) {\n      return jsonResult;\n    }\n    return yield* runCursorCommand(cursorSettings, [\"about\"], environment);\n  });\n\nexport const checkCursorProviderStatus = Effect.fn(\"checkCursorProviderStatus\")(function* (\n  cursorSettings: CursorSettings,\n  environment?: NodeJS.ProcessEnv,\n): Effect.fn.Return<\n  ServerProviderDraft,\n  never,\n  ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path\n> {\n  const checkedAt = DateTime.formatIso(yield* DateTime.now);\n  const fallbackModels = getCursorFallbackModels(cursorSettings);\n\n  if (!cursorSettings.enabled) {\n    return buildServerProvider({\n      presentation: CURSOR_PRESENTATION,\n      enabled: false,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Cursor is disabled in Synaptic Code settings.\",\n      },\n    });\n  }\n\n  // Single `agent about` probe: returns version + auth status in one call.\n  const aboutProbe = yield* runCursorAboutCommand(cursorSettings, environment).pipe(\n    Effect.timeoutOption(ABOUT_TIMEOUT_MS),\n    Effect.result,\n  );\n\n  if (Result.isFailure(aboutProbe)) {\n    const error = aboutProbe.failure;\n    yield* Effect.logWarning(\"Cursor Agent CLI health check failed.\", {\n      errorTag: error._tag,\n    });\n    return buildServerProvider({\n      presentation: CURSOR_PRESENTATION,\n      enabled: cursorSettings.enabled,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: !isCommandMissingCause(error),\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: isCommandMissingCause(error)\n          ? buildCursorCliCommandMissingMessage(cursorSettings.binaryPath)\n          : \"Failed to execute Cursor Agent CLI health check.\",\n      },\n    });\n  }\n\n  if (Option.isNone(aboutProbe.success)) {\n    return buildServerProvider({\n      presentation: CURSOR_PRESENTATION,\n      enabled: cursorSettings.enabled,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: true,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: \"Cursor Agent CLI is installed but timed out while running `agent about`.\",\n      },\n    });\n  }\n\n  const parsed = parseCursorAboutOutput(aboutProbe.success.value);\n  const cursorCliConfigChannel = yield* readCursorCliConfigChannel();\n  const parameterizedModelPickerUnsupportedMessage =\n    getCursorParameterizedModelPickerUnsupportedMessage({\n      version: parsed.version,\n      channel: cursorCliConfigChannel,\n    });\n  if (parameterizedModelPickerUnsupportedMessage) {\n    return buildServerProvider({\n      presentation: CURSOR_PRESENTATION,\n      enabled: cursorSettings.enabled,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: true,\n        version: parsed.version,\n        status: \"error\",\n        auth: parsed.auth,\n        message:\n          parsed.auth.status === \"unauthenticated\" && parsed.message\n            ? `${parameterizedModelPickerUnsupportedMessage} ${parsed.message}`\n            : parameterizedModelPickerUnsupportedMessage,\n      },\n    });\n  }\n  let discoveredModels = Option.none<ReadonlyArray<ServerProviderModel>>();\n  let discoveryWarning: string | undefined;\n  if (parsed.auth.status !== \"unauthenticated\") {\n    const discoveryExit = yield* Effect.exit(\n      discoverCursorModelsViaAcp(cursorSettings, environment).pipe(\n        Effect.timeoutOption(CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS),\n      ),\n    );\n    if (Exit.isFailure(discoveryExit)) {\n      yield* Effect.logWarning(\"Cursor ACP model discovery failed\", {\n        errorTag: causeErrorTag(discoveryExit.cause),\n      });\n      discoveryWarning = CURSOR_ACP_MODEL_DISCOVERY_FAILED_MESSAGE;\n    } else if (Option.isNone(discoveryExit.value)) {\n      discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;\n    } else if (discoveryExit.value.value.length === 0) {\n      discoveryWarning = \"Cursor ACP model discovery returned no built-in models.\";\n    } else {\n      discoveredModels = discoveryExit.value;\n    }\n  }\n  return buildCursorProviderSnapshot({\n    checkedAt,\n    cursorSettings,\n    parsed,\n    discoveredModels: Option.getOrElse(\n      Option.filter(discoveredModels, (models) => models.length > 0),\n      () => [] as const,\n    ),\n    ...(discoveryWarning ? { discoveryWarning } : {}),\n  });\n});\n\n/**\n * Background maintenance enrichment for a Cursor snapshot.\n *\n * Used by `CursorDriver` as the `makeManagedServerProvider.enrichSnapshot`\n * hook: republishes update/version advisory metadata without performing any\n * model or capability discovery. Cursor model data comes exclusively from\n * `cursor/list_available_models` during provider status checks.\n */\nexport const enrichCursorSnapshot = (input: {\n  readonly settings: CursorSettings;\n  readonly snapshot: ServerProvider;\n  readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;\n  readonly enableProviderUpdateChecks?: boolean;\n  readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;\n  readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;\n  readonly httpClient: HttpClient.HttpClient;\n}): Effect.Effect<void> => {\n  const { settings, snapshot, publishSnapshot } = input;\n  const stampIdentity = input.stampIdentity ?? ((value) => value);\n\n  if (!settings.enabled || snapshot.auth.status === \"unauthenticated\") {\n    return Effect.void;\n  }\n\n  return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {\n    enableProviderUpdateChecks: input.enableProviderUpdateChecks,\n  }).pipe(\n    Effect.provideService(HttpClient.HttpClient, input.httpClient),\n    Effect.flatMap((enrichedSnapshot) =>\n      publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),\n    ),\n    Effect.catchCause((cause) =>\n      Effect.logWarning(\"Cursor version advisory enrichment failed\", {\n        errorTag: causeErrorTag(cause),\n      }).pipe(Effect.asVoid),\n    ),\n  );\n};\n","import { type CursorSettings, type ProviderOptionSelection } from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Scope from \"effect/Scope\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport type * as EffectAcpErrors from \"effect-acp/errors\";\n\nimport {\n  CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,\n  resolveCursorAcpBaseModelId,\n  resolveCursorAcpConfigUpdates,\n} from \"../Layers/CursorProvider.ts\";\nimport * as AcpSessionRuntime from \"./AcpSessionRuntime.ts\";\n\ntype CursorAcpRuntimeCursorSettings = Pick<CursorSettings, \"apiEndpoint\" | \"binaryPath\">;\n\nexport interface CursorAcpRuntimeInput extends Omit<\n  AcpSessionRuntime.AcpSessionRuntimeOptions,\n  \"authMethodId\" | \"clientCapabilities\" | \"spawn\"\n> {\n  readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner[\"Service\"];\n  readonly cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined;\n  readonly environment?: NodeJS.ProcessEnv;\n}\n\nexport interface CursorAcpModelSelectionErrorContext {\n  readonly cause: EffectAcpErrors.AcpError;\n  readonly step: \"set-config-option\" | \"set-model\";\n  readonly configId?: string;\n}\n\nexport function buildCursorAcpSpawnInput(\n  cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined,\n  cwd: string,\n  environment?: NodeJS.ProcessEnv,\n): AcpSessionRuntime.AcpSpawnInput {\n  return {\n    command: cursorSettings?.binaryPath || \"cursor-agent\",\n    args: [\n      ...(cursorSettings?.apiEndpoint ? ([\"-e\", cursorSettings.apiEndpoint] as const) : []),\n      \"acp\",\n    ],\n    cwd,\n    ...(environment ? { env: environment } : {}),\n  };\n}\n\nexport const makeCursorAcpRuntime = (\n  input: CursorAcpRuntimeInput,\n): Effect.Effect<\n  AcpSessionRuntime.AcpSessionRuntime[\"Service\"],\n  EffectAcpErrors.AcpError,\n  Crypto.Crypto | Scope.Scope\n> =>\n  Effect.gen(function* () {\n    const acpContext = yield* Layer.build(\n      AcpSessionRuntime.layer({\n        ...input,\n        spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd, input.environment),\n        authMethodId: \"cursor_login\",\n        clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,\n      }).pipe(\n        Layer.provide(\n          Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),\n        ),\n      ),\n    );\n    return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(\n      Effect.provide(acpContext),\n    );\n  });\n\ninterface CursorAcpModelSelectionRuntime {\n  readonly getConfigOptions: AcpSessionRuntime.AcpSessionRuntime[\"Service\"][\"getConfigOptions\"];\n  readonly setConfigOption: (\n    configId: string,\n    value: string | boolean,\n  ) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;\n  readonly setModel: (model: string) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;\n}\n\nexport function applyCursorAcpModelSelection<E>(input: {\n  readonly runtime: CursorAcpModelSelectionRuntime;\n  readonly model: string | null | undefined;\n  readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;\n  readonly mapError: (context: CursorAcpModelSelectionErrorContext) => E;\n}): Effect.Effect<void, E> {\n  return Effect.gen(function* () {\n    yield* input.runtime.setModel(resolveCursorAcpBaseModelId(input.model)).pipe(\n      Effect.mapError((cause) =>\n        input.mapError({\n          cause,\n          step: \"set-model\",\n        }),\n      ),\n    );\n\n    const configUpdates = resolveCursorAcpConfigUpdates(\n      yield* input.runtime.getConfigOptions,\n      input.selections,\n    );\n    for (const update of configUpdates) {\n      yield* input.runtime.setConfigOption(update.configId, update.value).pipe(\n        Effect.mapError((cause) =>\n          input.mapError({\n            cause,\n            step: \"set-config-option\",\n            configId: update.configId,\n          }),\n        ),\n      );\n    }\n  });\n}\n","import * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { type CursorSettings, type ModelSelection } from \"@t3tools/contracts\";\nimport { sanitizeBranchFragment, sanitizeFeatureBranchName } from \"@t3tools/shared/git\";\nimport { extractJsonObject } from \"@t3tools/shared/schemaJson\";\n\nimport { TextGenerationError } from \"@t3tools/contracts\";\nimport * as TextGeneration from \"./TextGeneration.ts\";\nimport {\n  buildBranchNamePrompt,\n  buildCommitMessagePrompt,\n  buildPrContentPrompt,\n  buildThreadTitlePrompt,\n} from \"./TextGenerationPrompts.ts\";\nimport {\n  sanitizeCommitSubject,\n  sanitizePrTitle,\n  sanitizeThreadTitle,\n} from \"./TextGenerationUtils.ts\";\nimport {\n  applyCursorAcpModelSelection,\n  makeCursorAcpRuntime,\n} from \"../provider/acp/CursorAcpSupport.ts\";\n\nconst CURSOR_TIMEOUT_MS = 180_000;\n\nconst isTextGenerationError = Schema.is(TextGenerationError);\n\n/**\n * Build a Cursor text-generation closure bound to a specific `CursorSettings`\n * payload. See `makeCodexAdapter` for the overall per-instance rationale.\n */\nexport const makeCursorTextGeneration = Effect.fn(\"makeCursorTextGeneration\")(function* (\n  cursorSettings: CursorSettings,\n  environment?: NodeJS.ProcessEnv,\n) {\n  const crypto = yield* Crypto.Crypto;\n  const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const resolvedEnvironment = environment ?? process.env;\n\n  const runCursorJson = <S extends Schema.Top>({\n    operation,\n    cwd,\n    prompt,\n    outputSchemaJson,\n    modelSelection,\n  }: {\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\";\n    cwd: string;\n    prompt: string;\n    outputSchemaJson: S;\n    modelSelection: ModelSelection;\n  }): Effect.Effect<S[\"Type\"], TextGenerationError, S[\"DecodingServices\"]> =>\n    Effect.gen(function* () {\n      const outputRef = yield* Ref.make(\"\");\n      const runtime = yield* makeCursorAcpRuntime({\n        cursorSettings,\n        environment: resolvedEnvironment,\n        childProcessSpawner: commandSpawner,\n        cwd,\n        clientInfo: { name: \"synaptic-code-git-text\", version: \"0.0.0\" },\n      }).pipe(Effect.provideService(Crypto.Crypto, crypto));\n\n      yield* runtime.handleSessionUpdate((notification) => {\n        const update = notification.update;\n        if (update.sessionUpdate !== \"agent_message_chunk\") {\n          return Effect.void;\n        }\n        const content = update.content;\n        if (content.type !== \"text\") {\n          return Effect.void;\n        }\n        return Ref.update(outputRef, (current) => current + content.text);\n      });\n\n      const promptResult = yield* Effect.gen(function* () {\n        yield* runtime.start();\n        yield* Effect.ignore(runtime.setMode(\"ask\"));\n        yield* applyCursorAcpModelSelection({\n          runtime,\n          model: modelSelection.model,\n          selections: modelSelection.options,\n          mapError: ({ cause, configId, step }) =>\n            new TextGenerationError({\n              operation,\n              detail:\n                step === \"set-config-option\"\n                  ? `Failed to set Cursor ACP config option \"${configId}\" for text generation.`\n                  : \"Failed to set Cursor ACP base model for text generation.\",\n              cause,\n            }),\n        });\n\n        return yield* runtime.prompt({\n          prompt: [{ type: \"text\", text: prompt }],\n        });\n      }).pipe(\n        Effect.timeoutOption(CURSOR_TIMEOUT_MS),\n        Effect.flatMap(\n          Option.match({\n            onNone: () =>\n              Effect.fail(\n                new TextGenerationError({\n                  operation,\n                  detail: \"Cursor Agent request timed out.\",\n                }),\n              ),\n            onSome: (value) => Effect.succeed(value),\n          }),\n        ),\n        Effect.mapError((cause) =>\n          isTextGenerationError(cause)\n            ? cause\n            : new TextGenerationError({\n                operation,\n                detail: \"Cursor ACP request failed.\",\n                cause,\n              }),\n        ),\n      );\n\n      const rawResult = (yield* Ref.get(outputRef)).trim();\n      if (!rawResult) {\n        return yield* new TextGenerationError({\n          operation,\n          detail:\n            promptResult.stopReason === \"cancelled\"\n              ? \"Cursor ACP request was cancelled.\"\n              : \"Cursor Agent returned empty output.\",\n        });\n      }\n\n      const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));\n      return yield* decodeOutput(extractJsonObject(rawResult)).pipe(\n        Effect.catchTags({\n          SchemaError: (cause) =>\n            Effect.fail(\n              new TextGenerationError({\n                operation,\n                detail: \"Cursor Agent returned invalid structured output.\",\n                cause,\n              }),\n            ),\n        }),\n      );\n    }).pipe(\n      Effect.mapError((cause) =>\n        isTextGenerationError(cause)\n          ? cause\n          : new TextGenerationError({\n              operation,\n              detail: \"Cursor ACP text generation failed.\",\n              cause,\n            }),\n      ),\n      Effect.scoped,\n    );\n\n  const generateCommitMessage: TextGeneration.TextGeneration[\"Service\"][\"generateCommitMessage\"] =\n    Effect.fn(\"CursorTextGeneration.generateCommitMessage\")(function* (input) {\n      const { prompt, outputSchema } = buildCommitMessagePrompt({\n        branch: input.branch,\n        stagedSummary: input.stagedSummary,\n        stagedPatch: input.stagedPatch,\n        includeBranch: input.includeBranch === true,\n        policy: input.policy,\n      });\n\n      const generated = yield* runCursorJson({\n        operation: \"generateCommitMessage\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        subject: sanitizeCommitSubject(generated.subject),\n        body: generated.body.trim(),\n        ...(\"branch\" in generated && typeof generated.branch === \"string\"\n          ? { branch: sanitizeFeatureBranchName(generated.branch) }\n          : {}),\n      };\n    });\n\n  const generatePrContent: TextGeneration.TextGeneration[\"Service\"][\"generatePrContent\"] =\n    Effect.fn(\"CursorTextGeneration.generatePrContent\")(function* (input) {\n      const { prompt, outputSchema } = buildPrContentPrompt({\n        baseBranch: input.baseBranch,\n        headBranch: input.headBranch,\n        commitSummary: input.commitSummary,\n        diffSummary: input.diffSummary,\n        diffPatch: input.diffPatch,\n        policy: input.policy,\n        changeRequestTemplate: input.changeRequestTemplate,\n      });\n\n      const generated = yield* runCursorJson({\n        operation: \"generatePrContent\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizePrTitle(generated.title),\n        body: generated.body.trim(),\n      };\n    });\n\n  const generateBranchName: TextGeneration.TextGeneration[\"Service\"][\"generateBranchName\"] =\n    Effect.fn(\"CursorTextGeneration.generateBranchName\")(function* (input) {\n      const { prompt, outputSchema } = buildBranchNamePrompt({\n        message: input.message,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runCursorJson({\n        operation: \"generateBranchName\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        branch: sanitizeBranchFragment(generated.branch),\n      };\n    });\n\n  const generateThreadTitle: TextGeneration.TextGeneration[\"Service\"][\"generateThreadTitle\"] =\n    Effect.fn(\"CursorTextGeneration.generateThreadTitle\")(function* (input) {\n      const { prompt, outputSchema } = buildThreadTitlePrompt({\n        message: input.message,\n        previousTitle: input.previousTitle,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runCursorJson({\n        operation: \"generateThreadTitle\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizeThreadTitle(generated.title),\n      } satisfies TextGeneration.ThreadTitleGenerationResult;\n    });\n\n  return {\n    generateCommitMessage,\n    generatePrContent,\n    generateBranchName,\n    generateThreadTitle,\n  } satisfies TextGeneration.TextGeneration[\"Service\"];\n});\n","import {\n  type ProviderApprovalDecision,\n  type ProviderDriverKind,\n  type ThreadId,\n} from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as EffectAcpErrors from \"effect-acp/errors\";\n\nimport {\n  ProviderAdapterRequestError,\n  ProviderAdapterSessionClosedError,\n  type ProviderAdapterError,\n} from \"../Errors.ts\";\nconst isAcpProcessExitedError = Schema.is(EffectAcpErrors.AcpProcessExitedError);\nconst isAcpRequestError = Schema.is(EffectAcpErrors.AcpRequestError);\n\nexport function mapAcpToAdapterError(\n  provider: ProviderDriverKind,\n  threadId: ThreadId,\n  method: string,\n  error: EffectAcpErrors.AcpError,\n): ProviderAdapterError {\n  if (isAcpProcessExitedError(error)) {\n    return new ProviderAdapterSessionClosedError({\n      provider,\n      threadId,\n      cause: error,\n    });\n  }\n  if (isAcpRequestError(error)) {\n    return new ProviderAdapterRequestError({\n      provider,\n      method,\n      detail: error.message,\n      cause: error,\n    });\n  }\n  return new ProviderAdapterRequestError({\n    provider,\n    method,\n    detail: error.message,\n    cause: error,\n  });\n}\n\nexport function acpPermissionOutcome(decision: ProviderApprovalDecision): string {\n  switch (decision) {\n    case \"acceptForSession\":\n      return \"allow-always\";\n    case \"accept\":\n      return \"allow-once\";\n    case \"decline\":\n    default:\n      return \"reject-once\";\n  }\n}\n","import {\n  type RuntimeEventRawSource,\n  RuntimeItemId,\n  type CanonicalRequestType,\n  type EventId,\n  type ProviderApprovalDecision,\n  type ProviderDriverKind,\n  type ProviderRuntimeEvent,\n  type RuntimeRequestId,\n  type ThreadId,\n  type ToolLifecycleItemType,\n  type TurnId,\n} from \"@t3tools/contracts\";\n\nimport type { AcpPermissionRequest, AcpPlanUpdate, AcpToolCallState } from \"./AcpRuntimeModel.ts\";\n\ntype AcpAdapterRawSource = Extract<\n  RuntimeEventRawSource,\n  \"acp.jsonrpc\" | `acp.${string}.extension`\n>;\n\ninterface AcpEventStamp {\n  readonly eventId: EventId;\n  readonly createdAt: string;\n}\n\ntype AcpCanonicalRequestType = Extract<\n  CanonicalRequestType,\n  \"exec_command_approval\" | \"file_read_approval\" | \"file_change_approval\" | \"dynamic_tool_call\"\n>;\n\nfunction canonicalRequestTypeFromAcpKind(kind: string | \"unknown\"): AcpCanonicalRequestType {\n  switch (kind) {\n    case \"execute\":\n      return \"exec_command_approval\";\n    case \"read\":\n      return \"file_read_approval\";\n    case \"edit\":\n    case \"delete\":\n    case \"move\":\n      return \"file_change_approval\";\n    default:\n      return \"dynamic_tool_call\";\n  }\n}\n\nfunction canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {\n  switch (kind) {\n    case \"execute\":\n      return \"command_execution\";\n    case \"edit\":\n    case \"delete\":\n    case \"move\":\n      return \"file_change\";\n    case \"search\":\n    case \"fetch\":\n      return \"web_search\";\n    default:\n      return \"dynamic_tool_call\";\n  }\n}\n\nfunction runtimeItemStatusFromAcpToolStatus(\n  status: AcpToolCallState[\"status\"],\n): \"inProgress\" | \"completed\" | \"failed\" | undefined {\n  switch (status) {\n    case \"pending\":\n    case \"inProgress\":\n      return \"inProgress\";\n    case \"completed\":\n      return \"completed\";\n    case \"failed\":\n      return \"failed\";\n    default:\n      return undefined;\n  }\n}\n\nexport function makeAcpRequestOpenedEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly requestId: RuntimeRequestId;\n  readonly permissionRequest: AcpPermissionRequest;\n  readonly detail: string;\n  readonly args: unknown;\n  readonly source: AcpAdapterRawSource;\n  readonly method: string;\n  readonly rawPayload: unknown;\n}): ProviderRuntimeEvent {\n  return {\n    type: \"request.opened\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    requestId: input.requestId,\n    payload: {\n      requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),\n      detail: input.detail,\n      args: input.args,\n    },\n    raw: {\n      source: input.source,\n      method: input.method,\n      payload: input.rawPayload,\n    },\n  };\n}\n\nexport function makeAcpRequestResolvedEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly requestId: RuntimeRequestId;\n  readonly permissionRequest: AcpPermissionRequest;\n  readonly decision: ProviderApprovalDecision;\n}): ProviderRuntimeEvent {\n  return {\n    type: \"request.resolved\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    requestId: input.requestId,\n    payload: {\n      requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),\n      decision: input.decision,\n    },\n  };\n}\n\nexport function makeAcpPlanUpdatedEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly payload: AcpPlanUpdate;\n  readonly source: AcpAdapterRawSource;\n  readonly method: string;\n  readonly rawPayload: unknown;\n}): ProviderRuntimeEvent {\n  return {\n    type: \"turn.plan.updated\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    payload: input.payload,\n    raw: {\n      source: input.source,\n      method: input.method,\n      payload: input.rawPayload,\n    },\n  };\n}\n\nexport function makeAcpToolCallEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly toolCall: AcpToolCallState;\n  readonly rawPayload: unknown;\n}): ProviderRuntimeEvent {\n  const runtimeStatus = runtimeItemStatusFromAcpToolStatus(input.toolCall.status);\n  return {\n    type:\n      input.toolCall.status === \"completed\" || input.toolCall.status === \"failed\"\n        ? \"item.completed\"\n        : \"item.updated\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    itemId: RuntimeItemId.make(input.toolCall.toolCallId),\n    payload: {\n      itemType: canonicalItemTypeFromAcpToolKind(input.toolCall.kind),\n      ...(runtimeStatus ? { status: runtimeStatus } : {}),\n      ...(input.toolCall.title ? { title: input.toolCall.title } : {}),\n      ...(input.toolCall.detail ? { detail: input.toolCall.detail } : {}),\n      ...(Object.keys(input.toolCall.data).length > 0 ? { data: input.toolCall.data } : {}),\n    },\n    raw: {\n      source: \"acp.jsonrpc\",\n      method: \"session/update\",\n      payload: input.rawPayload,\n    },\n  };\n}\n\nexport function makeAcpAssistantItemEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly itemId: string;\n  readonly lifecycle: \"item.started\" | \"item.completed\";\n}): ProviderRuntimeEvent {\n  return {\n    type: input.lifecycle,\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    itemId: RuntimeItemId.make(input.itemId),\n    payload: {\n      itemType: \"assistant_message\",\n      status: input.lifecycle === \"item.completed\" ? \"completed\" : \"inProgress\",\n    },\n  };\n}\n\nexport function makeAcpContentDeltaEvent(input: {\n  readonly stamp: AcpEventStamp;\n  readonly provider: ProviderDriverKind;\n  readonly threadId: ThreadId;\n  readonly turnId: TurnId | undefined;\n  readonly itemId?: string;\n  readonly text: string;\n  readonly rawPayload: unknown;\n}): ProviderRuntimeEvent {\n  return {\n    type: \"content.delta\",\n    ...input.stamp,\n    provider: input.provider,\n    threadId: input.threadId,\n    turnId: input.turnId,\n    ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),\n    payload: {\n      streamKind: \"assistant_text\",\n      delta: input.text,\n    },\n    raw: {\n      source: \"acp.jsonrpc\",\n      method: \"session/update\",\n      payload: input.rawPayload,\n    },\n  };\n}\n","import type { ProviderDriverKind, ThreadId } from \"@t3tools/contracts\";\nimport { causeErrorTag, errorTag } from \"@t3tools/shared/observability\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport type * as EffectAcpProtocol from \"effect-acp/protocol\";\n\nimport type { EventNdjsonLogger } from \"../Layers/EventNdjsonLogger.ts\";\nimport type * as AcpSessionRuntime from \"./AcpSessionRuntime.ts\";\n\nfunction structuralMethod(value: string): string {\n  return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : \"unknown\";\n}\n\nfunction summarizePayload(payload: unknown): Readonly<Record<string, unknown>> {\n  if (payload === null) return { valueType: \"null\" };\n  if (typeof payload === \"string\") {\n    return { valueType: \"string\", byteLength: new TextEncoder().encode(payload).byteLength };\n  }\n  if (payload instanceof Uint8Array) {\n    return { valueType: \"bytes\", byteLength: payload.byteLength };\n  }\n  if (Array.isArray(payload)) {\n    return { valueType: \"array\", itemCount: payload.length };\n  }\n  if (typeof payload !== \"object\") {\n    return { valueType: typeof payload };\n  }\n\n  try {\n    const record = payload as Record<string, unknown>;\n    return {\n      valueType: \"object\",\n      fieldCount: Object.keys(record).length,\n      ...(typeof record._tag === \"string\" ? { messageTag: errorTag(record) } : {}),\n      ...(typeof record.tag === \"string\" ? { method: structuralMethod(record.tag) } : {}),\n    };\n  } catch {\n    return { valueType: \"object\" };\n  }\n}\n\nfunction formatRequestLogPayload(event: AcpSessionRuntime.AcpSessionRequestLogEvent) {\n  return {\n    method: structuralMethod(event.method),\n    status: event.status,\n    request: summarizePayload(event.payload),\n    ...(event.result !== undefined ? { result: summarizePayload(event.result) } : {}),\n    ...(event.cause !== undefined\n      ? {\n          errorTag: causeErrorTag(event.cause),\n          reasonCount: event.cause.reasons.length,\n        }\n      : {}),\n  };\n}\n\nfunction formatProtocolLogPayload(event: EffectAcpProtocol.AcpProtocolLogEvent) {\n  return {\n    direction: event.direction,\n    stage: event.stage,\n    payload: summarizePayload(event.payload),\n  };\n}\n\nexport const makeAcpNativeLoggerFactory = Effect.fn(\"makeAcpNativeLoggerFactory\")(function* () {\n  const crypto = yield* Crypto.Crypto;\n  return (input: {\n    readonly nativeEventLogger: EventNdjsonLogger | undefined;\n    readonly provider: ProviderDriverKind;\n    readonly threadId: ThreadId;\n  }): Pick<AcpSessionRuntime.AcpSessionRuntimeOptions, \"requestLogger\" | \"protocolLogging\"> => {\n    const writeNativeAcpLog = (logInput: {\n      readonly kind: \"request\" | \"protocol\";\n      readonly payload: unknown;\n    }) =>\n      Effect.gen(function* () {\n        if (!input.nativeEventLogger) return;\n        const observedAt = DateTime.formatIso(yield* DateTime.now);\n        yield* input.nativeEventLogger.write(\n          {\n            observedAt,\n            event: {\n              id: yield* crypto.randomUUIDv4,\n              kind: logInput.kind,\n              provider: input.provider,\n              createdAt: observedAt,\n              threadId: input.threadId,\n              payload: logInput.payload,\n            },\n          },\n          input.threadId,\n        );\n      }).pipe(\n        Effect.catchCause((cause) =>\n          Cause.hasInterrupts(cause)\n            ? Effect.interrupt\n            : Effect.logWarning(\"Failed to write native ACP event log.\", {\n                errorTag: causeErrorTag(cause),\n                reasonCount: cause.reasons.length,\n                provider: input.provider,\n                threadId: input.threadId,\n              }),\n        ),\n      );\n\n    return {\n      requestLogger: (event: AcpSessionRuntime.AcpSessionRequestLogEvent) =>\n        writeNativeAcpLog({\n          kind: \"request\",\n          payload: formatRequestLogPayload(event),\n        }),\n      ...(input.nativeEventLogger\n        ? {\n            protocolLogging: {\n              logIncoming: true,\n              logOutgoing: true,\n              logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>\n                writeNativeAcpLog({\n                  kind: \"protocol\",\n                  payload: formatProtocolLogPayload(event),\n                }),\n            } satisfies NonNullable<AcpSessionRuntime.AcpSessionRuntimeOptions[\"protocolLogging\"]>,\n          }\n        : {}),\n    };\n  };\n});\n","/**\n * CursorAdapterLive — Cursor CLI (`agent acp`) via ACP.\n *\n * @module CursorAdapterLive\n */\n\nimport {\n  ApprovalRequestId,\n  type CursorSettings,\n  type ProviderOptionSelection,\n  EventId,\n  type ProviderApprovalDecision,\n  type ProviderInteractionMode,\n  type ProviderRuntimeEvent,\n  type ProviderSession,\n  type ProviderUserInputAnswers,\n  ProviderDriverKind,\n  ProviderInstanceId,\n  RuntimeRequestId,\n  type RuntimeMode,\n  type ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as EffectAcpErrors from \"effect-acp/errors\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\n\nimport { resolveAttachmentPath } from \"../../attachmentStore.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport * as McpProviderSession from \"../../mcp/McpProviderSession.ts\";\nimport {\n  ProviderAdapterProcessError,\n  ProviderAdapterRequestError,\n  ProviderAdapterSessionNotFoundError,\n  ProviderAdapterValidationError,\n} from \"../Errors.ts\";\nimport { acpPermissionOutcome, mapAcpToAdapterError } from \"../acp/AcpAdapterSupport.ts\";\nimport type * as AcpSessionRuntime from \"../acp/AcpSessionRuntime.ts\";\nimport {\n  makeAcpAssistantItemEvent,\n  makeAcpContentDeltaEvent,\n  makeAcpPlanUpdatedEvent,\n  makeAcpRequestOpenedEvent,\n  makeAcpRequestResolvedEvent,\n  makeAcpToolCallEvent,\n} from \"../acp/AcpCoreRuntimeEvents.ts\";\nimport {\n  type AcpSessionMode,\n  type AcpSessionModeState,\n  parsePermissionRequest,\n} from \"../acp/AcpRuntimeModel.ts\";\nimport { makeAcpNativeLoggerFactory } from \"../acp/AcpNativeLogging.ts\";\nimport { applyCursorAcpModelSelection, makeCursorAcpRuntime } from \"../acp/CursorAcpSupport.ts\";\nimport {\n  CursorAskQuestionRequest,\n  CursorCreatePlanRequest,\n  CursorUpdateTodosRequest,\n  extractAskQuestions,\n  extractPlanMarkdown,\n  extractTodosAsPlan,\n} from \"../acp/CursorAcpExtension.ts\";\nimport { type CursorAdapterShape } from \"../Services/CursorAdapter.ts\";\nimport { resolveCursorAcpBaseModelId } from \"./CursorProvider.ts\";\nimport { type EventNdjsonLogger, makeEventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\nconst encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));\n\nconst PROVIDER = ProviderDriverKind.make(\"cursor\");\nconst CURSOR_RESUME_VERSION = 1 as const;\nconst ACP_PLAN_MODE_ALIASES = [\"plan\", \"architect\"];\nconst ACP_IMPLEMENT_MODE_ALIASES = [\"code\", \"agent\", \"default\", \"chat\", \"implement\"];\nconst ACP_APPROVAL_MODE_ALIASES = [\"ask\"];\n\nfunction encodeJsonStringForDiagnostics(input: unknown): string | undefined {\n  const result = encodeUnknownJsonStringExit(input);\n  return Exit.isSuccess(result) ? result.value : undefined;\n}\n\nexport interface CursorAdapterLiveOptions {\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly nativeEventLogPath?: string;\n  readonly nativeEventLogger?: EventNdjsonLogger;\n  /**\n   * Selections are honored when `modelSelection.instanceId` matches this value.\n   * Defaults to the legacy built-in instance id (`cursor`).\n   */\n  readonly instanceId?: ProviderInstanceId;\n  /**\n   * Optional per-session settings resolver. When provided the adapter yields\n   * this effect at the start of every session and uses the result instead of\n   * the `cursorSettings` captured at construction.\n   *\n   * Production instances bind settings to the instance scope (the hydration\n   * layer rebuilds the adapter on config change) and leave this undefined.\n   * Test suites that mutate `ServerSettingsService` mid-flight — e.g. to\n   * swap `binaryPath` to a mock ACP wrapper — pass a resolver that reads\n   * the latest snapshot so the closure isn't stale.\n   */\n  readonly resolveSettings?: Effect.Effect<CursorSettings>;\n}\n\ninterface PendingApproval {\n  readonly decision: Deferred.Deferred<ProviderApprovalDecision>;\n  readonly kind: string | \"unknown\";\n}\n\ninterface PendingUserInput {\n  readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;\n}\n\ninterface CursorSessionContext {\n  readonly threadId: ThreadId;\n  session: ProviderSession;\n  readonly scope: Scope.Closeable;\n  readonly acp: AcpSessionRuntime.AcpSessionRuntime[\"Service\"];\n  notificationFiber: Fiber.Fiber<void, never> | undefined;\n  readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;\n  readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;\n  readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;\n  lastPlanFingerprint: string | undefined;\n  activeTurnId: TurnId | undefined;\n  /** Number of sendTurn prompts currently in flight or being prepared.\n   * >0 means a turn is actively running, so a new sendTurn is a steer that\n   * continues it, and only the last remaining prompt settles the turn. */\n  promptsInFlight: number;\n  stopped: boolean;\n}\n\nfunction settlePendingApprovalsAsCancelled(\n  pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,\n): Effect.Effect<void> {\n  const pendingEntries = Array.from(pendingApprovals.values());\n  return Effect.forEach(\n    pendingEntries,\n    (pending) => Deferred.succeed(pending.decision, \"cancel\").pipe(Effect.ignore),\n    {\n      discard: true,\n    },\n  );\n}\n\nfunction settlePendingUserInputsAsEmptyAnswers(\n  pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,\n): Effect.Effect<void> {\n  const pendingEntries = Array.from(pendingUserInputs.values());\n  return Effect.forEach(\n    pendingEntries,\n    (pending) => Deferred.succeed(pending.answers, {}).pipe(Effect.ignore),\n    {\n      discard: true,\n    },\n  );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseCursorResume(raw: unknown): { sessionId: string } | undefined {\n  if (!isRecord(raw)) return undefined;\n  if (raw.schemaVersion !== CURSOR_RESUME_VERSION) return undefined;\n  if (typeof raw.sessionId !== \"string\" || !raw.sessionId.trim()) return undefined;\n  return { sessionId: raw.sessionId.trim() };\n}\n\nfunction normalizeModeSearchText(mode: AcpSessionMode): string {\n  return [mode.id, mode.name, mode.description]\n    .filter((value): value is string => typeof value === \"string\" && value.length > 0)\n    .join(\" \")\n    .toLowerCase()\n    .replace(/[^a-z0-9]+/g, \" \")\n    .trim();\n}\n\nfunction findModeByAliases(\n  modes: ReadonlyArray<AcpSessionMode>,\n  aliases: ReadonlyArray<string>,\n): AcpSessionMode | undefined {\n  const normalizedAliases = aliases.map((alias) => alias.toLowerCase());\n  for (const alias of normalizedAliases) {\n    const exact = modes.find((mode) => {\n      const id = mode.id.toLowerCase();\n      const name = mode.name.toLowerCase();\n      return id === alias || name === alias;\n    });\n    if (exact) {\n      return exact;\n    }\n  }\n  for (const alias of normalizedAliases) {\n    const partial = modes.find((mode) => normalizeModeSearchText(mode).includes(alias));\n    if (partial) {\n      return partial;\n    }\n  }\n  return undefined;\n}\n\nfunction isPlanMode(mode: AcpSessionMode): boolean {\n  return findModeByAliases([mode], ACP_PLAN_MODE_ALIASES) !== undefined;\n}\n\nfunction resolveRequestedModeId(input: {\n  readonly interactionMode: ProviderInteractionMode | undefined;\n  readonly runtimeMode: RuntimeMode;\n  readonly modeState: AcpSessionModeState | undefined;\n}): string | undefined {\n  const modeState = input.modeState;\n  if (!modeState) {\n    return undefined;\n  }\n\n  if (input.interactionMode === \"plan\") {\n    return findModeByAliases(modeState.availableModes, ACP_PLAN_MODE_ALIASES)?.id;\n  }\n\n  if (input.runtimeMode === \"approval-required\") {\n    return (\n      findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??\n      findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??\n      modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??\n      modeState.currentModeId\n    );\n  }\n\n  return (\n    findModeByAliases(modeState.availableModes, ACP_IMPLEMENT_MODE_ALIASES)?.id ??\n    findModeByAliases(modeState.availableModes, ACP_APPROVAL_MODE_ALIASES)?.id ??\n    modeState.availableModes.find((mode) => !isPlanMode(mode))?.id ??\n    modeState.currentModeId\n  );\n}\n\nfunction applyRequestedSessionConfiguration<E>(input: {\n  readonly runtime: AcpSessionRuntime.AcpSessionRuntime[\"Service\"];\n  readonly runtimeMode: RuntimeMode;\n  readonly interactionMode: ProviderInteractionMode | undefined;\n  readonly modelSelection:\n    | {\n        readonly model: string;\n        readonly options?: ReadonlyArray<ProviderOptionSelection> | null | undefined;\n      }\n    | undefined;\n  readonly mapError: (context: {\n    readonly cause: import(\"effect-acp/errors\").AcpError;\n    readonly method: \"session/set_config_option\" | \"session/set_mode\";\n  }) => E;\n}): Effect.Effect<void, E> {\n  return Effect.gen(function* () {\n    if (input.modelSelection) {\n      yield* applyCursorAcpModelSelection({\n        runtime: input.runtime,\n        model: input.modelSelection.model,\n        selections: input.modelSelection.options,\n        mapError: ({ cause }) =>\n          input.mapError({\n            cause,\n            method: \"session/set_config_option\",\n          }),\n      });\n    }\n\n    const requestedModeId = resolveRequestedModeId({\n      interactionMode: input.interactionMode,\n      runtimeMode: input.runtimeMode,\n      modeState: yield* input.runtime.getModeState,\n    });\n    if (!requestedModeId) {\n      return;\n    }\n\n    yield* input.runtime.setMode(requestedModeId).pipe(\n      Effect.mapError((cause) =>\n        input.mapError({\n          cause,\n          method: \"session/set_mode\",\n        }),\n      ),\n    );\n  });\n}\n\nfunction selectAutoApprovedPermissionOption(\n  request: EffectAcpSchema.RequestPermissionRequest,\n): string | undefined {\n  const allowAlwaysOption = request.options.find((option) => option.kind === \"allow_always\");\n  if (typeof allowAlwaysOption?.optionId === \"string\" && allowAlwaysOption.optionId.trim()) {\n    return allowAlwaysOption.optionId.trim();\n  }\n\n  const allowOnceOption = request.options.find((option) => option.kind === \"allow_once\");\n  if (typeof allowOnceOption?.optionId === \"string\" && allowOnceOption.optionId.trim()) {\n    return allowOnceOption.optionId.trim();\n  }\n\n  return undefined;\n}\n\nexport function makeCursorAdapter(\n  cursorSettings: CursorSettings,\n  options?: CursorAdapterLiveOptions,\n) {\n  return Effect.gen(function* () {\n    const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make(\"cursor\");\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const serverConfig = yield* Effect.service(ServerConfig);\n    const crypto = yield* Crypto.Crypto;\n    const nativeEventLogger =\n      options?.nativeEventLogger ??\n      (options?.nativeEventLogPath !== undefined\n        ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {\n            stream: \"native\",\n          })\n        : undefined);\n    const managedNativeEventLogger =\n      options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n    const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();\n\n    const sessions = new Map<ThreadId, CursorSessionContext>();\n    const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());\n    const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();\n\n    const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n    const randomUUIDv4 = crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"crypto/randomUUIDv4\",\n            detail: \"Failed to generate Cursor runtime identifier.\",\n            cause,\n          }),\n      ),\n    );\n    const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));\n    const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });\n    const mapExtensionFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n      effect.pipe(\n        Effect.mapError(\n          (cause) =>\n            new EffectAcpErrors.AcpTransportError({\n              detail: \"Failed to process Cursor ACP extension event.\",\n              cause,\n            }),\n        ),\n      );\n\n    const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>\n      PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);\n\n    const getThreadSemaphore = (threadId: string) =>\n      SynchronizedRef.modifyEffect(threadLocksRef, (current) => {\n        const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(\n          current.get(threadId),\n        );\n        return Option.match(existing, {\n          onNone: () =>\n            Semaphore.make(1).pipe(\n              Effect.map((semaphore) => {\n                const next = new Map(current);\n                next.set(threadId, semaphore);\n                return [semaphore, next] as const;\n              }),\n            ),\n          onSome: (semaphore) => Effect.succeed([semaphore, current] as const),\n        });\n      });\n\n    const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>\n      Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));\n\n    const logNative = (\n      threadId: ThreadId,\n      method: string,\n      payload: unknown,\n      _source: \"acp.jsonrpc\" | \"acp.cursor.extension\",\n    ) =>\n      Effect.gen(function* () {\n        if (!nativeEventLogger) return;\n        const observedAt = yield* nowIso;\n        yield* nativeEventLogger.write(\n          {\n            observedAt,\n            event: {\n              id: yield* randomUUIDv4,\n              kind: \"notification\",\n              provider: PROVIDER,\n              createdAt: observedAt,\n              method,\n              threadId,\n              payload,\n            },\n          },\n          threadId,\n        );\n      });\n\n    const emitPlanUpdate = (\n      ctx: CursorSessionContext,\n      payload: {\n        readonly explanation?: string | null;\n        readonly plan: ReadonlyArray<{\n          readonly step: string;\n          readonly status: \"pending\" | \"inProgress\" | \"completed\";\n        }>;\n      },\n      rawPayload: unknown,\n      source: \"acp.jsonrpc\" | \"acp.cursor.extension\",\n      method: string,\n    ) =>\n      Effect.gen(function* () {\n        const fingerprint = `${ctx.activeTurnId ?? \"no-turn\"}:${encodeJsonStringForDiagnostics(payload) ?? \"[unserializable payload]\"}`;\n        if (ctx.lastPlanFingerprint === fingerprint) {\n          return;\n        }\n        ctx.lastPlanFingerprint = fingerprint;\n        yield* offerRuntimeEvent(\n          makeAcpPlanUpdatedEvent({\n            stamp: yield* makeEventStamp(),\n            provider: PROVIDER,\n            threadId: ctx.threadId,\n            turnId: ctx.activeTurnId,\n            payload,\n            source,\n            method,\n            rawPayload,\n          }),\n        );\n      });\n\n    const requireSession = (\n      threadId: ThreadId,\n    ): Effect.Effect<CursorSessionContext, ProviderAdapterSessionNotFoundError> => {\n      const ctx = sessions.get(threadId);\n      if (!ctx || ctx.stopped) {\n        return Effect.fail(\n          new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),\n        );\n      }\n      return Effect.succeed(ctx);\n    };\n\n    const stopSessionInternal = (ctx: CursorSessionContext) =>\n      Effect.gen(function* () {\n        if (ctx.stopped) return;\n        ctx.stopped = true;\n        yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);\n        yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);\n        if (ctx.notificationFiber) {\n          yield* Fiber.interrupt(ctx.notificationFiber);\n        }\n        yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));\n        sessions.delete(ctx.threadId);\n        yield* offerRuntimeEvent({\n          type: \"session.exited\",\n          ...(yield* makeEventStamp()),\n          provider: PROVIDER,\n          threadId: ctx.threadId,\n          payload: { exitKind: \"graceful\" },\n        });\n      });\n\n    const startSession: CursorAdapterShape[\"startSession\"] = (input) =>\n      withThreadLock(\n        input.threadId,\n        Effect.gen(function* () {\n          if (input.provider !== undefined && input.provider !== PROVIDER) {\n            return yield* new ProviderAdapterValidationError({\n              provider: PROVIDER,\n              operation: \"startSession\",\n              issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,\n            });\n          }\n          if (!input.cwd?.trim()) {\n            return yield* new ProviderAdapterValidationError({\n              provider: PROVIDER,\n              operation: \"startSession\",\n              issue: \"cwd is required and must be non-empty.\",\n            });\n          }\n\n          const cwd = path.resolve(input.cwd.trim());\n          const cursorModelSelection =\n            input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;\n          const existing = sessions.get(input.threadId);\n          if (existing && !existing.stopped) {\n            yield* stopSessionInternal(existing);\n          }\n\n          const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();\n          const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();\n          const sessionScope = yield* Scope.make(\"sequential\");\n          let sessionScopeTransferred = false;\n          yield* Effect.addFinalizer(() =>\n            sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),\n          );\n          let ctx!: CursorSessionContext;\n\n          const resumeSessionId = parseCursorResume(input.resumeCursor)?.sessionId;\n          const acpNativeLoggers = makeAcpNativeLoggers({\n            nativeEventLogger,\n            provider: PROVIDER,\n            threadId: input.threadId,\n          });\n\n          // Resolve the CursorSettings used to spawn the ACP child. Production\n          // leaves `options.resolveSettings` undefined so we use the value\n          // captured at adapter construction — per-instance isolation is\n          // enforced by the hydration layer rebuilding this adapter whenever\n          // its config changes. Tests set `resolveSettings` to pull the latest\n          // snapshot from `ServerSettingsService` so that mid-suite\n          // `updateSettings({ providers: { cursor: { binaryPath } } })` calls\n          // actually take effect when the next session spawns.\n          const effectiveCursorSettings = options?.resolveSettings\n            ? yield* options.resolveSettings\n            : cursorSettings;\n\n          const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);\n          const acp = yield* makeCursorAcpRuntime({\n            cursorSettings: effectiveCursorSettings,\n            ...(options?.environment ? { environment: options.environment } : {}),\n            childProcessSpawner,\n            cwd,\n            ...(resumeSessionId ? { resumeSessionId } : {}),\n            clientInfo: { name: \"synaptic-code\", version: \"0.0.0\" },\n            ...(mcpSession\n              ? {\n                  mcpServers: [\n                    {\n                      type: \"http\" as const,\n                      name: \"synaptic-code\",\n                      url: mcpSession.endpoint,\n                      headers: [\n                        {\n                          name: \"Authorization\",\n                          value: mcpSession.authorizationHeader,\n                        },\n                      ],\n                    },\n                  ],\n                }\n              : {}),\n            ...acpNativeLoggers,\n          }).pipe(\n            Effect.provideService(Crypto.Crypto, crypto),\n            Effect.provideService(Scope.Scope, sessionScope),\n            Effect.mapError(\n              (cause) =>\n                new ProviderAdapterProcessError({\n                  provider: PROVIDER,\n                  threadId: input.threadId,\n                  detail: cause.message,\n                  cause,\n                }),\n            ),\n          );\n          const started = yield* Effect.gen(function* () {\n            yield* acp.handleExtRequest(\"cursor/ask_question\", CursorAskQuestionRequest, (params) =>\n              mapExtensionFailure(\n                Effect.gen(function* () {\n                  yield* logNative(\n                    input.threadId,\n                    \"cursor/ask_question\",\n                    params,\n                    \"acp.cursor.extension\",\n                  );\n                  const requestId = ApprovalRequestId.make(yield* randomUUIDv4);\n                  const runtimeRequestId = RuntimeRequestId.make(requestId);\n                  const answers = yield* Deferred.make<ProviderUserInputAnswers>();\n                  pendingUserInputs.set(requestId, { answers });\n                  yield* offerRuntimeEvent({\n                    type: \"user-input.requested\",\n                    ...(yield* makeEventStamp()),\n                    provider: PROVIDER,\n                    threadId: input.threadId,\n                    turnId: ctx?.activeTurnId,\n                    requestId: runtimeRequestId,\n                    payload: { questions: extractAskQuestions(params) },\n                    raw: {\n                      source: \"acp.cursor.extension\",\n                      method: \"cursor/ask_question\",\n                      payload: params,\n                    },\n                  });\n                  const resolved = yield* Deferred.await(answers);\n                  pendingUserInputs.delete(requestId);\n                  yield* offerRuntimeEvent({\n                    type: \"user-input.resolved\",\n                    ...(yield* makeEventStamp()),\n                    provider: PROVIDER,\n                    threadId: input.threadId,\n                    turnId: ctx?.activeTurnId,\n                    requestId: runtimeRequestId,\n                    payload: { answers: resolved },\n                  });\n                  return { answers: resolved };\n                }),\n              ),\n            );\n            yield* acp.handleExtRequest(\"cursor/create_plan\", CursorCreatePlanRequest, (params) =>\n              mapExtensionFailure(\n                Effect.gen(function* () {\n                  yield* logNative(\n                    input.threadId,\n                    \"cursor/create_plan\",\n                    params,\n                    \"acp.cursor.extension\",\n                  );\n                  yield* offerRuntimeEvent({\n                    type: \"turn.proposed.completed\",\n                    ...(yield* makeEventStamp()),\n                    provider: PROVIDER,\n                    threadId: input.threadId,\n                    turnId: ctx?.activeTurnId,\n                    payload: { planMarkdown: extractPlanMarkdown(params) },\n                    raw: {\n                      source: \"acp.cursor.extension\",\n                      method: \"cursor/create_plan\",\n                      payload: params,\n                    },\n                  });\n                  return { accepted: true } as const;\n                }),\n              ),\n            );\n            yield* acp.handleExtNotification(\n              \"cursor/update_todos\",\n              CursorUpdateTodosRequest,\n              (params) =>\n                mapExtensionFailure(\n                  Effect.gen(function* () {\n                    yield* logNative(\n                      input.threadId,\n                      \"cursor/update_todos\",\n                      params,\n                      \"acp.cursor.extension\",\n                    );\n                    if (ctx) {\n                      yield* emitPlanUpdate(\n                        ctx,\n                        extractTodosAsPlan(params),\n                        params,\n                        \"acp.cursor.extension\",\n                        \"cursor/update_todos\",\n                      );\n                    }\n                  }),\n                ),\n            );\n            yield* acp.handleRequestPermission((params) =>\n              mapExtensionFailure(\n                Effect.gen(function* () {\n                  yield* logNative(\n                    input.threadId,\n                    \"session/request_permission\",\n                    params,\n                    \"acp.jsonrpc\",\n                  );\n                  if (input.runtimeMode === \"full-access\") {\n                    const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);\n                    if (autoApprovedOptionId !== undefined) {\n                      return {\n                        outcome: {\n                          outcome: \"selected\" as const,\n                          optionId: autoApprovedOptionId,\n                        },\n                      };\n                    }\n                  }\n                  const permissionRequest = parsePermissionRequest(params);\n                  const requestId = ApprovalRequestId.make(yield* randomUUIDv4);\n                  const runtimeRequestId = RuntimeRequestId.make(requestId);\n                  const decision = yield* Deferred.make<ProviderApprovalDecision>();\n                  pendingApprovals.set(requestId, {\n                    decision,\n                    kind: permissionRequest.kind,\n                  });\n                  yield* offerRuntimeEvent(\n                    makeAcpRequestOpenedEvent({\n                      stamp: yield* makeEventStamp(),\n                      provider: PROVIDER,\n                      threadId: input.threadId,\n                      turnId: ctx?.activeTurnId,\n                      requestId: runtimeRequestId,\n                      permissionRequest,\n                      detail:\n                        permissionRequest.detail ??\n                        encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??\n                        \"[unserializable params]\",\n                      args: params,\n                      source: \"acp.jsonrpc\",\n                      method: \"session/request_permission\",\n                      rawPayload: params,\n                    }),\n                  );\n                  const resolved = yield* Deferred.await(decision);\n                  pendingApprovals.delete(requestId);\n                  yield* offerRuntimeEvent(\n                    makeAcpRequestResolvedEvent({\n                      stamp: yield* makeEventStamp(),\n                      provider: PROVIDER,\n                      threadId: input.threadId,\n                      turnId: ctx?.activeTurnId,\n                      requestId: runtimeRequestId,\n                      permissionRequest,\n                      decision: resolved,\n                    }),\n                  );\n                  return {\n                    outcome:\n                      resolved === \"cancel\"\n                        ? ({ outcome: \"cancelled\" } as const)\n                        : {\n                            outcome: \"selected\" as const,\n                            optionId: acpPermissionOutcome(resolved),\n                          },\n                  };\n                }),\n              ),\n            );\n            return yield* acp.start();\n          }).pipe(\n            Effect.mapError((error) =>\n              mapAcpToAdapterError(PROVIDER, input.threadId, \"session/start\", error),\n            ),\n          );\n\n          yield* applyRequestedSessionConfiguration({\n            runtime: acp,\n            runtimeMode: input.runtimeMode,\n            interactionMode: undefined,\n            modelSelection: cursorModelSelection,\n            mapError: ({ cause, method }) =>\n              mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),\n          });\n\n          const now = yield* nowIso;\n          const session: ProviderSession = {\n            provider: PROVIDER,\n            providerInstanceId: boundInstanceId,\n            status: \"ready\",\n            runtimeMode: input.runtimeMode,\n            cwd,\n            model: cursorModelSelection?.model,\n            threadId: input.threadId,\n            resumeCursor: {\n              schemaVersion: CURSOR_RESUME_VERSION,\n              sessionId: started.sessionId,\n            },\n            createdAt: now,\n            updatedAt: now,\n          };\n\n          ctx = {\n            threadId: input.threadId,\n            session,\n            scope: sessionScope,\n            acp,\n            notificationFiber: undefined,\n            pendingApprovals,\n            pendingUserInputs,\n            turns: [],\n            lastPlanFingerprint: undefined,\n            activeTurnId: undefined,\n            promptsInFlight: 0,\n            stopped: false,\n          };\n\n          const nf = yield* Stream.runDrain(\n            Stream.mapEffect(acp.getEvents(), (event) =>\n              Effect.gen(function* () {\n                switch (event._tag) {\n                  case \"EventStreamBarrier\":\n                    yield* Deferred.succeed(event.acknowledge, undefined);\n                    return;\n                  case \"ModeChanged\":\n                    return;\n                  case \"AssistantItemStarted\":\n                    yield* offerRuntimeEvent(\n                      makeAcpAssistantItemEvent({\n                        stamp: yield* makeEventStamp(),\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: ctx.activeTurnId,\n                        itemId: event.itemId,\n                        lifecycle: \"item.started\",\n                      }),\n                    );\n                    return;\n                  case \"AssistantItemCompleted\":\n                    yield* offerRuntimeEvent(\n                      makeAcpAssistantItemEvent({\n                        stamp: yield* makeEventStamp(),\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: ctx.activeTurnId,\n                        itemId: event.itemId,\n                        lifecycle: \"item.completed\",\n                      }),\n                    );\n                    return;\n                  case \"PlanUpdated\":\n                    yield* logNative(\n                      ctx.threadId,\n                      \"session/update\",\n                      event.rawPayload,\n                      \"acp.jsonrpc\",\n                    );\n                    yield* emitPlanUpdate(\n                      ctx,\n                      event.payload,\n                      event.rawPayload,\n                      \"acp.jsonrpc\",\n                      \"session/update\",\n                    );\n                    return;\n                  case \"ToolCallUpdated\":\n                    yield* logNative(\n                      ctx.threadId,\n                      \"session/update\",\n                      event.rawPayload,\n                      \"acp.jsonrpc\",\n                    );\n                    yield* offerRuntimeEvent(\n                      makeAcpToolCallEvent({\n                        stamp: yield* makeEventStamp(),\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: ctx.activeTurnId,\n                        toolCall: event.toolCall,\n                        rawPayload: event.rawPayload,\n                      }),\n                    );\n                    return;\n                  case \"ContentDelta\":\n                    yield* logNative(\n                      ctx.threadId,\n                      \"session/update\",\n                      event.rawPayload,\n                      \"acp.jsonrpc\",\n                    );\n                    yield* offerRuntimeEvent(\n                      makeAcpContentDeltaEvent({\n                        stamp: yield* makeEventStamp(),\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: ctx.activeTurnId,\n                        ...(event.itemId ? { itemId: event.itemId } : {}),\n                        text: event.text,\n                        rawPayload: event.rawPayload,\n                      }),\n                    );\n                    return;\n                }\n              }),\n            ),\n          ).pipe(\n            Effect.catch((cause) =>\n              Effect.logError(\"Failed to process Cursor runtime notification.\", { cause }),\n            ),\n            Effect.forkChild,\n          );\n\n          ctx.notificationFiber = nf;\n          sessions.set(input.threadId, ctx);\n          sessionScopeTransferred = true;\n\n          yield* offerRuntimeEvent({\n            type: \"session.started\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId: input.threadId,\n            payload: { resume: started.initializeResult },\n          });\n          yield* offerRuntimeEvent({\n            type: \"session.state.changed\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId: input.threadId,\n            payload: { state: \"ready\", reason: \"Cursor ACP session ready\" },\n          });\n          yield* offerRuntimeEvent({\n            type: \"thread.started\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId: input.threadId,\n            payload: { providerThreadId: started.sessionId },\n          });\n\n          return session;\n        }).pipe(Effect.scoped),\n      );\n\n    const sendTurn: CursorAdapterShape[\"sendTurn\"] = (input) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(input.threadId);\n        // A sendTurn while a prompt is in flight is a steer: the agent folds\n        // the new prompt into the ongoing work, so the active turn id is\n        // reused instead of opening a new turn.\n        const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;\n        const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);\n        // Count this prompt immediately so a superseded in-flight prompt\n        // resolving from here on does not settle the turn; the matching\n        // decrement is the `ensuring` below.\n        ctx.promptsInFlight += 1;\n\n        return yield* Effect.gen(function* () {\n          const turnModelSelection =\n            input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;\n          const model = turnModelSelection?.model ?? ctx.session.model;\n          const resolvedModel = resolveCursorAcpBaseModelId(model);\n          yield* applyRequestedSessionConfiguration({\n            runtime: ctx.acp,\n            runtimeMode: ctx.session.runtimeMode,\n            interactionMode: input.interactionMode,\n            modelSelection:\n              model === undefined\n                ? undefined\n                : {\n                    model,\n                    options: turnModelSelection?.options,\n                  },\n            mapError: ({ cause, method }) =>\n              mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),\n          });\n          ctx.activeTurnId = turnId;\n          if (steeringTurnId === undefined) {\n            ctx.lastPlanFingerprint = undefined;\n          }\n          ctx.session = {\n            ...ctx.session,\n            activeTurnId: turnId,\n            updatedAt: yield* nowIso,\n          };\n\n          if (steeringTurnId === undefined) {\n            yield* offerRuntimeEvent({\n              type: \"turn.started\",\n              ...(yield* makeEventStamp()),\n              provider: PROVIDER,\n              threadId: input.threadId,\n              turnId,\n              payload: { model: resolvedModel },\n            });\n          }\n\n          const promptParts: Array<EffectAcpSchema.ContentBlock> = [];\n          if (input.input?.trim()) {\n            promptParts.push({ type: \"text\", text: input.input.trim() });\n          }\n          if (input.attachments && input.attachments.length > 0) {\n            for (const attachment of input.attachments) {\n              const attachmentPath = resolveAttachmentPath({\n                attachmentsDir: serverConfig.attachmentsDir,\n                attachment,\n              });\n              if (!attachmentPath) {\n                return yield* new ProviderAdapterRequestError({\n                  provider: PROVIDER,\n                  method: \"session/prompt\",\n                  detail: `Invalid attachment id '${attachment.id}'.`,\n                });\n              }\n              const bytes = yield* fileSystem.readFile(attachmentPath).pipe(\n                Effect.mapError(\n                  (cause) =>\n                    new ProviderAdapterRequestError({\n                      provider: PROVIDER,\n                      method: \"session/prompt\",\n                      detail: cause.message,\n                      cause,\n                    }),\n                ),\n              );\n              promptParts.push({\n                type: \"image\",\n                data: Buffer.from(bytes).toString(\"base64\"),\n                mimeType: attachment.mimeType,\n              });\n            }\n          }\n\n          if (promptParts.length === 0) {\n            return yield* new ProviderAdapterValidationError({\n              provider: PROVIDER,\n              operation: \"sendTurn\",\n              issue: \"Turn requires non-empty text or attachments.\",\n            });\n          }\n\n          const result = yield* ctx.acp\n            .prompt({\n              prompt: promptParts,\n            })\n            .pipe(\n              Effect.mapError((error) =>\n                mapAcpToAdapterError(PROVIDER, input.threadId, \"session/prompt\", error),\n              ),\n            );\n\n          const turnRecord = ctx.turns.find((turn) => turn.id === turnId);\n          if (turnRecord) {\n            turnRecord.items.push({ prompt: promptParts, result });\n          } else {\n            ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });\n          }\n          ctx.session = {\n            ...ctx.session,\n            activeTurnId: turnId,\n            updatedAt: yield* nowIso,\n            model: resolvedModel,\n          };\n\n          // Only the last remaining prompt settles the turn — a steer-\n          // superseded prompt resolving (usually cancelled) while another is\n          // in flight or pending must leave the merged turn running.\n          if (ctx.promptsInFlight === 1) {\n            yield* offerRuntimeEvent({\n              type: \"turn.completed\",\n              ...(yield* makeEventStamp()),\n              provider: PROVIDER,\n              threadId: input.threadId,\n              turnId,\n              payload: {\n                state: result.stopReason === \"cancelled\" ? \"cancelled\" : \"completed\",\n                stopReason: result.stopReason ?? null,\n              },\n            });\n          }\n\n          return {\n            threadId: input.threadId,\n            turnId,\n            resumeCursor: ctx.session.resumeCursor,\n          };\n        }).pipe(\n          Effect.ensuring(\n            Effect.sync(() => {\n              ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);\n            }),\n          ),\n        );\n      });\n\n    const interruptTurn: CursorAdapterShape[\"interruptTurn\"] = (threadId) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(threadId);\n        yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);\n        yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs);\n        yield* Effect.ignore(\n          ctx.acp.cancel.pipe(\n            Effect.mapError((error) =>\n              mapAcpToAdapterError(PROVIDER, threadId, \"session/cancel\", error),\n            ),\n          ),\n        );\n      });\n\n    const respondToRequest: CursorAdapterShape[\"respondToRequest\"] = (\n      threadId,\n      requestId,\n      decision,\n    ) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(threadId);\n        const pending = ctx.pendingApprovals.get(requestId);\n        if (!pending) {\n          return yield* new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"session/request_permission\",\n            detail: `Unknown pending approval request: ${requestId}`,\n          });\n        }\n        yield* Deferred.succeed(pending.decision, decision);\n      });\n\n    const respondToUserInput: CursorAdapterShape[\"respondToUserInput\"] = (\n      threadId,\n      requestId,\n      answers,\n    ) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(threadId);\n        const pending = ctx.pendingUserInputs.get(requestId);\n        if (!pending) {\n          return yield* new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"cursor/ask_question\",\n            detail: `Unknown pending user-input request: ${requestId}`,\n          });\n        }\n        yield* Deferred.succeed(pending.answers, answers);\n      });\n\n    const readThread: CursorAdapterShape[\"readThread\"] = (threadId) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(threadId);\n        return { threadId, turns: ctx.turns };\n      });\n\n    const rollbackThread: CursorAdapterShape[\"rollbackThread\"] = (threadId, numTurns) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(threadId);\n        if (!Number.isInteger(numTurns) || numTurns < 1) {\n          return yield* new ProviderAdapterValidationError({\n            provider: PROVIDER,\n            operation: \"rollbackThread\",\n            issue: \"numTurns must be an integer >= 1.\",\n          });\n        }\n        const nextLength = Math.max(0, ctx.turns.length - numTurns);\n        ctx.turns.splice(nextLength);\n        return { threadId, turns: ctx.turns };\n      });\n\n    const stopSession: CursorAdapterShape[\"stopSession\"] = (threadId) =>\n      withThreadLock(\n        threadId,\n        Effect.gen(function* () {\n          const ctx = yield* requireSession(threadId);\n          yield* stopSessionInternal(ctx);\n        }),\n      );\n\n    const listSessions: CursorAdapterShape[\"listSessions\"] = () =>\n      Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));\n\n    const hasSession: CursorAdapterShape[\"hasSession\"] = (threadId) =>\n      Effect.sync(() => {\n        const c = sessions.get(threadId);\n        return c !== undefined && !c.stopped;\n      });\n\n    const stopAll: CursorAdapterShape[\"stopAll\"] = () =>\n      Effect.forEach(sessions.values(), stopSessionInternal, { discard: true });\n\n    yield* Effect.addFinalizer(() =>\n      Effect.forEach(sessions.values(), stopSessionInternal, { discard: true }).pipe(\n        Effect.catch((cause) =>\n          Effect.logError(\"Failed to emit Cursor session shutdown event.\", { cause }),\n        ),\n        Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),\n        Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),\n      ),\n    );\n\n    const streamEvents = Stream.fromPubSub(runtimeEventPubSub);\n\n    return {\n      provider: PROVIDER,\n      capabilities: { sessionModelSwitch: \"in-session\" },\n      startSession,\n      sendTurn,\n      interruptTurn,\n      readThread,\n      rollbackThread,\n      respondToRequest,\n      respondToUserInput,\n      stopSession,\n      listSessions,\n      hasSession,\n      stopAll,\n      streamEvents,\n    } satisfies CursorAdapterShape;\n  });\n}\n","/**\n * CursorDriver — `ProviderDriver` for the Cursor Agent (`cursor-agent`) runtime.\n *\n * Cursor exposes an ACP-based CLI. Model catalog and capability refreshes\n * happen during the managed provider status check via Cursor's\n * `list_available_models` extension method.\n *\n * Text generation is supported via the ACP runtime — `makeCursorTextGeneration`\n * drives `runtime.prompt` with a structured-output schema and collects the\n * agent's `agent_message_chunk` stream into a single JSON blob.\n *\n * @module provider/Drivers/CursorDriver\n */\nimport { CursorSettings, ProviderDriverKind, type ServerProvider } from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport * as BackgroundPolicy from \"../../background/BackgroundPolicy.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { makeCursorTextGeneration } from \"../../textGeneration/CursorTextGeneration.ts\";\nimport { ProviderDriverError } from \"../Errors.ts\";\nimport { makeCursorAdapter } from \"../Layers/CursorAdapter.ts\";\nimport {\n  buildInitialCursorProviderSnapshot,\n  checkCursorProviderStatus,\n  enrichCursorSnapshot,\n} from \"../Layers/CursorProvider.ts\";\nimport { ProviderEventLoggers } from \"../Layers/ProviderEventLoggers.ts\";\nimport { makeManagedServerProvider } from \"../makeManagedServerProvider.ts\";\nimport {\n  defaultProviderContinuationIdentity,\n  type ProviderDriver,\n  type ProviderInstance,\n} from \"../ProviderDriver.ts\";\nimport type { ServerProviderDraft } from \"../providerSnapshot.ts\";\nimport { mergeProviderInstanceEnvironment } from \"../ProviderInstanceEnvironment.ts\";\nimport {\n  makeProviderMaintenanceCapabilities,\n  type ProviderMaintenanceCapabilitiesResolver,\n  resolveProviderMaintenanceCapabilitiesEffect,\n} from \"../providerMaintenance.ts\";\nimport {\n  haveProviderSnapshotSettingsChanged,\n  makeProviderSnapshotSettingsSource,\n  type ProviderSnapshotSettings,\n} from \"../providerUpdateSettings.ts\";\nconst decodeCursorSettings = Schema.decodeSync(CursorSettings);\n\nconst DRIVER_KIND = ProviderDriverKind.make(\"cursor\");\nconst UPDATE: ProviderMaintenanceCapabilitiesResolver = {\n  resolve: (options) =>\n    makeProviderMaintenanceCapabilities({\n      provider: DRIVER_KIND,\n      packageName: null,\n      updateExecutable: options?.binaryPath?.trim() || \"cursor-agent\",\n      updateArgs: [\"update\"],\n      updateLockKey: \"cursor-agent\",\n    }),\n};\n\nexport type CursorDriverEnv =\n  | BackgroundPolicy.BackgroundPolicy\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | HttpClient.HttpClient\n  | Path.Path\n  | ProviderEventLoggers\n  | ServerConfig\n  | ServerSettingsService;\n\nconst withInstanceIdentity =\n  (input: {\n    readonly instanceId: ProviderInstance[\"instanceId\"];\n    readonly displayName: string | undefined;\n    readonly accentColor: string | undefined;\n    readonly continuationGroupKey: string;\n  }) =>\n  (snapshot: ServerProviderDraft): ServerProvider => ({\n    ...snapshot,\n    instanceId: input.instanceId,\n    driver: DRIVER_KIND,\n    ...(input.displayName ? { displayName: input.displayName } : {}),\n    ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n    continuation: { groupKey: input.continuationGroupKey },\n  });\n\nexport const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {\n  driverKind: DRIVER_KIND,\n  metadata: {\n    displayName: \"Cursor\",\n    supportsMultipleInstances: true,\n  },\n  configSchema: CursorSettings,\n  defaultConfig: (): CursorSettings => decodeCursorSettings({}),\n  create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n    Effect.gen(function* () {\n      const crypto = yield* Crypto.Crypto;\n      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n      const fileSystem = yield* FileSystem.FileSystem;\n      const path = yield* Path.Path;\n      const httpClient = yield* HttpClient.HttpClient;\n      const serverSettings = yield* ServerSettingsService;\n      const eventLoggers = yield* ProviderEventLoggers;\n      const processEnv = mergeProviderInstanceEnvironment(environment);\n      const continuationIdentity = defaultProviderContinuationIdentity({\n        driverKind: DRIVER_KIND,\n        instanceId,\n      });\n      const stampIdentity = withInstanceIdentity({\n        instanceId,\n        displayName,\n        accentColor,\n        continuationGroupKey: continuationIdentity.continuationKey,\n      });\n      const effectiveConfig = { ...config, enabled } satisfies CursorSettings;\n      const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {\n        binaryPath: effectiveConfig.binaryPath,\n        env: processEnv,\n      });\n\n      const adapter = yield* makeCursorAdapter(effectiveConfig, {\n        environment: processEnv,\n        ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n        instanceId,\n      });\n      const textGeneration = yield* makeCursorTextGeneration(effectiveConfig, processEnv);\n\n      const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe(\n        Effect.map(stampIdentity),\n        Effect.provideService(Crypto.Crypto, crypto),\n        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n        Effect.provideService(FileSystem.FileSystem, fileSystem),\n        Effect.provideService(Path.Path, path),\n      );\n\n      const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);\n      const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<CursorSettings>>({\n        maintenanceCapabilities,\n        getSettings: snapshotSettings.getSettings,\n        streamSettings: snapshotSettings.streamSettings,\n        haveSettingsChanged: haveProviderSnapshotSettingsChanged,\n        initialSnapshot: (settings) =>\n          buildInitialCursorProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),\n        checkProvider,\n        // Model catalog and capabilities come exclusively from Cursor's\n        // list_available_models extension method during provider checks.\n        enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>\n          enrichCursorSnapshot({\n            settings: settings.provider,\n            snapshot: currentSnapshot,\n            maintenanceCapabilities,\n            enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n            publishSnapshot,\n            stampIdentity,\n            httpClient,\n          }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),\n      }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProviderDriverError({\n              driver: DRIVER_KIND,\n              instanceId,\n              detail: `Failed to build Cursor snapshot: ${cause.message ?? String(cause)}`,\n              cause,\n            }),\n        ),\n      );\n\n      return {\n        instanceId,\n        driverKind: DRIVER_KIND,\n        continuationIdentity,\n        displayName,\n        accentColor,\n        enabled,\n        snapshot,\n        adapter,\n        textGeneration,\n      } satisfies ProviderInstance;\n    }),\n};\n","import type { ProviderUserInputAnswers, UserInputQuestion } from \"@t3tools/contracts\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\n\nimport type * as AcpSessionRuntime from \"./AcpSessionRuntime.ts\";\n\nconst XAiPromptCompleteNotification = Schema.Struct({\n  sessionId: Schema.String,\n  promptId: Schema.optional(Schema.String),\n  stopReason: Schema.optional(Schema.String),\n  agentResult: Schema.optional(Schema.NullOr(Schema.Unknown)),\n});\n\ntype XAiPromptCompleteNotification = typeof XAiPromptCompleteNotification.Type;\n\ninterface PendingXAiPromptCompletion {\n  readonly sessionId: string;\n  readonly promptId: string;\n  readonly deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>;\n}\n\nconst completedXAiPromptIdLimit = 128;\nconst xAiStopReasonMissingMetaKey = \"xAiStopReasonMissing\";\n\nconst XAiAskUserQuestionOption = Schema.Struct({\n  label: Schema.String,\n  description: Schema.optional(Schema.String),\n  preview: Schema.optional(Schema.String),\n  id: Schema.optional(Schema.String),\n});\n\nconst XAiAskUserQuestion = Schema.Struct({\n  id: Schema.optional(Schema.String),\n  question: Schema.String,\n  options: Schema.Array(XAiAskUserQuestionOption),\n  multiSelect: Schema.optional(Schema.NullOr(Schema.Boolean)),\n});\n\nconst XAiAskUserQuestionParams = Schema.Struct({\n  sessionId: Schema.String,\n  toolCallId: Schema.String,\n  questions: Schema.Array(XAiAskUserQuestion),\n  mode: Schema.Literals([\"default\", \"plan\"]),\n});\n\nconst XAiWrappedAskUserQuestionParams = Schema.Struct({\n  method: Schema.Literals([\"x.ai/ask_user_question\", \"_x.ai/ask_user_question\"]),\n  params: XAiAskUserQuestionParams,\n});\n\nexport const XAiAskUserQuestionRequest = Schema.Union([\n  XAiAskUserQuestionParams,\n  XAiWrappedAskUserQuestionParams,\n]);\n\ntype XAiAskUserQuestionRequestParams = typeof XAiAskUserQuestionParams.Type;\ntype XAiAskUserQuestionRequest = typeof XAiAskUserQuestionRequest.Type;\n\nfunction trimmed(value: string | undefined): string | undefined {\n  const text = value?.trim();\n  return text && text.length > 0 ? text : undefined;\n}\n\nfunction unwrapAskUserQuestionParams(\n  params: XAiAskUserQuestionRequest,\n): XAiAskUserQuestionRequestParams {\n  return \"params\" in params ? params.params : params;\n}\n\nexport function extractXAiAskUserQuestions(\n  params: XAiAskUserQuestionRequest,\n): ReadonlyArray<UserInputQuestion> {\n  return unwrapAskUserQuestionParams(params).questions.map((question) => ({\n    id: question.id ?? question.question,\n    header: \"Question\",\n    question: question.question,\n    multiSelect: question.multiSelect === true,\n    options:\n      question.options.length > 0\n        ? question.options.map((option) => ({\n            label: option.label,\n            description: option.description ?? option.label,\n          }))\n        : [{ label: \"OK\", description: \"Continue\" }],\n  }));\n}\n\ninterface XAiAskUserQuestionAnnotation {\n  readonly preview?: string;\n  readonly notes?: string;\n}\n\ninterface XAiAskUserQuestionAcceptedResponse {\n  readonly outcome: \"accepted\";\n  readonly answers: Record<string, ReadonlyArray<string>>;\n  readonly annotations?: Record<string, XAiAskUserQuestionAnnotation>;\n}\n\ninterface XAiAskUserQuestionCancelledResponse {\n  readonly outcome: \"cancelled\";\n}\n\nexport type XAiAskUserQuestionResponse =\n  | XAiAskUserQuestionAcceptedResponse\n  | XAiAskUserQuestionCancelledResponse;\n\ninterface NormalizedXAiAnswer {\n  readonly questionText: string;\n  readonly selectedLabels: ReadonlyArray<string>;\n  readonly annotation?: XAiAskUserQuestionAnnotation;\n}\n\nfunction answerValues(answer: unknown): ReadonlyArray<string> {\n  if (Array.isArray(answer)) {\n    return answer.flatMap((entry) => {\n      const text = typeof entry === \"string\" ? trimmed(entry) : undefined;\n      return text ? [text] : [];\n    });\n  }\n  const text = typeof answer === \"string\" ? trimmed(answer) : undefined;\n  return text ? [text] : [];\n}\n\nfunction normalizeAnswerForXAi(\n  question: XAiAskUserQuestionRequestParams[\"questions\"][number],\n  answer: unknown,\n): NormalizedXAiAnswer | undefined {\n  const values = answerValues(answer);\n  if (values.length === 0) {\n    return undefined;\n  }\n\n  const optionByLabel = new Map(question.options.map((option) => [option.label, option]));\n  const resolvedValues = values.map((value) => ({\n    value,\n    option: optionByLabel.get(value),\n  }));\n  const selectedLabels = resolvedValues.flatMap(({ option }) => (option ? [option.label] : []));\n  const notes = resolvedValues.flatMap(({ option, value }) => (option ? [] : [value]));\n  const preview =\n    question.multiSelect === true\n      ? undefined\n      : resolvedValues.map(({ option }) => trimmed(option?.preview)).find((value) => value);\n\n  const annotation =\n    preview || notes.length > 0\n      ? {\n          ...(preview ? { preview } : {}),\n          ...(notes.length > 0 ? { notes: notes.join(\"\\n\") } : {}),\n        }\n      : undefined;\n\n  return {\n    questionText: question.question,\n    selectedLabels: selectedLabels.length > 0 ? selectedLabels : [\"Other\"],\n    ...(annotation ? { annotation } : {}),\n  };\n}\n\nfunction findQuestionAnswer(\n  answers: ProviderUserInputAnswers,\n  question: XAiAskUserQuestionRequestParams[\"questions\"][number],\n): unknown {\n  const key = question.id ?? question.question;\n  return answers[key] ?? answers[question.question];\n}\n\nexport function makeXAiAskUserQuestionResponse(\n  params: XAiAskUserQuestionRequest,\n  answers: ProviderUserInputAnswers,\n): XAiAskUserQuestionAcceptedResponse {\n  const questions = unwrapAskUserQuestionParams(params).questions;\n  const normalized = questions.flatMap((question) => {\n    const entry = normalizeAnswerForXAi(question, findQuestionAnswer(answers, question));\n    return entry ? [entry] : [];\n  });\n  const annotations = Object.fromEntries(\n    normalized.flatMap((entry) =>\n      entry.annotation ? [[entry.questionText, entry.annotation] as const] : [],\n    ),\n  );\n\n  return {\n    outcome: \"accepted\",\n    answers: Object.fromEntries(\n      normalized.map((entry) => [entry.questionText, entry.selectedLabels]),\n    ),\n    ...(Object.keys(annotations).length > 0 ? { annotations } : {}),\n  };\n}\n\nexport function makeXAiAskUserQuestionCancelledResponse(): XAiAskUserQuestionCancelledResponse {\n  return { outcome: \"cancelled\" };\n}\n\n/**\n * Adds Grok's private prompt-completion fallback around a standards-only ACP runtime.\n * The underlying runtime remains unaware of xAI methods and metadata.\n */\nexport const makeXAiPromptCompletionRuntime = Effect.fn(\"makeXAiPromptCompletionRuntime\")(\n  function* (runtime: AcpSessionRuntime.AcpSessionRuntime[\"Service\"]) {\n    const activeSessionIdRef = yield* Ref.make<string | undefined>(undefined);\n    const pendingRef = yield* Ref.make<ReadonlyArray<PendingXAiPromptCompletion>>([]);\n    const completedPromptIdsRef = yield* Ref.make<ReadonlyArray<string>>([]);\n    let nextPromptFallbackId = 0;\n    const allocatePromptFallbackId = Effect.sync(() => {\n      nextPromptFallbackId += 1;\n      return `t3-xai-prompt-${nextPromptFallbackId}`;\n    });\n\n    yield* runtime.handleExtNotification(\n      \"_x.ai/session/prompt_complete\",\n      XAiPromptCompleteNotification,\n      (notification) =>\n        resolveXAiPromptCompletionFallback({\n          pendingRef,\n          completedPromptIdsRef,\n          notification,\n        }),\n    );\n\n    return {\n      ...runtime,\n      start: () =>\n        runtime\n          .start()\n          .pipe(Effect.tap((started) => Ref.set(activeSessionIdRef, started.sessionId))),\n      prompt: (payload) =>\n        Effect.gen(function* () {\n          const sessionId = yield* Ref.get(activeSessionIdRef);\n          if (sessionId === undefined) {\n            return yield* runtime.prompt(payload);\n          }\n\n          const promptId = yield* allocatePromptFallbackId;\n          const fallback = yield* registerXAiPromptCompletionFallback(\n            pendingRef,\n            sessionId,\n            promptId,\n          );\n          const requestPayload = {\n            ...payload,\n            _meta: {\n              ...payload._meta,\n              promptId: fallback.promptId,\n              requestId: fallback.promptId,\n            },\n          } satisfies Omit<EffectAcpSchema.PromptRequest, \"sessionId\">;\n\n          return yield* Effect.raceFirst(\n            runtime.prompt(requestPayload),\n            Deferred.await(fallback.deferred),\n          ).pipe(\n            Effect.tap((response) =>\n              rememberCompletedXAiPromptId(completedPromptIdsRef, response, fallback.promptId),\n            ),\n            Effect.ensuring(unregisterXAiPromptCompletionFallback(pendingRef, fallback.deferred)),\n          );\n        }),\n      cancel: Ref.get(activeSessionIdRef).pipe(\n        Effect.flatMap((sessionId) =>\n          sessionId === undefined\n            ? runtime.cancel\n            : abortPendingPromptCompletions(pendingRef, sessionId).pipe(\n                Effect.andThen(runtime.cancel),\n              ),\n        ),\n      ),\n    } satisfies AcpSessionRuntime.AcpSessionRuntime[\"Service\"];\n  },\n);\n\nconst registerXAiPromptCompletionFallback = (\n  pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,\n  sessionId: string,\n  promptId: string,\n) =>\n  Deferred.make<EffectAcpSchema.PromptResponse>().pipe(\n    Effect.tap((deferred) =>\n      Ref.update(pendingRef, (pending) => [...pending, { sessionId, promptId, deferred }]),\n    ),\n    Effect.map((deferred) => ({ deferred, promptId })),\n  );\n\nconst unregisterXAiPromptCompletionFallback = (\n  pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,\n  deferred: Deferred.Deferred<EffectAcpSchema.PromptResponse>,\n) => Ref.update(pendingRef, (pending) => pending.filter((entry) => entry.deferred !== deferred));\n\nconst abortPendingPromptCompletions = (\n  pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>,\n  sessionId: string,\n) =>\n  Ref.modify(pendingRef, (pending) => {\n    const [toAbort, remaining] = pending.reduce<\n      [ReadonlyArray<PendingXAiPromptCompletion>, ReadonlyArray<PendingXAiPromptCompletion>]\n    >(\n      ([aborting, kept], entry) =>\n        entry.sessionId === sessionId ? [[...aborting, entry], kept] : [aborting, [...kept, entry]],\n      [[], []],\n    );\n    if (toAbort.length === 0) {\n      return [Effect.void, pending] as const;\n    }\n    return [\n      Effect.forEach(\n        toAbort,\n        (entry) =>\n          Deferred.succeed(\n            entry.deferred,\n            promptResponseFromXAi({\n              sessionId: entry.sessionId,\n              promptId: entry.promptId,\n              stopReason: \"cancelled\",\n              agentResult: null,\n            }),\n          ),\n        { concurrency: \"unbounded\" },\n      ).pipe(Effect.asVoid),\n      remaining,\n    ] as const;\n  }).pipe(Effect.flatten);\n\nconst resolveXAiPromptCompletionFallback = ({\n  pendingRef,\n  completedPromptIdsRef,\n  notification,\n}: {\n  readonly pendingRef: Ref.Ref<ReadonlyArray<PendingXAiPromptCompletion>>;\n  readonly completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>;\n  readonly notification: XAiPromptCompleteNotification;\n}) =>\n  Ref.get(completedPromptIdsRef).pipe(\n    Effect.flatMap((completedPromptIds) => {\n      if (\n        notification.promptId !== undefined &&\n        completedPromptIds.includes(notification.promptId)\n      ) {\n        return Effect.void;\n      }\n      return Ref.modify(pendingRef, (pending) => {\n        const index =\n          notification.promptId !== undefined\n            ? pending.findIndex(\n                (entry) =>\n                  entry.sessionId === notification.sessionId &&\n                  entry.promptId === notification.promptId,\n              )\n            : pending.findIndex((entry) => entry.sessionId === notification.sessionId);\n        if (index < 0) {\n          return [Effect.void, pending] as const;\n        }\n        const entry = pending[index];\n        if (!entry) {\n          return [Effect.void, pending] as const;\n        }\n        return [\n          Deferred.succeed(entry.deferred, promptResponseFromXAi(notification)).pipe(Effect.asVoid),\n          [...pending.slice(0, index), ...pending.slice(index + 1)],\n        ] as const;\n      }).pipe(Effect.flatten);\n    }),\n  );\n\nconst rememberCompletedXAiPromptId = (\n  completedPromptIdsRef: Ref.Ref<ReadonlyArray<string>>,\n  response: EffectAcpSchema.PromptResponse,\n  fallbackPromptId: string,\n) => {\n  const promptId = promptIdFromResponse(response) ?? fallbackPromptId;\n  return Ref.update(completedPromptIdsRef, (completedPromptIds) => {\n    if (completedPromptIds.includes(promptId)) {\n      return completedPromptIds;\n    }\n    return [...completedPromptIds, promptId].slice(-completedXAiPromptIdLimit);\n  });\n};\n\nfunction promptIdFromResponse(response: EffectAcpSchema.PromptResponse): string | undefined {\n  const meta = response._meta;\n  if (meta === null || typeof meta !== \"object\") {\n    return undefined;\n  }\n  const promptId = meta.promptId ?? meta.requestId;\n  return typeof promptId === \"string\" && promptId.length > 0 ? promptId : undefined;\n}\n\nexport function promptResponseHasMissingXAiStopReason(\n  response: EffectAcpSchema.PromptResponse,\n): boolean {\n  const meta = response._meta;\n  return meta !== null && typeof meta === \"object\" && meta[xAiStopReasonMissingMetaKey] === true;\n}\n\nfunction promptResponseFromXAi(\n  notification: XAiPromptCompleteNotification,\n): EffectAcpSchema.PromptResponse {\n  const stopReason = normalizeXAiStopReason(notification.stopReason);\n  const meta: Record<string, unknown> = {\n    sessionId: notification.sessionId,\n  };\n  if (notification.stopReason === undefined) {\n    meta[xAiStopReasonMissingMetaKey] = true;\n  }\n  if (notification.promptId !== undefined) {\n    meta.promptId = notification.promptId;\n    meta.requestId = notification.promptId;\n  }\n  if (notification.agentResult !== undefined) {\n    meta.agentResult = notification.agentResult;\n  }\n  return {\n    stopReason,\n    _meta: meta,\n  };\n}\n\nfunction normalizeXAiStopReason(value: string | undefined): EffectAcpSchema.StopReason {\n  switch (value) {\n    case \"cancelled\":\n    case \"end_turn\":\n    case \"max_tokens\":\n    case \"max_turn_requests\":\n    case \"refusal\":\n      return value;\n    default:\n      return \"end_turn\";\n  }\n}\n","import { type GrokSettings, ProviderDriverKind } from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Scope from \"effect/Scope\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as EffectAcpErrors from \"effect-acp/errors\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\nimport { normalizeModelSlug } from \"@t3tools/shared/model\";\n\nimport * as AcpSessionRuntime from \"./AcpSessionRuntime.ts\";\nimport { makeXAiPromptCompletionRuntime } from \"./XAiAcpExtension.ts\";\n\nconst GROK_API_KEY_ENV = \"XAI_API_KEY\";\nconst GROK_OAUTH2_REFERRER_ENV = \"GROK_OAUTH2_REFERRER\";\n// Attribution slug on the browser OAuth authorization URL, following the\n// product-slug convention other grok CLI integrations use. The grok CLI reads\n// it only when GROK_OAUTH2_ISSUER and GROK_OAUTH2_CLIENT_ID are also set, so\n// it takes effect only once those are configured too.\nconst SYNAPTIC_OAUTH_REFERRER = \"synaptic-code\";\nconst GROK_AUTH_METHOD_API_KEY = \"xai.api_key\";\nconst GROK_AUTH_METHOD_CACHED_TOKEN = \"cached_token\";\nconst GROK_DRIVER_KIND = ProviderDriverKind.make(\"grok\");\n\ntype GrokAcpRuntimeGrokSettings = Pick<GrokSettings, \"binaryPath\">;\n\ninterface GrokAcpRuntimeInput extends Omit<\n  AcpSessionRuntime.AcpSessionRuntimeOptions,\n  \"authMethodId\" | \"clientCapabilities\" | \"spawn\"\n> {\n  readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner[\"Service\"];\n  readonly grokSettings: GrokAcpRuntimeGrokSettings | null | undefined;\n  readonly environment?: NodeJS.ProcessEnv;\n}\n\nexport function buildGrokAcpSpawnInput(\n  grokSettings: GrokAcpRuntimeGrokSettings | null | undefined,\n  cwd: string,\n  environment?: NodeJS.ProcessEnv,\n): AcpSessionRuntime.AcpSpawnInput {\n  return {\n    command: grokSettings?.binaryPath || \"grok\",\n    args: [\"agent\", \"stdio\"],\n    cwd,\n    env: {\n      ...environment,\n      [GROK_OAUTH2_REFERRER_ENV]: SYNAPTIC_OAUTH_REFERRER,\n    },\n  };\n}\n\nfunction resolveGrokAuthMethodId(environment: NodeJS.ProcessEnv | undefined): string {\n  return environment?.[GROK_API_KEY_ENV]?.trim()\n    ? GROK_AUTH_METHOD_API_KEY\n    : GROK_AUTH_METHOD_CACHED_TOKEN;\n}\n\nexport const makeGrokAcpRuntime = (\n  input: GrokAcpRuntimeInput,\n): Effect.Effect<\n  AcpSessionRuntime.AcpSessionRuntime[\"Service\"],\n  EffectAcpErrors.AcpError,\n  Crypto.Crypto | Scope.Scope\n> =>\n  Effect.gen(function* () {\n    const acpContext = yield* Layer.build(\n      AcpSessionRuntime.layer({\n        ...input,\n        spawn: buildGrokAcpSpawnInput(input.grokSettings, input.cwd, input.environment),\n        authMethodId: resolveGrokAuthMethodId(input.environment),\n      }).pipe(\n        Layer.provide(\n          Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),\n        ),\n      ),\n    );\n    const runtime = yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(\n      Effect.provide(acpContext),\n    );\n    return yield* makeXAiPromptCompletionRuntime(runtime);\n  });\n\nexport function resolveGrokAcpBaseModelId(model: string | null | undefined): string {\n  const trimmed = model?.trim();\n  const base = trimmed && trimmed.length > 0 ? trimmed : \"grok-build\";\n  return normalizeModelSlug(base, GROK_DRIVER_KIND) ?? \"grok-build\";\n}\n\nexport function currentGrokModelIdFromSessionSetup(\n  sessionSetupResult:\n    | EffectAcpSchema.LoadSessionResponse\n    | EffectAcpSchema.NewSessionResponse\n    | EffectAcpSchema.ResumeSessionResponse,\n): string | undefined {\n  return sessionSetupResult.models?.currentModelId?.trim() || undefined;\n}\n\nexport function applyGrokAcpModelSelection<E>(input: {\n  readonly runtime: Pick<AcpSessionRuntime.AcpSessionRuntime[\"Service\"], \"setSessionModel\">;\n  readonly currentModelId: string | undefined;\n  readonly requestedModelId: string | undefined;\n  readonly mapError: (cause: EffectAcpErrors.AcpError) => E;\n}): Effect.Effect<string | undefined, E> {\n  const shouldSwitchModel =\n    input.requestedModelId !== undefined && input.requestedModelId !== input.currentModelId;\n  if (!shouldSwitchModel) {\n    return Effect.succeed(input.currentModelId);\n  }\n  return input.runtime\n    .setSessionModel(input.requestedModelId)\n    .pipe(Effect.mapError(input.mapError), Effect.as(input.requestedModelId));\n}\n","import * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\nimport type * as EffectAcpErrors from \"effect-acp/errors\";\n\nimport { type GrokSettings, type ModelSelection } from \"@t3tools/contracts\";\nimport { sanitizeBranchFragment, sanitizeFeatureBranchName } from \"@t3tools/shared/git\";\nimport { extractJsonObject } from \"@t3tools/shared/schemaJson\";\n\nimport { TextGenerationError } from \"@t3tools/contracts\";\nimport * as TextGeneration from \"./TextGeneration.ts\";\nimport {\n  buildBranchNamePrompt,\n  buildCommitMessagePrompt,\n  buildPrContentPrompt,\n  buildThreadTitlePrompt,\n} from \"./TextGenerationPrompts.ts\";\nimport {\n  sanitizeCommitSubject,\n  sanitizePrTitle,\n  sanitizeThreadTitle,\n} from \"./TextGenerationUtils.ts\";\nimport {\n  applyGrokAcpModelSelection,\n  currentGrokModelIdFromSessionSetup,\n  makeGrokAcpRuntime,\n  resolveGrokAcpBaseModelId,\n} from \"../provider/acp/GrokAcpSupport.ts\";\n\nconst GROK_TIMEOUT_MS = 180_000;\n\nconst isTextGenerationError = Schema.is(TextGenerationError);\n\nexport const makeGrokTextGeneration = Effect.fn(\"makeGrokTextGeneration\")(function* (\n  grokSettings: GrokSettings,\n  environment: NodeJS.ProcessEnv = process.env,\n) {\n  const crypto = yield* Crypto.Crypto;\n  const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n\n  const runGrokJson = <S extends Schema.Top>({\n    operation,\n    cwd,\n    prompt,\n    outputSchemaJson,\n    modelSelection,\n  }: {\n    operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\";\n    cwd: string;\n    prompt: string;\n    outputSchemaJson: S;\n    modelSelection: ModelSelection;\n  }): Effect.Effect<S[\"Type\"], TextGenerationError, S[\"DecodingServices\"]> =>\n    Effect.gen(function* () {\n      const resolvedModel = resolveGrokAcpBaseModelId(modelSelection.model);\n      const outputRef = yield* Ref.make(\"\");\n      const runtime = yield* makeGrokAcpRuntime({\n        grokSettings,\n        environment,\n        childProcessSpawner: commandSpawner,\n        cwd,\n        clientInfo: { name: \"synaptic-code-git-text\", version: \"0.0.0\" },\n      }).pipe(Effect.provideService(Crypto.Crypto, crypto));\n\n      yield* runtime.handleSessionUpdate((notification) => {\n        const update = notification.update;\n        if (update.sessionUpdate !== \"agent_message_chunk\") {\n          return Effect.void;\n        }\n        const content = update.content;\n        if (content.type !== \"text\") {\n          return Effect.void;\n        }\n        return Ref.update(outputRef, (current) => current + content.text);\n      });\n\n      const promptResult = yield* Effect.gen(function* () {\n        const started = yield* runtime.start();\n        yield* applyGrokAcpModelSelection({\n          runtime,\n          currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),\n          requestedModelId: resolvedModel,\n          mapError: (cause) =>\n            new TextGenerationError({\n              operation,\n              detail: \"Failed to set Grok ACP base model for text generation.\",\n              cause,\n            }),\n        });\n\n        return yield* runtime.prompt({\n          prompt: [{ type: \"text\", text: prompt }],\n        });\n      }).pipe(\n        Effect.timeoutOption(GROK_TIMEOUT_MS),\n        Effect.flatMap(\n          Option.match({\n            onNone: () =>\n              Effect.fail(\n                new TextGenerationError({ operation, detail: \"Grok ACP request timed out.\" }),\n              ),\n            onSome: (value) => Effect.succeed(value),\n          }),\n        ),\n        Effect.mapError((cause: EffectAcpErrors.AcpError | TextGenerationError) =>\n          isTextGenerationError(cause)\n            ? cause\n            : new TextGenerationError({\n                operation,\n                detail: \"Grok ACP request failed.\",\n                cause,\n              }),\n        ),\n      );\n\n      const trimmed = (yield* Ref.get(outputRef)).trim();\n      if (!trimmed) {\n        return yield* new TextGenerationError({\n          operation,\n          detail:\n            promptResult.stopReason === \"cancelled\"\n              ? \"Grok ACP request was cancelled.\"\n              : \"Grok Agent returned empty output.\",\n        });\n      }\n\n      const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson));\n      return yield* decodeOutput(extractJsonObject(trimmed)).pipe(\n        Effect.catchTags({\n          SchemaError: (cause) =>\n            Effect.fail(\n              new TextGenerationError({\n                operation,\n                detail: \"Grok Agent returned invalid structured output.\",\n                cause,\n              }),\n            ),\n        }),\n      );\n    }).pipe(\n      Effect.mapError((cause) =>\n        isTextGenerationError(cause)\n          ? cause\n          : new TextGenerationError({\n              operation,\n              detail: \"Grok ACP text generation failed.\",\n              cause,\n            }),\n      ),\n      Effect.scoped,\n    );\n\n  const generateCommitMessage: TextGeneration.TextGeneration[\"Service\"][\"generateCommitMessage\"] =\n    Effect.fn(\"GrokTextGeneration.generateCommitMessage\")(function* (input) {\n      const { prompt, outputSchema } = buildCommitMessagePrompt({\n        branch: input.branch,\n        stagedSummary: input.stagedSummary,\n        stagedPatch: input.stagedPatch,\n        includeBranch: input.includeBranch === true,\n        policy: input.policy,\n      });\n\n      const generated = yield* runGrokJson({\n        operation: \"generateCommitMessage\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        subject: sanitizeCommitSubject(generated.subject),\n        body: generated.body.trim(),\n        ...(\"branch\" in generated && typeof generated.branch === \"string\"\n          ? { branch: sanitizeFeatureBranchName(generated.branch) }\n          : {}),\n      };\n    });\n\n  const generatePrContent: TextGeneration.TextGeneration[\"Service\"][\"generatePrContent\"] =\n    Effect.fn(\"GrokTextGeneration.generatePrContent\")(function* (input) {\n      const { prompt, outputSchema } = buildPrContentPrompt({\n        baseBranch: input.baseBranch,\n        headBranch: input.headBranch,\n        commitSummary: input.commitSummary,\n        diffSummary: input.diffSummary,\n        diffPatch: input.diffPatch,\n        policy: input.policy,\n        changeRequestTemplate: input.changeRequestTemplate,\n      });\n\n      const generated = yield* runGrokJson({\n        operation: \"generatePrContent\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizePrTitle(generated.title),\n        body: generated.body.trim(),\n      };\n    });\n\n  const generateBranchName: TextGeneration.TextGeneration[\"Service\"][\"generateBranchName\"] =\n    Effect.fn(\"GrokTextGeneration.generateBranchName\")(function* (input) {\n      const { prompt, outputSchema } = buildBranchNamePrompt({\n        message: input.message,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runGrokJson({\n        operation: \"generateBranchName\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        branch: sanitizeBranchFragment(generated.branch),\n      };\n    });\n\n  const generateThreadTitle: TextGeneration.TextGeneration[\"Service\"][\"generateThreadTitle\"] =\n    Effect.fn(\"GrokTextGeneration.generateThreadTitle\")(function* (input) {\n      const { prompt, outputSchema } = buildThreadTitlePrompt({\n        message: input.message,\n        previousTitle: input.previousTitle,\n        attachments: input.attachments,\n      });\n\n      const generated = yield* runGrokJson({\n        operation: \"generateThreadTitle\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizeThreadTitle(generated.title),\n      } satisfies TextGeneration.ThreadTitleGenerationResult;\n    });\n\n  return {\n    generateCommitMessage,\n    generatePrContent,\n    generateBranchName,\n    generateThreadTitle,\n  } satisfies TextGeneration.TextGeneration[\"Service\"];\n});\n","import {\n  ApprovalRequestId,\n  type GrokSettings,\n  EventId,\n  type ProviderApprovalDecision,\n  type ProviderRuntimeEvent,\n  type ProviderSession,\n  type ProviderUserInputAnswers,\n  ProviderDriverKind,\n  ProviderInstanceId,\n  RuntimeRequestId,\n  type ThreadId,\n  TurnId,\n} from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Stream from \"effect/Stream\";\nimport * as SynchronizedRef from \"effect/SynchronizedRef\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\nimport * as EffectAcpErrors from \"effect-acp/errors\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\n\nimport { resolveAttachmentPath } from \"../../attachmentStore.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport * as McpProviderSession from \"../../mcp/McpProviderSession.ts\";\nimport {\n  ProviderAdapterProcessError,\n  ProviderAdapterRequestError,\n  ProviderAdapterSessionNotFoundError,\n  ProviderAdapterValidationError,\n} from \"../Errors.ts\";\nimport { mapAcpToAdapterError } from \"../acp/AcpAdapterSupport.ts\";\nimport type * as AcpSessionRuntime from \"../acp/AcpSessionRuntime.ts\";\nimport {\n  makeAcpAssistantItemEvent,\n  makeAcpContentDeltaEvent,\n  makeAcpPlanUpdatedEvent,\n  makeAcpRequestOpenedEvent,\n  makeAcpRequestResolvedEvent,\n  makeAcpToolCallEvent,\n} from \"../acp/AcpCoreRuntimeEvents.ts\";\nimport { parsePermissionRequest } from \"../acp/AcpRuntimeModel.ts\";\nimport { makeAcpNativeLoggerFactory } from \"../acp/AcpNativeLogging.ts\";\nimport {\n  applyGrokAcpModelSelection,\n  currentGrokModelIdFromSessionSetup,\n  makeGrokAcpRuntime,\n  resolveGrokAcpBaseModelId,\n} from \"../acp/GrokAcpSupport.ts\";\nimport {\n  extractXAiAskUserQuestions,\n  makeXAiAskUserQuestionCancelledResponse,\n  makeXAiAskUserQuestionResponse,\n  promptResponseHasMissingXAiStopReason,\n  XAiAskUserQuestionRequest,\n} from \"../acp/XAiAcpExtension.ts\";\nimport { type GrokAdapterShape } from \"../Services/GrokAdapter.ts\";\nimport { type EventNdjsonLogger, makeEventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\n\nconst encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonString(Schema.Unknown));\n\nconst PROVIDER = ProviderDriverKind.make(\"grok\");\nconst GROK_RESUME_VERSION = 1 as const;\n\nfunction encodeJsonStringForDiagnostics(input: unknown): string | undefined {\n  const result = encodeUnknownJsonStringExit(input);\n  return Exit.isSuccess(result) ? result.value : undefined;\n}\n\nexport interface GrokAdapterLiveOptions {\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly nativeEventLogPath?: string;\n  readonly nativeEventLogger?: EventNdjsonLogger;\n  readonly instanceId?: ProviderInstanceId;\n}\n\ninterface PendingApproval {\n  readonly decision: Deferred.Deferred<ProviderApprovalDecision>;\n}\n\ntype PendingUserInputResolution =\n  | { readonly _tag: \"answered\"; readonly answers: ProviderUserInputAnswers }\n  | { readonly _tag: \"cancelled\" };\n\ninterface PendingUserInput {\n  readonly resolution: Deferred.Deferred<PendingUserInputResolution>;\n}\n\ninterface GrokSessionContext {\n  readonly threadId: ThreadId;\n  readonly acpSessionId: string;\n  session: ProviderSession;\n  readonly scope: Scope.Closeable;\n  readonly acp: AcpSessionRuntime.AcpSessionRuntime[\"Service\"];\n  notificationFiber: Fiber.Fiber<void, never> | undefined;\n  readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;\n  readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;\n  turns: Array<{ id: TurnId; items: Array<unknown> }>;\n  lastPlanFingerprint: string | undefined;\n  activeTurnId: TurnId | undefined;\n  /** Turns already interrupted; late prompt RPCs must not resurrect them. */\n  interruptedTurnIds: Set<TurnId>;\n  /** Number of sendTurn prompts currently in flight or being prepared.\n   * >0 means a turn is actively running, so a new sendTurn is a steer that\n   * continues it, and only the last remaining prompt settles the turn. */\n  promptsInFlight: number;\n  currentModelId: string | undefined;\n  stopped: boolean;\n}\n\nfunction settlePendingApprovalsAsCancelled(\n  pendingApprovals: ReadonlyMap<ApprovalRequestId, PendingApproval>,\n): Effect.Effect<void> {\n  return Effect.forEach(\n    Array.from(pendingApprovals.values()),\n    (pending) => Deferred.succeed(pending.decision, \"cancel\").pipe(Effect.ignore),\n    { discard: true },\n  );\n}\n\nfunction settlePendingUserInputsAsCancelled(\n  pendingUserInputs: ReadonlyMap<ApprovalRequestId, PendingUserInput>,\n): Effect.Effect<void> {\n  return Effect.forEach(\n    Array.from(pendingUserInputs.values()),\n    (pending) => Deferred.succeed(pending.resolution, { _tag: \"cancelled\" }).pipe(Effect.ignore),\n    { discard: true },\n  );\n}\n\nfunction appendPromptResultToTurn(\n  ctx: GrokSessionContext,\n  turnId: TurnId,\n  promptParts: ReadonlyArray<EffectAcpSchema.ContentBlock>,\n  result: EffectAcpSchema.PromptResponse,\n): void {\n  const existingTurnRecord = ctx.turns.find((turn) => turn.id === turnId);\n  ctx.turns = existingTurnRecord\n    ? ctx.turns.map((turn) =>\n        turn.id === turnId\n          ? { ...turn, items: [...turn.items, { prompt: promptParts, result }] }\n          : turn,\n      )\n    : [...ctx.turns, { id: turnId, items: [{ prompt: promptParts, result }] }];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nconst resolveNotificationTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;\n\nconst resolveCallbackTurnId = (ctx: GrokSessionContext): TurnId | undefined => ctx.activeTurnId;\n\nconst resolveSessionCallbackTurnId = (\n  sessions: ReadonlyMap<ThreadId, GrokSessionContext>,\n  threadId: ThreadId,\n): TurnId | undefined => {\n  const ctx = sessions.get(threadId);\n  return ctx ? resolveCallbackTurnId(ctx) : undefined;\n};\n\nfunction parseGrokResume(raw: unknown): { sessionId: string } | undefined {\n  if (!isRecord(raw)) return undefined;\n  if (raw.schemaVersion !== GROK_RESUME_VERSION) return undefined;\n  if (typeof raw.sessionId !== \"string\" || !raw.sessionId.trim()) return undefined;\n  return { sessionId: raw.sessionId.trim() };\n}\n\nfunction selectPermissionOptionId(\n  request: EffectAcpSchema.RequestPermissionRequest,\n  decision: Exclude<ProviderApprovalDecision, \"cancel\">,\n): string | undefined {\n  const kind =\n    decision === \"acceptForSession\"\n      ? \"allow_always\"\n      : decision === \"accept\"\n        ? \"allow_once\"\n        : \"reject_once\";\n  const option = request.options.find((entry) => entry.kind === kind);\n  return option?.optionId.trim() || undefined;\n}\n\nfunction selectAutoApprovedPermissionOption(\n  request: EffectAcpSchema.RequestPermissionRequest,\n): string | undefined {\n  return (\n    selectPermissionOptionId(request, \"acceptForSession\") ??\n    selectPermissionOptionId(request, \"accept\")\n  );\n}\n\nfunction completedStopReasonFromPromptResponse(\n  response: EffectAcpSchema.PromptResponse | undefined,\n): EffectAcpSchema.StopReason | null {\n  if (response === undefined || promptResponseHasMissingXAiStopReason(response)) {\n    return null;\n  }\n  return response.stopReason;\n}\n\nexport function grokPromptSettlementBelongsToContext(input: {\n  readonly liveAcpSessionId: string;\n  readonly expectedAcpSessionId: string;\n  readonly liveActiveTurnId: TurnId | undefined;\n  readonly liveSessionActiveTurnId: TurnId | undefined;\n  readonly turnId: TurnId;\n}): boolean {\n  return (\n    input.liveAcpSessionId === input.expectedAcpSessionId &&\n    (input.liveActiveTurnId === input.turnId || input.liveSessionActiveTurnId === input.turnId)\n  );\n}\n\nexport function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapterLiveOptions) {\n  return Effect.gen(function* () {\n    const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make(\"grok\");\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const serverConfig = yield* Effect.service(ServerConfig);\n    const crypto = yield* Crypto.Crypto;\n    const nativeEventLogger =\n      options?.nativeEventLogger ??\n      (options?.nativeEventLogPath !== undefined\n        ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, { stream: \"native\" })\n        : undefined);\n    const managedNativeEventLogger =\n      options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n    const makeAcpNativeLoggers = yield* makeAcpNativeLoggerFactory();\n\n    const sessions = new Map<ThreadId, GrokSessionContext>();\n    const threadLocksRef = yield* SynchronizedRef.make(new Map<string, Semaphore.Semaphore>());\n    const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();\n\n    const nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n    const randomUUIDv4 = crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"crypto/randomUUIDv4\",\n            detail: \"Failed to generate Grok runtime identifier.\",\n            cause,\n          }),\n      ),\n    );\n    const nextEventId = Effect.map(randomUUIDv4, (id) => EventId.make(id));\n    const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });\n    const mapAcpCallbackFailure = <A, E, R>(effect: Effect.Effect<A, E, R>) =>\n      effect.pipe(\n        Effect.mapError(\n          (cause) =>\n            new EffectAcpErrors.AcpTransportError({\n              detail: \"Failed to process Grok ACP callback.\",\n              cause,\n            }),\n        ),\n      );\n\n    const offerRuntimeEvent = (event: ProviderRuntimeEvent) =>\n      PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid);\n\n    const getThreadSemaphore = (threadId: string) =>\n      SynchronizedRef.modifyEffect(threadLocksRef, (current) => {\n        const existing: Option.Option<Semaphore.Semaphore> = Option.fromNullishOr(\n          current.get(threadId),\n        );\n        return Option.match(existing, {\n          onNone: () =>\n            Semaphore.make(1).pipe(\n              Effect.map((semaphore) => {\n                const next = new Map(current);\n                next.set(threadId, semaphore);\n                return [semaphore, next] as const;\n              }),\n            ),\n          onSome: (semaphore) => Effect.succeed([semaphore, current] as const),\n        });\n      });\n\n    const withThreadLock = <A, E, R>(threadId: string, effect: Effect.Effect<A, E, R>) =>\n      Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect));\n\n    const settlePromptInFlight = (\n      threadId: ThreadId,\n      turnId: TurnId,\n      expectedAcpSessionId: string,\n      options?: {\n        readonly errorMessage?: string;\n        readonly completedStopReason?: EffectAcpSchema.StopReason | null;\n        readonly emitTurnCompletion?: boolean;\n        /** Interrupt/cancel: drop every outstanding prompt slot and settle once. */\n        readonly settleAllPrompts?: boolean;\n      },\n    ) =>\n      Effect.gen(function* () {\n        const liveCtx = sessions.get(threadId);\n        if (!liveCtx) {\n          return;\n        }\n        const settlementBelongsToLiveContext = grokPromptSettlementBelongsToContext({\n          liveAcpSessionId: liveCtx.acpSessionId,\n          expectedAcpSessionId,\n          liveActiveTurnId: liveCtx.activeTurnId,\n          liveSessionActiveTurnId: liveCtx.session.activeTurnId,\n          turnId,\n        });\n        if (!settlementBelongsToLiveContext) {\n          // interruptTurn already consumed every prompt slot for this turn. A\n          // late prompt result must neither emit a second terminal event nor\n          // consume a slot belonging to a newer turn on the same ACP session.\n          if (\n            liveCtx.acpSessionId !== expectedAcpSessionId ||\n            liveCtx.interruptedTurnIds.has(turnId)\n          ) {\n            return;\n          }\n          if (options?.emitTurnCompletion !== false) {\n            if (options?.errorMessage !== undefined) {\n              yield* offerRuntimeEvent({\n                type: \"turn.completed\",\n                ...(yield* makeEventStamp()),\n                provider: PROVIDER,\n                threadId,\n                turnId,\n                payload: {\n                  state: \"failed\",\n                  errorMessage: options.errorMessage,\n                },\n              });\n            } else if (options?.completedStopReason !== undefined) {\n              yield* offerRuntimeEvent({\n                type: \"turn.completed\",\n                ...(yield* makeEventStamp()),\n                provider: PROVIDER,\n                threadId,\n                turnId,\n                payload: {\n                  state: options.completedStopReason === \"cancelled\" ? \"cancelled\" : \"completed\",\n                  stopReason: options.completedStopReason ?? null,\n                },\n              });\n            }\n          }\n          return;\n        }\n        let settleTurnId = turnId;\n        if (options?.settleAllPrompts) {\n          liveCtx.promptsInFlight = 0;\n          if (liveCtx.activeTurnId !== turnId && liveCtx.session.activeTurnId !== turnId) {\n            const fallbackTurnId = liveCtx.activeTurnId ?? liveCtx.session.activeTurnId;\n            if (!fallbackTurnId) {\n              if (liveCtx.session.status === \"running\" || liveCtx.session.status === \"connecting\") {\n                const updatedAt = yield* nowIso;\n                const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;\n                liveCtx.activeTurnId = undefined;\n                liveCtx.session = {\n                  ...readySession,\n                  status: \"ready\",\n                  updatedAt,\n                };\n              }\n              return;\n            }\n            settleTurnId = fallbackTurnId;\n          }\n        } else {\n          const remainingPrompts = Math.max(0, liveCtx.promptsInFlight - 1);\n          if (\n            remainingPrompts > 0 ||\n            liveCtx.activeTurnId !== settleTurnId ||\n            liveCtx.session.activeTurnId !== settleTurnId\n          ) {\n            liveCtx.promptsInFlight = remainingPrompts;\n            return;\n          }\n          liveCtx.promptsInFlight = remainingPrompts;\n        }\n        const updatedAt = yield* nowIso;\n        const canEmitTurnCompletion =\n          liveCtx.session.status === \"running\" || liveCtx.session.status === \"connecting\";\n        const shouldEmitFailedTurn = options?.errorMessage !== undefined && canEmitTurnCompletion;\n        const shouldEmitCompletedTurn =\n          options?.completedStopReason !== undefined && canEmitTurnCompletion;\n        const { activeTurnId: _activeTurnId, ...readySession } = liveCtx.session;\n        liveCtx.activeTurnId = undefined;\n        liveCtx.session = {\n          ...readySession,\n          status: \"ready\",\n          updatedAt,\n        };\n        if (options?.emitTurnCompletion === false) {\n          return;\n        }\n        if (shouldEmitFailedTurn) {\n          yield* offerRuntimeEvent({\n            type: \"turn.completed\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId,\n            turnId: settleTurnId,\n            payload: {\n              state: \"failed\",\n              errorMessage: options.errorMessage,\n            },\n          });\n        } else if (shouldEmitCompletedTurn) {\n          yield* offerRuntimeEvent({\n            type: \"turn.completed\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId,\n            turnId: settleTurnId,\n            payload: {\n              state: options.completedStopReason === \"cancelled\" ? \"cancelled\" : \"completed\",\n              stopReason: options.completedStopReason ?? null,\n            },\n          });\n        }\n      });\n\n    const logNative = (threadId: ThreadId, method: string, payload: unknown) =>\n      Effect.gen(function* () {\n        if (!nativeEventLogger) return;\n        const observedAt = yield* nowIso;\n        yield* nativeEventLogger.write(\n          {\n            observedAt,\n            event: {\n              id: yield* randomUUIDv4,\n              kind: \"notification\",\n              provider: PROVIDER,\n              createdAt: observedAt,\n              method,\n              threadId,\n              payload,\n            },\n          },\n          threadId,\n        );\n      }).pipe(\n        Effect.catchCause((cause) =>\n          Effect.logWarning(\"Failed to write native Grok notification log.\", {\n            cause,\n            threadId,\n            method,\n          }),\n        ),\n      );\n\n    const emitPlanUpdate = (\n      ctx: GrokSessionContext,\n      turnId: TurnId | undefined,\n      stamp: { readonly eventId: EventId; readonly createdAt: string },\n      payload: {\n        readonly explanation?: string | null;\n        readonly plan: ReadonlyArray<{\n          readonly step: string;\n          readonly status: \"pending\" | \"inProgress\" | \"completed\";\n        }>;\n      },\n      rawPayload: unknown,\n      method: string,\n    ) =>\n      Effect.gen(function* () {\n        const fingerprint = `${turnId ?? \"no-turn\"}:${encodeJsonStringForDiagnostics(payload) ?? \"[unserializable payload]\"}`;\n        if (ctx.lastPlanFingerprint === fingerprint) {\n          return;\n        }\n        ctx.lastPlanFingerprint = fingerprint;\n        yield* offerRuntimeEvent(\n          makeAcpPlanUpdatedEvent({\n            stamp,\n            provider: PROVIDER,\n            threadId: ctx.threadId,\n            turnId,\n            payload,\n            source: \"acp.jsonrpc\",\n            method,\n            rawPayload,\n          }),\n        );\n      });\n\n    const requireSession = (\n      threadId: ThreadId,\n    ): Effect.Effect<GrokSessionContext, ProviderAdapterSessionNotFoundError> => {\n      const ctx = sessions.get(threadId);\n      if (!ctx || ctx.stopped) {\n        return Effect.fail(\n          new ProviderAdapterSessionNotFoundError({ provider: PROVIDER, threadId }),\n        );\n      }\n      return Effect.succeed(ctx);\n    };\n\n    const stopSessionInternal = (ctx: GrokSessionContext) =>\n      Effect.gen(function* () {\n        if (ctx.stopped) return;\n        ctx.stopped = true;\n        yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);\n        yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);\n        if (ctx.notificationFiber) {\n          yield* Fiber.interrupt(ctx.notificationFiber);\n        }\n        yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));\n        sessions.delete(ctx.threadId);\n        yield* offerRuntimeEvent({\n          type: \"session.exited\",\n          ...(yield* makeEventStamp()),\n          provider: PROVIDER,\n          threadId: ctx.threadId,\n          payload: { exitKind: \"graceful\" },\n        });\n      });\n\n    const startSession: GrokAdapterShape[\"startSession\"] = (input) =>\n      withThreadLock(\n        input.threadId,\n        Effect.gen(function* () {\n          if (input.provider !== undefined && input.provider !== PROVIDER) {\n            return yield* new ProviderAdapterValidationError({\n              provider: PROVIDER,\n              operation: \"startSession\",\n              issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,\n            });\n          }\n          if (!input.cwd?.trim()) {\n            return yield* new ProviderAdapterValidationError({\n              provider: PROVIDER,\n              operation: \"startSession\",\n              issue: \"cwd is required and must be non-empty.\",\n            });\n          }\n\n          const cwd = path.resolve(input.cwd.trim());\n          const grokModelSelection =\n            input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;\n          const existing = sessions.get(input.threadId);\n          if (existing && !existing.stopped) {\n            yield* stopSessionInternal(existing);\n          }\n\n          const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();\n          const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();\n          const sessionScope = yield* Scope.make(\"sequential\");\n          let sessionScopeTransferred = false;\n          yield* Effect.addFinalizer(() =>\n            sessionScopeTransferred ? Effect.void : Scope.close(sessionScope, Exit.void),\n          );\n\n          const resumeSessionId = parseGrokResume(input.resumeCursor)?.sessionId;\n          const acpNativeLoggers = makeAcpNativeLoggers({\n            nativeEventLogger,\n            provider: PROVIDER,\n            threadId: input.threadId,\n          });\n\n          const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);\n          const acp = yield* makeGrokAcpRuntime({\n            grokSettings,\n            ...(options?.environment ? { environment: options.environment } : {}),\n            childProcessSpawner,\n            cwd,\n            ...(resumeSessionId ? { resumeSessionId } : {}),\n            clientInfo: { name: \"synaptic-code\", version: \"0.0.0\" },\n            ...(mcpSession\n              ? {\n                  mcpServers: [\n                    {\n                      type: \"http\" as const,\n                      name: \"synaptic-code\",\n                      url: mcpSession.endpoint,\n                      headers: [\n                        {\n                          name: \"Authorization\",\n                          value: mcpSession.authorizationHeader,\n                        },\n                      ],\n                    },\n                  ],\n                }\n              : {}),\n            ...acpNativeLoggers,\n          }).pipe(\n            Effect.provideService(Crypto.Crypto, crypto),\n            Effect.provideService(Scope.Scope, sessionScope),\n            Effect.mapError(\n              (cause) =>\n                new ProviderAdapterProcessError({\n                  provider: PROVIDER,\n                  threadId: input.threadId,\n                  detail: cause.message,\n                  cause,\n                }),\n            ),\n          );\n          const started = yield* Effect.gen(function* () {\n            yield* Effect.forEach(\n              [\"x.ai/ask_user_question\", \"_x.ai/ask_user_question\"] as const,\n              (method) =>\n                acp.handleExtRequest(method, XAiAskUserQuestionRequest, (params) =>\n                  mapAcpCallbackFailure(\n                    Effect.gen(function* () {\n                      yield* logNative(input.threadId, method, params);\n                      const requestId = ApprovalRequestId.make(yield* randomUUIDv4);\n                      const runtimeRequestId = RuntimeRequestId.make(requestId);\n                      const resolution = yield* Deferred.make<PendingUserInputResolution>();\n                      const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);\n                      pendingUserInputs.set(requestId, { resolution });\n                      yield* offerRuntimeEvent({\n                        type: \"user-input.requested\",\n                        ...(yield* makeEventStamp()),\n                        provider: PROVIDER,\n                        threadId: input.threadId,\n                        turnId,\n                        requestId: runtimeRequestId,\n                        payload: { questions: extractXAiAskUserQuestions(params) },\n                        raw: {\n                          source: \"acp.grok.extension\",\n                          method,\n                          payload: params,\n                        },\n                      });\n                      const resolved = yield* Deferred.await(resolution);\n                      pendingUserInputs.delete(requestId);\n                      const resolvedAnswers = resolved._tag === \"answered\" ? resolved.answers : {};\n                      yield* offerRuntimeEvent({\n                        type: \"user-input.resolved\",\n                        ...(yield* makeEventStamp()),\n                        provider: PROVIDER,\n                        threadId: input.threadId,\n                        turnId,\n                        requestId: runtimeRequestId,\n                        payload: { answers: resolvedAnswers },\n                        raw: {\n                          source: \"acp.grok.extension\",\n                          method,\n                          payload: params,\n                        },\n                      });\n                      switch (resolved._tag) {\n                        case \"answered\":\n                          return makeXAiAskUserQuestionResponse(params, resolved.answers);\n                        case \"cancelled\":\n                          return makeXAiAskUserQuestionCancelledResponse();\n                      }\n                    }),\n                  ),\n                ),\n              { discard: true },\n            );\n            yield* acp.handleRequestPermission((params) =>\n              mapAcpCallbackFailure(\n                Effect.gen(function* () {\n                  yield* logNative(input.threadId, \"session/request_permission\", params);\n                  if (input.runtimeMode === \"full-access\") {\n                    const autoApprovedOptionId = selectAutoApprovedPermissionOption(params);\n                    if (autoApprovedOptionId !== undefined) {\n                      return {\n                        outcome: {\n                          outcome: \"selected\" as const,\n                          optionId: autoApprovedOptionId,\n                        },\n                      };\n                    }\n                  }\n                  const permissionRequest = parsePermissionRequest(params);\n                  const requestId = ApprovalRequestId.make(yield* randomUUIDv4);\n                  const runtimeRequestId = RuntimeRequestId.make(requestId);\n                  const decision = yield* Deferred.make<ProviderApprovalDecision>();\n                  const turnId = resolveSessionCallbackTurnId(sessions, input.threadId);\n                  pendingApprovals.set(requestId, { decision });\n                  yield* offerRuntimeEvent(\n                    makeAcpRequestOpenedEvent({\n                      stamp: yield* makeEventStamp(),\n                      provider: PROVIDER,\n                      threadId: input.threadId,\n                      turnId,\n                      requestId: runtimeRequestId,\n                      permissionRequest,\n                      detail:\n                        permissionRequest.detail ??\n                        encodeJsonStringForDiagnostics(params)?.slice(0, 2000) ??\n                        \"[unserializable params]\",\n                      args: params,\n                      source: \"acp.jsonrpc\",\n                      method: \"session/request_permission\",\n                      rawPayload: params,\n                    }),\n                  );\n                  const resolved = yield* Deferred.await(decision);\n                  pendingApprovals.delete(requestId);\n                  yield* offerRuntimeEvent(\n                    makeAcpRequestResolvedEvent({\n                      stamp: yield* makeEventStamp(),\n                      provider: PROVIDER,\n                      threadId: input.threadId,\n                      turnId,\n                      requestId: runtimeRequestId,\n                      permissionRequest,\n                      decision: resolved,\n                    }),\n                  );\n                  const selectedOptionId =\n                    resolved === \"cancel\" ? undefined : selectPermissionOptionId(params, resolved);\n                  return {\n                    outcome: selectedOptionId\n                      ? {\n                          outcome: \"selected\" as const,\n                          optionId: selectedOptionId,\n                        }\n                      : ({ outcome: \"cancelled\" } as const),\n                  };\n                }),\n              ),\n            );\n            return yield* acp.start();\n          }).pipe(\n            Effect.mapError((error) =>\n              mapAcpToAdapterError(PROVIDER, input.threadId, \"session/start\", error),\n            ),\n          );\n\n          const requestedStartModelId = grokModelSelection?.model\n            ? resolveGrokAcpBaseModelId(grokModelSelection.model)\n            : undefined;\n          const boundModelId = yield* applyGrokAcpModelSelection({\n            runtime: acp,\n            currentModelId: currentGrokModelIdFromSessionSetup(started.sessionSetupResult),\n            requestedModelId: requestedStartModelId,\n            mapError: (cause) =>\n              mapAcpToAdapterError(PROVIDER, input.threadId, \"session/set_model\", cause),\n          });\n\n          const now = yield* nowIso;\n          const session: ProviderSession = {\n            provider: PROVIDER,\n            providerInstanceId: boundInstanceId,\n            status: \"ready\",\n            runtimeMode: input.runtimeMode,\n            cwd,\n            ...(boundModelId ? { model: resolveGrokAcpBaseModelId(boundModelId) } : {}),\n            threadId: input.threadId,\n            resumeCursor: {\n              schemaVersion: GROK_RESUME_VERSION,\n              sessionId: started.sessionId,\n            },\n            createdAt: now,\n            updatedAt: now,\n          };\n\n          const ctx: GrokSessionContext = {\n            threadId: input.threadId,\n            acpSessionId: started.sessionId,\n            session,\n            scope: sessionScope,\n            acp,\n            notificationFiber: undefined,\n            pendingApprovals,\n            pendingUserInputs,\n            turns: [],\n            lastPlanFingerprint: undefined,\n            activeTurnId: undefined,\n            interruptedTurnIds: new Set(),\n            promptsInFlight: 0,\n            currentModelId: boundModelId,\n            stopped: false,\n          };\n\n          const nf = yield* Stream.runDrain(\n            Stream.mapEffect(acp.getEvents(), (event) =>\n              Effect.gen(function* () {\n                if (event._tag === \"EventStreamBarrier\") {\n                  yield* Deferred.succeed(event.acknowledge, undefined);\n                  return;\n                }\n                if (\n                  event._tag === \"PlanUpdated\" ||\n                  event._tag === \"ToolCallUpdated\" ||\n                  event._tag === \"ContentDelta\"\n                ) {\n                  yield* logNative(ctx.threadId, \"session/update\", event.rawPayload);\n                }\n\n                if (event._tag === \"ModeChanged\") {\n                  return;\n                }\n\n                const notificationTurnId = resolveNotificationTurnId(ctx);\n                if (\n                  notificationTurnId === undefined ||\n                  ctx.interruptedTurnIds.has(notificationTurnId)\n                ) {\n                  return;\n                }\n                const stamp = yield* makeEventStamp();\n\n                switch (event._tag) {\n                  case \"AssistantItemStarted\":\n                    yield* offerRuntimeEvent(\n                      makeAcpAssistantItemEvent({\n                        stamp,\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: notificationTurnId,\n                        itemId: event.itemId,\n                        lifecycle: \"item.started\",\n                      }),\n                    );\n                    return;\n                  case \"AssistantItemCompleted\":\n                    yield* offerRuntimeEvent(\n                      makeAcpAssistantItemEvent({\n                        stamp,\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: notificationTurnId,\n                        itemId: event.itemId,\n                        lifecycle: \"item.completed\",\n                      }),\n                    );\n                    return;\n                  case \"PlanUpdated\":\n                    yield* emitPlanUpdate(\n                      ctx,\n                      notificationTurnId,\n                      stamp,\n                      event.payload,\n                      event.rawPayload,\n                      \"session/update\",\n                    );\n                    return;\n                  case \"ToolCallUpdated\":\n                    yield* offerRuntimeEvent(\n                      makeAcpToolCallEvent({\n                        stamp,\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: notificationTurnId,\n                        toolCall: event.toolCall,\n                        rawPayload: event.rawPayload,\n                      }),\n                    );\n                    return;\n                  case \"ContentDelta\":\n                    yield* offerRuntimeEvent(\n                      makeAcpContentDeltaEvent({\n                        stamp,\n                        provider: PROVIDER,\n                        threadId: ctx.threadId,\n                        turnId: notificationTurnId,\n                        ...(event.itemId ? { itemId: event.itemId } : {}),\n                        text: event.text,\n                        rawPayload: event.rawPayload,\n                      }),\n                    );\n                    return;\n                }\n              }),\n            ),\n          ).pipe(\n            Effect.catch((cause) =>\n              Effect.logError(\"Failed to process Grok runtime notification.\", { cause }),\n            ),\n            Effect.forkChild,\n          );\n\n          ctx.notificationFiber = nf;\n          sessions.set(input.threadId, ctx);\n          sessionScopeTransferred = true;\n\n          yield* offerRuntimeEvent({\n            type: \"session.started\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId: input.threadId,\n            payload: { resume: started.initializeResult },\n          });\n          yield* offerRuntimeEvent({\n            type: \"session.state.changed\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId: input.threadId,\n            payload: { state: \"ready\", reason: \"Grok ACP session ready\" },\n          });\n          yield* offerRuntimeEvent({\n            type: \"thread.started\",\n            ...(yield* makeEventStamp()),\n            provider: PROVIDER,\n            threadId: input.threadId,\n            payload: { providerThreadId: started.sessionId },\n          });\n\n          return session;\n        }).pipe(Effect.scoped),\n      );\n\n    const sendTurn: GrokAdapterShape[\"sendTurn\"] = (input) =>\n      Effect.gen(function* () {\n        const prepared = yield* withThreadLock(\n          input.threadId,\n          Effect.gen(function* () {\n            const ctx = yield* requireSession(input.threadId);\n            // A sendTurn while a prompt is in flight is a steer: the agent\n            // folds the new prompt into the ongoing work, so the active turn\n            // id is reused instead of opening a new turn.\n            const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;\n            const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);\n            // Count this prompt immediately so a superseded in-flight prompt\n            // resolving from here on does not settle the turn; decremented on\n            // preparation failure here, and after the prompt below otherwise.\n            ctx.promptsInFlight += 1;\n            // Bind the turn id before cooperative yields so interruptTurn can\n            // settle this prompt even if stop arrives during preparation.\n            ctx.activeTurnId = turnId;\n            ctx.session = {\n              ...ctx.session,\n              status: steeringTurnId === undefined ? \"connecting\" : \"running\",\n              activeTurnId: turnId,\n              updatedAt: yield* nowIso,\n            };\n\n            return yield* Effect.gen(function* () {\n              const turnModelSelection =\n                input.modelSelection?.instanceId === boundInstanceId\n                  ? input.modelSelection\n                  : undefined;\n              const requestedTurnModelId = turnModelSelection?.model\n                ? resolveGrokAcpBaseModelId(turnModelSelection.model)\n                : undefined;\n              const currentModelId = yield* applyGrokAcpModelSelection({\n                runtime: ctx.acp,\n                currentModelId: ctx.currentModelId,\n                requestedModelId: requestedTurnModelId,\n                mapError: (cause) =>\n                  mapAcpToAdapterError(PROVIDER, input.threadId, \"session/set_model\", cause),\n              });\n\n              const text = input.input?.trim();\n              const imagePromptParts = yield* Effect.forEach(\n                input.attachments ?? [],\n                (attachment) =>\n                  Effect.gen(function* () {\n                    const attachmentPath = resolveAttachmentPath({\n                      attachmentsDir: serverConfig.attachmentsDir,\n                      attachment,\n                    });\n                    if (!attachmentPath) {\n                      return yield* new ProviderAdapterRequestError({\n                        provider: PROVIDER,\n                        method: \"session/prompt\",\n                        detail: `Invalid attachment id '${attachment.id}'.`,\n                      });\n                    }\n                    const bytes = yield* fileSystem.readFile(attachmentPath).pipe(\n                      Effect.mapError(\n                        (cause) =>\n                          new ProviderAdapterRequestError({\n                            provider: PROVIDER,\n                            method: \"session/prompt\",\n                            detail: cause.message,\n                            cause,\n                          }),\n                      ),\n                    );\n                    return {\n                      type: \"image\",\n                      data: Buffer.from(bytes).toString(\"base64\"),\n                      mimeType: attachment.mimeType,\n                    } satisfies EffectAcpSchema.ContentBlock;\n                  }),\n              );\n              const promptParts: Array<EffectAcpSchema.ContentBlock> = [\n                ...(text ? [{ type: \"text\" as const, text }] : []),\n                ...imagePromptParts,\n              ];\n\n              if (promptParts.length === 0) {\n                return yield* new ProviderAdapterValidationError({\n                  provider: PROVIDER,\n                  operation: \"sendTurn\",\n                  issue: \"Turn requires non-empty text or attachments.\",\n                });\n              }\n\n              ctx.currentModelId = currentModelId;\n              const displayModel = currentModelId\n                ? resolveGrokAcpBaseModelId(currentModelId)\n                : undefined;\n              for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {\n                yield* Effect.yieldNow;\n              }\n              if (ctx.interruptedTurnIds.has(turnId)) {\n                yield* settlePromptInFlight(input.threadId, turnId, ctx.acpSessionId, {\n                  completedStopReason: \"cancelled\",\n                  emitTurnCompletion: false,\n                  settleAllPrompts: true,\n                });\n                return yield* new ProviderAdapterRequestError({\n                  provider: PROVIDER,\n                  method: \"session/prompt\",\n                  detail: \"Grok prompt was interrupted during preparation.\",\n                });\n              }\n              if (steeringTurnId === undefined) {\n                ctx.lastPlanFingerprint = undefined;\n              }\n              ctx.session = {\n                ...ctx.session,\n                status: \"running\",\n                activeTurnId: turnId,\n                updatedAt: yield* nowIso,\n                ...(displayModel ? { model: displayModel } : {}),\n              };\n\n              if (steeringTurnId === undefined) {\n                yield* offerRuntimeEvent({\n                  type: \"turn.started\",\n                  ...(yield* makeEventStamp()),\n                  provider: PROVIDER,\n                  threadId: input.threadId,\n                  turnId,\n                  payload: displayModel ? { model: displayModel } : {},\n                });\n              }\n\n              return {\n                acp: ctx.acp,\n                acpSessionId: ctx.acpSessionId,\n                displayModel,\n                promptParts,\n                turnId,\n              };\n            }).pipe(\n              Effect.tapCause(() =>\n                Effect.gen(function* () {\n                  const liveCtx = sessions.get(input.threadId);\n                  if (!liveCtx) {\n                    return;\n                  }\n                  yield* settlePromptInFlight(input.threadId, turnId, liveCtx.acpSessionId, {\n                    errorMessage: \"Grok prompt preparation failed.\",\n                    emitTurnCompletion: false,\n                  });\n                }),\n              ),\n            );\n          }),\n        );\n        const promptSettled = yield* Ref.make(false);\n        const promptRpcSucceeded = yield* Ref.make(false);\n        const promptResultRef = yield* Ref.make<EffectAcpSchema.PromptResponse | undefined>(\n          undefined,\n        );\n\n        const promptFailureMessageRef = yield* Ref.make<string | undefined>(undefined);\n\n        return yield* Effect.gen(function* () {\n          const result = yield* prepared.acp\n            .prompt({\n              prompt: prepared.promptParts,\n            })\n            .pipe(\n              Effect.tap((promptResult) =>\n                Effect.all([\n                  Ref.set(promptRpcSucceeded, true),\n                  Ref.set(promptResultRef, promptResult),\n                ]),\n              ),\n              Effect.tapError((error) =>\n                Ref.set(\n                  promptFailureMessageRef,\n                  mapAcpToAdapterError(PROVIDER, input.threadId, \"session/prompt\", error).message,\n                ).pipe(Effect.andThen(prepared.acp.drainEvents)),\n              ),\n              Effect.mapError((error) =>\n                mapAcpToAdapterError(PROVIDER, input.threadId, \"session/prompt\", error),\n              ),\n            );\n\n          return yield* withThreadLock(\n            input.threadId,\n            Effect.gen(function* () {\n              const ctx = yield* requireSession(input.threadId);\n              if (ctx.acpSessionId !== prepared.acpSessionId) {\n                yield* settlePromptInFlight(\n                  input.threadId,\n                  prepared.turnId,\n                  prepared.acpSessionId,\n                  {\n                    errorMessage: \"Grok session changed before the turn completed.\",\n                    settleAllPrompts: true,\n                  },\n                );\n                yield* Ref.set(promptSettled, true);\n                return yield* new ProviderAdapterRequestError({\n                  provider: PROVIDER,\n                  method: \"session/prompt\",\n                  detail: \"Grok session changed before the turn completed.\",\n                });\n              }\n              // Keep prompt settlement atomic with respect to Stop and steering.\n              // interruptTurn marks its target before waiting for this lock, so\n              // cancellation can still win while queued ACP events are drained.\n              for (let yieldAttempt = 0; yieldAttempt < 8; yieldAttempt += 1) {\n                yield* Effect.yieldNow;\n              }\n              yield* prepared.acp.drainEvents;\n              if (ctx.interruptedTurnIds.has(prepared.turnId)) {\n                yield* Ref.set(promptSettled, true);\n                return {\n                  threadId: input.threadId,\n                  turnId: prepared.turnId,\n                  resumeCursor: ctx.session.resumeCursor,\n                };\n              }\n\n              if (\n                ctx.promptsInFlight <= 0 ||\n                ctx.activeTurnId !== prepared.turnId ||\n                ctx.session.activeTurnId !== prepared.turnId\n              ) {\n                yield* Ref.set(promptSettled, true);\n                return {\n                  threadId: input.threadId,\n                  turnId: prepared.turnId,\n                  resumeCursor: ctx.session.resumeCursor,\n                };\n              }\n\n              appendPromptResultToTurn(ctx, prepared.turnId, prepared.promptParts, result);\n              ctx.session = {\n                ...ctx.session,\n                status: \"running\",\n                activeTurnId: prepared.turnId,\n                updatedAt: yield* nowIso,\n                ...(prepared.displayModel ? { model: prepared.displayModel } : {}),\n              };\n              const remainingPrompts = Math.max(0, ctx.promptsInFlight - 1);\n              ctx.promptsInFlight = remainingPrompts;\n\n              // Only the last remaining prompt settles the turn. A steer-\n              // superseded prompt resolving while another is in flight or\n              // pending must leave the merged turn running.\n              if (\n                remainingPrompts === 0 &&\n                ctx.activeTurnId === prepared.turnId &&\n                ctx.session.activeTurnId === prepared.turnId\n              ) {\n                if (ctx.interruptedTurnIds.has(prepared.turnId)) {\n                  yield* Ref.set(promptSettled, true);\n                  return {\n                    threadId: input.threadId,\n                    turnId: prepared.turnId,\n                    resumeCursor: ctx.session.resumeCursor,\n                  };\n                }\n                const completedAt = yield* nowIso;\n                const { activeTurnId: _completedTurnId, ...readySession } = ctx.session;\n                ctx.activeTurnId = undefined;\n                ctx.session = {\n                  ...readySession,\n                  status: \"ready\",\n                  updatedAt: completedAt,\n                  ...(prepared.displayModel ? { model: prepared.displayModel } : {}),\n                };\n                const completedStopReason = completedStopReasonFromPromptResponse(result);\n                yield* offerRuntimeEvent({\n                  type: \"turn.completed\",\n                  ...(yield* makeEventStamp()),\n                  provider: PROVIDER,\n                  threadId: input.threadId,\n                  turnId: prepared.turnId,\n                  payload: {\n                    state: result.stopReason === \"cancelled\" ? \"cancelled\" : \"completed\",\n                    stopReason: completedStopReason,\n                  },\n                });\n                ctx.interruptedTurnIds.delete(prepared.turnId);\n                yield* Ref.set(promptSettled, true);\n              } else if (remainingPrompts > 0) {\n                yield* Ref.set(promptSettled, true);\n              }\n\n              return {\n                threadId: input.threadId,\n                turnId: prepared.turnId,\n                resumeCursor: ctx.session.resumeCursor,\n              };\n            }),\n          );\n        }).pipe(\n          Effect.ensuring(\n            Effect.gen(function* () {\n              if (yield* Ref.get(promptSettled)) {\n                return;\n              }\n\n              if (yield* Ref.get(promptRpcSucceeded)) {\n                const promptResult = yield* Ref.get(promptResultRef);\n                if (promptResult === undefined) {\n                  return;\n                }\n                yield* withThreadLock(\n                  input.threadId,\n                  Effect.gen(function* () {\n                    const ctx = yield* requireSession(input.threadId);\n                    if (ctx.acpSessionId !== prepared.acpSessionId) {\n                      yield* settlePromptInFlight(\n                        input.threadId,\n                        prepared.turnId,\n                        prepared.acpSessionId,\n                        {\n                          errorMessage: \"Grok session changed before the turn completed.\",\n                          settleAllPrompts: true,\n                        },\n                      );\n                      return;\n                    }\n                    if (ctx.interruptedTurnIds.has(prepared.turnId)) {\n                      return;\n                    }\n                    if (\n                      ctx.promptsInFlight <= 0 ||\n                      ctx.activeTurnId !== prepared.turnId ||\n                      ctx.session.activeTurnId !== prepared.turnId\n                    ) {\n                      return;\n                    }\n                    appendPromptResultToTurn(\n                      ctx,\n                      prepared.turnId,\n                      prepared.promptParts,\n                      promptResult,\n                    );\n                    yield* settlePromptInFlight(\n                      input.threadId,\n                      prepared.turnId,\n                      prepared.acpSessionId,\n                      {\n                        completedStopReason: completedStopReasonFromPromptResponse(promptResult),\n                      },\n                    );\n                  }),\n                );\n                return;\n              }\n\n              const errorMessage = yield* Ref.get(promptFailureMessageRef);\n              yield* withThreadLock(\n                input.threadId,\n                settlePromptInFlight(input.threadId, prepared.turnId, prepared.acpSessionId, {\n                  errorMessage: errorMessage ?? \"Grok prompt request failed.\",\n                }),\n              );\n            }).pipe(Effect.catch(() => Effect.void)),\n          ),\n        );\n      });\n\n    const interruptTurn: GrokAdapterShape[\"interruptTurn\"] = (threadId, turnId) =>\n      Effect.gen(function* () {\n        const observed = yield* Effect.sync(() => {\n          const ctx = sessions.get(threadId);\n          if (!ctx || ctx.stopped) {\n            return {\n              _tag: \"Proceed\" as const,\n              acpSessionId: undefined,\n              interruptedTurnId: turnId,\n            };\n          }\n          const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;\n          if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {\n            return { _tag: \"Ignore\" as const };\n          }\n          const interruptedTurnId = turnId ?? activeTurnId;\n          if (interruptedTurnId !== undefined) {\n            ctx.interruptedTurnIds.add(interruptedTurnId);\n          }\n          return {\n            _tag: \"Proceed\" as const,\n            acpSessionId: ctx.acpSessionId,\n            interruptedTurnId,\n          };\n        });\n        if (observed._tag === \"Ignore\") {\n          return;\n        }\n\n        yield* withThreadLock(\n          threadId,\n          Effect.gen(function* () {\n            const ctx = yield* requireSession(threadId);\n            if (observed.acpSessionId !== undefined && ctx.acpSessionId !== observed.acpSessionId) {\n              return;\n            }\n            const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;\n            if (turnId !== undefined && activeTurnId !== undefined && activeTurnId !== turnId) {\n              return;\n            }\n            if (\n              observed.interruptedTurnId !== undefined &&\n              activeTurnId !== undefined &&\n              activeTurnId !== observed.interruptedTurnId\n            ) {\n              return;\n            }\n            const interruptedTurnId =\n              observed.interruptedTurnId ?? turnId ?? activeTurnId ?? ctx.session.activeTurnId;\n            yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);\n            yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);\n            yield* Effect.ignore(\n              ctx.acp.cancel.pipe(\n                Effect.mapError((error) =>\n                  mapAcpToAdapterError(PROVIDER, threadId, \"session/cancel\", error),\n                ),\n              ),\n            );\n            if (interruptedTurnId) {\n              ctx.interruptedTurnIds.add(interruptedTurnId);\n              yield* settlePromptInFlight(threadId, interruptedTurnId, ctx.acpSessionId, {\n                completedStopReason: \"cancelled\",\n                settleAllPrompts: true,\n              });\n            } else if (\n              ctx.promptsInFlight > 0 ||\n              ctx.session.status === \"running\" ||\n              ctx.session.status === \"connecting\"\n            ) {\n              const updatedAt = yield* nowIso;\n              ctx.promptsInFlight = 0;\n              ctx.activeTurnId = undefined;\n              const { activeTurnId: _activeTurnId, ...readySession } = ctx.session;\n              ctx.session = {\n                ...readySession,\n                status: \"ready\",\n                updatedAt,\n              };\n            }\n          }),\n        );\n      });\n\n    const respondToRequest: GrokAdapterShape[\"respondToRequest\"] = (\n      threadId,\n      requestId,\n      decision,\n    ) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(threadId);\n        const pending = ctx.pendingApprovals.get(requestId);\n        if (!pending) {\n          return yield* new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"session/request_permission\",\n            detail: `Unknown pending approval request: ${requestId}`,\n          });\n        }\n        yield* Deferred.succeed(pending.decision, decision);\n      });\n\n    const respondToUserInput: GrokAdapterShape[\"respondToUserInput\"] = (\n      threadId,\n      requestId,\n      answers,\n    ) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(threadId);\n        const pending = ctx.pendingUserInputs.get(requestId);\n        if (!pending) {\n          return yield* new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"_x.ai/ask_user_question\",\n            detail: `Unknown pending user-input request: ${requestId}`,\n          });\n        }\n        yield* Deferred.succeed(pending.resolution, { _tag: \"answered\", answers });\n      });\n\n    const readThread: GrokAdapterShape[\"readThread\"] = (threadId) =>\n      Effect.gen(function* () {\n        const ctx = yield* requireSession(threadId);\n        return { threadId, turns: ctx.turns };\n      });\n\n    const rollbackThread: GrokAdapterShape[\"rollbackThread\"] = (threadId, numTurns) =>\n      Effect.gen(function* () {\n        yield* requireSession(threadId);\n        if (!Number.isInteger(numTurns) || numTurns < 1) {\n          return yield* new ProviderAdapterValidationError({\n            provider: PROVIDER,\n            operation: \"rollbackThread\",\n            issue: \"numTurns must be an integer >= 1.\",\n          });\n        }\n        return yield* new ProviderAdapterRequestError({\n          provider: PROVIDER,\n          method: \"thread/rollback\",\n          detail: \"Grok ACP sessions do not support provider-side rollback yet.\",\n        });\n      });\n\n    const stopSession: GrokAdapterShape[\"stopSession\"] = (threadId) =>\n      withThreadLock(\n        threadId,\n        Effect.gen(function* () {\n          const ctx = yield* requireSession(threadId);\n          yield* stopSessionInternal(ctx);\n        }),\n      );\n\n    const listSessions: GrokAdapterShape[\"listSessions\"] = () =>\n      Effect.sync(() => Array.from(sessions.values(), (c) => ({ ...c.session })));\n\n    const hasSession: GrokAdapterShape[\"hasSession\"] = (threadId) =>\n      Effect.sync(() => {\n        const c = sessions.get(threadId);\n        return c !== undefined && !c.stopped;\n      });\n\n    const stopAll: GrokAdapterShape[\"stopAll\"] = () =>\n      Effect.forEach(Array.from(sessions.values()), stopSessionInternal, { discard: true });\n\n    yield* Effect.addFinalizer(() =>\n      Effect.ignore(stopAll()).pipe(\n        Effect.tap(() => PubSub.shutdown(runtimeEventPubSub)),\n        Effect.tap(() => managedNativeEventLogger?.close() ?? Effect.void),\n      ),\n    );\n\n    const streamEvents = Stream.fromPubSub(runtimeEventPubSub);\n\n    return {\n      provider: PROVIDER,\n      capabilities: { sessionModelSwitch: \"in-session\" },\n      startSession,\n      sendTurn,\n      interruptTurn,\n      readThread,\n      rollbackThread,\n      respondToRequest,\n      respondToUserInput,\n      stopSession,\n      listSessions,\n      hasSession,\n      stopAll,\n      streamEvents,\n    } satisfies GrokAdapterShape;\n  });\n}\n","import {\n  type GrokSettings,\n  type ModelCapabilities,\n  type ServerProvider,\n  type ServerProviderModel,\n} from \"@t3tools/contracts\";\nimport type * as EffectAcpSchema from \"effect-acp/schema\";\nimport { causeErrorTag } from \"@t3tools/shared/observability\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Option from \"effect/Option\";\nimport * as Result from \"effect/Result\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/unstable/process\";\nimport { createModelCapabilities } from \"@t3tools/shared/model\";\nimport { resolveSpawnCommand } from \"@t3tools/shared/shell\";\n\nimport {\n  buildServerProvider,\n  isCommandMissingCause,\n  parseGenericCliVersion,\n  providerModelsFromSettings,\n  spawnAndCollect,\n  type ServerProviderDraft,\n} from \"../providerSnapshot.ts\";\nimport {\n  enrichProviderSnapshotWithVersionAdvisory,\n  type ProviderMaintenanceCapabilities,\n} from \"../providerMaintenance.ts\";\nimport { makeGrokAcpRuntime, resolveGrokAcpBaseModelId } from \"../acp/GrokAcpSupport.ts\";\n\nconst GROK_PRESENTATION = {\n  displayName: \"Grok\",\n  badgeLabel: \"Early Access\",\n  showInteractionModeToggle: false,\n  requiresNewThreadForModelChange: true,\n} as const;\nconst EMPTY_CAPABILITIES: ModelCapabilities = createModelCapabilities({\n  optionDescriptors: [],\n});\n\nconst VERSION_PROBE_TIMEOUT_MS = 4_000;\nconst GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS = 15_000;\n\nconst GROK_BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [\n  {\n    slug: \"grok-build\",\n    name: \"Grok Build\",\n    isCustom: false,\n    capabilities: EMPTY_CAPABILITIES,\n  },\n];\n\nexport function buildInitialGrokProviderSnapshot(\n  grokSettings: GrokSettings,\n): Effect.Effect<ServerProviderDraft> {\n  return Effect.gen(function* () {\n    const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);\n    const models = grokModelsFromSettings(grokSettings.customModels);\n\n    if (!grokSettings.enabled) {\n      return buildServerProvider({\n        presentation: GROK_PRESENTATION,\n        enabled: false,\n        checkedAt,\n        models,\n        probe: {\n          installed: false,\n          version: null,\n          status: \"warning\",\n          auth: { status: \"unknown\" },\n          message: \"Grok is disabled in Synaptic Code settings.\",\n        },\n      });\n    }\n\n    return buildServerProvider({\n      presentation: GROK_PRESENTATION,\n      enabled: true,\n      checkedAt,\n      models,\n      probe: {\n        installed: true,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Checking Grok CLI availability...\",\n      },\n    });\n  });\n}\n\nfunction grokModelsFromSettings(\n  customModels: ReadonlyArray<string> | undefined,\n  builtInModels: ReadonlyArray<ServerProviderModel> = GROK_BUILT_IN_MODELS,\n): ReadonlyArray<ServerProviderModel> {\n  return providerModelsFromSettings(builtInModels, customModels ?? [], EMPTY_CAPABILITIES);\n}\n\nfunction buildGrokDiscoveredModelsFromSessionModelState(\n  modelState: EffectAcpSchema.SessionModelState | null | undefined,\n): ReadonlyArray<ServerProviderModel> {\n  if (!modelState || modelState.availableModels.length === 0) {\n    return [];\n  }\n  const seen = new Set<string>();\n  return modelState.availableModels\n    .map((model): ServerProviderModel | undefined => {\n      const slug = resolveGrokAcpBaseModelId(model.modelId);\n      if (!slug || seen.has(slug)) {\n        return undefined;\n      }\n      seen.add(slug);\n      return {\n        slug,\n        name: model.name.trim() || slug,\n        isCustom: false,\n        capabilities: EMPTY_CAPABILITIES,\n      };\n    })\n    .filter((model): model is ServerProviderModel => model !== undefined);\n}\n\nconst discoverGrokModelsViaAcp = (\n  grokSettings: GrokSettings,\n  environment: NodeJS.ProcessEnv = process.env,\n) =>\n  Effect.gen(function* () {\n    const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n    const acp = yield* makeGrokAcpRuntime({\n      grokSettings,\n      environment,\n      childProcessSpawner,\n      cwd: process.cwd(),\n      clientInfo: { name: \"synaptic-code-provider-probe\", version: \"0.0.0\" },\n    });\n    const started = yield* acp.start();\n    return buildGrokDiscoveredModelsFromSessionModelState(started.sessionSetupResult.models);\n  }).pipe(Effect.scoped);\n\nconst runGrokVersionCommand = (\n  grokSettings: GrokSettings,\n  environment: NodeJS.ProcessEnv = process.env,\n) =>\n  Effect.gen(function* () {\n    const command = grokSettings.binaryPath || \"grok\";\n    const spawnCommand = yield* resolveSpawnCommand(command, [\"--version\"], {\n      env: environment,\n    });\n    return yield* spawnAndCollect(\n      command,\n      ChildProcess.make(spawnCommand.command, spawnCommand.args, {\n        env: environment,\n        shell: spawnCommand.shell,\n      }),\n    );\n  });\n\nexport const checkGrokProviderStatus = Effect.fn(\"checkGrokProviderStatus\")(function* (\n  grokSettings: GrokSettings,\n  environment: NodeJS.ProcessEnv = process.env,\n): Effect.fn.Return<\n  ServerProviderDraft,\n  never,\n  ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto\n> {\n  const checkedAt = DateTime.formatIso(yield* DateTime.now);\n  const fallbackModels = grokModelsFromSettings(grokSettings.customModels);\n\n  if (!grokSettings.enabled) {\n    return buildServerProvider({\n      presentation: GROK_PRESENTATION,\n      enabled: false,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"Grok is disabled in Synaptic Code settings.\",\n      },\n    });\n  }\n\n  const versionResult = yield* runGrokVersionCommand(grokSettings, environment).pipe(\n    Effect.timeoutOption(VERSION_PROBE_TIMEOUT_MS),\n    Effect.result,\n  );\n\n  if (Result.isFailure(versionResult)) {\n    const error = versionResult.failure;\n    yield* Effect.logWarning(\"Grok CLI health check failed.\", {\n      errorTag: error._tag,\n    });\n    return buildServerProvider({\n      presentation: GROK_PRESENTATION,\n      enabled: grokSettings.enabled,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: !isCommandMissingCause(error),\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: isCommandMissingCause(error)\n          ? \"Grok CLI (`grok`) is not installed or not on PATH.\"\n          : \"Failed to execute Grok CLI health check.\",\n      },\n    });\n  }\n\n  if (Option.isNone(versionResult.success)) {\n    return buildServerProvider({\n      presentation: GROK_PRESENTATION,\n      enabled: grokSettings.enabled,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: true,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: \"Grok CLI is installed but timed out while running `grok --version`.\",\n      },\n    });\n  }\n\n  const versionOutput = versionResult.success.value;\n  const version = parseGenericCliVersion(`${versionOutput.stdout}\\n${versionOutput.stderr}`);\n  if (versionOutput.code !== 0) {\n    yield* Effect.logWarning(\"Grok CLI version probe exited with a non-zero status.\", {\n      exitCode: versionOutput.code,\n      stdoutLength: versionOutput.stdout.length,\n      stderrLength: versionOutput.stderr.length,\n    });\n    return buildServerProvider({\n      presentation: GROK_PRESENTATION,\n      enabled: grokSettings.enabled,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: true,\n        version,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: \"Grok CLI is installed but failed to run.\",\n      },\n    });\n  }\n\n  const discoveryExit = yield* discoverGrokModelsViaAcp(grokSettings, environment).pipe(\n    Effect.timeoutOption(GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS),\n    Effect.exit,\n  );\n  if (Exit.isFailure(discoveryExit)) {\n    yield* Effect.logWarning(\"Grok ACP model discovery failed\", {\n      errorTag: causeErrorTag(discoveryExit.cause),\n    });\n    return buildServerProvider({\n      presentation: GROK_PRESENTATION,\n      enabled: grokSettings.enabled,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: true,\n        version,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: \"Grok CLI is installed but ACP startup failed. Check server logs for details.\",\n      },\n    });\n  }\n  if (Option.isNone(discoveryExit.value)) {\n    yield* Effect.logWarning(\n      `Grok ACP model discovery timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,\n    );\n    return buildServerProvider({\n      presentation: GROK_PRESENTATION,\n      enabled: grokSettings.enabled,\n      checkedAt,\n      models: fallbackModels,\n      probe: {\n        installed: true,\n        version,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: `Grok CLI is installed but ACP startup timed out after ${GROK_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`,\n      },\n    });\n  }\n  const discoveredModels = discoveryExit.value.value;\n  const models =\n    discoveredModels.length > 0\n      ? grokModelsFromSettings(grokSettings.customModels, discoveredModels)\n      : fallbackModels;\n\n  return buildServerProvider({\n    presentation: GROK_PRESENTATION,\n    enabled: grokSettings.enabled,\n    checkedAt,\n    models,\n    probe: {\n      installed: true,\n      version,\n      status: \"ready\",\n      auth: { status: \"unknown\" },\n    },\n  });\n});\n\nexport const enrichGrokSnapshot = (input: {\n  readonly snapshot: ServerProvider;\n  readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;\n  readonly enableProviderUpdateChecks?: boolean;\n  readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;\n  readonly httpClient: HttpClient.HttpClient;\n}): Effect.Effect<void> => {\n  const { snapshot, publishSnapshot } = input;\n\n  return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities, {\n    enableProviderUpdateChecks: input.enableProviderUpdateChecks,\n  }).pipe(\n    Effect.provideService(HttpClient.HttpClient, input.httpClient),\n    Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),\n    Effect.catchCause((cause) =>\n      Effect.logWarning(\"Grok version advisory enrichment failed\", {\n        errorTag: causeErrorTag(cause),\n      }),\n    ),\n    Effect.asVoid,\n  );\n};\n","import { GrokSettings, ProviderDriverKind, type ServerProvider } from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport * as BackgroundPolicy from \"../../background/BackgroundPolicy.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { makeGrokTextGeneration } from \"../../textGeneration/GrokTextGeneration.ts\";\nimport { ProviderDriverError } from \"../Errors.ts\";\nimport { makeGrokAdapter } from \"../Layers/GrokAdapter.ts\";\nimport {\n  buildInitialGrokProviderSnapshot,\n  checkGrokProviderStatus,\n  enrichGrokSnapshot,\n} from \"../Layers/GrokProvider.ts\";\nimport { ProviderEventLoggers } from \"../Layers/ProviderEventLoggers.ts\";\nimport { makeManagedServerProvider } from \"../makeManagedServerProvider.ts\";\nimport {\n  defaultProviderContinuationIdentity,\n  type ProviderDriver,\n  type ProviderInstance,\n} from \"../ProviderDriver.ts\";\nimport type { ServerProviderDraft } from \"../providerSnapshot.ts\";\nimport { mergeProviderInstanceEnvironment } from \"../ProviderInstanceEnvironment.ts\";\nimport {\n  makeManualOnlyProviderMaintenanceCapabilities,\n  makeStaticProviderMaintenanceResolver,\n  resolveProviderMaintenanceCapabilitiesEffect,\n} from \"../providerMaintenance.ts\";\nimport {\n  haveProviderSnapshotSettingsChanged,\n  makeProviderSnapshotSettingsSource,\n  type ProviderSnapshotSettings,\n} from \"../providerUpdateSettings.ts\";\nconst decodeGrokSettings = Schema.decodeSync(GrokSettings);\n\nconst DRIVER_KIND = ProviderDriverKind.make(\"grok\");\nconst UPDATE = makeStaticProviderMaintenanceResolver(\n  makeManualOnlyProviderMaintenanceCapabilities({\n    provider: DRIVER_KIND,\n    packageName: null,\n  }),\n);\n\nexport type GrokDriverEnv =\n  | BackgroundPolicy.BackgroundPolicy\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | HttpClient.HttpClient\n  | Path.Path\n  | ProviderEventLoggers\n  | ServerConfig\n  | ServerSettingsService;\n\nconst withInstanceIdentity =\n  (input: {\n    readonly instanceId: ProviderInstance[\"instanceId\"];\n    readonly displayName: string | undefined;\n    readonly accentColor: string | undefined;\n    readonly continuationGroupKey: string;\n  }) =>\n  (snapshot: ServerProviderDraft): ServerProvider => ({\n    ...snapshot,\n    instanceId: input.instanceId,\n    driver: DRIVER_KIND,\n    ...(input.displayName ? { displayName: input.displayName } : {}),\n    ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n    continuation: { groupKey: input.continuationGroupKey },\n  });\n\nexport const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {\n  driverKind: DRIVER_KIND,\n  metadata: {\n    displayName: \"Grok\",\n    supportsMultipleInstances: true,\n  },\n  configSchema: GrokSettings,\n  defaultConfig: (): GrokSettings => decodeGrokSettings({}),\n  create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n    Effect.gen(function* () {\n      const crypto = yield* Crypto.Crypto;\n      const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n      const httpClient = yield* HttpClient.HttpClient;\n      const serverSettings = yield* ServerSettingsService;\n      const eventLoggers = yield* ProviderEventLoggers;\n      const processEnv = mergeProviderInstanceEnvironment(environment);\n      const continuationIdentity = defaultProviderContinuationIdentity({\n        driverKind: DRIVER_KIND,\n        instanceId,\n      });\n      const stampIdentity = withInstanceIdentity({\n        instanceId,\n        displayName,\n        accentColor,\n        continuationGroupKey: continuationIdentity.continuationKey,\n      });\n      const effectiveConfig = { ...config, enabled } satisfies GrokSettings;\n      const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {\n        binaryPath: effectiveConfig.binaryPath,\n        env: processEnv,\n      });\n\n      const adapter = yield* makeGrokAdapter(effectiveConfig, {\n        environment: processEnv,\n        ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n        instanceId,\n      });\n      const textGeneration = yield* makeGrokTextGeneration(effectiveConfig, processEnv);\n\n      const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(\n        Effect.map(stampIdentity),\n        Effect.provideService(Crypto.Crypto, crypto),\n        Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),\n      );\n\n      const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);\n      const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<GrokSettings>>({\n        maintenanceCapabilities,\n        getSettings: snapshotSettings.getSettings,\n        streamSettings: snapshotSettings.streamSettings,\n        haveSettingsChanged: haveProviderSnapshotSettingsChanged,\n        initialSnapshot: (settings) =>\n          buildInitialGrokProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),\n        checkProvider,\n        enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>\n          enrichGrokSnapshot({\n            snapshot: currentSnapshot,\n            maintenanceCapabilities,\n            enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n            publishSnapshot,\n            httpClient,\n          }),\n      }).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProviderDriverError({\n              driver: DRIVER_KIND,\n              instanceId,\n              detail: `Failed to build Grok snapshot: ${cause.message ?? String(cause)}`,\n              cause,\n            }),\n        ),\n      );\n\n      return {\n        instanceId,\n        driverKind: DRIVER_KIND,\n        continuationIdentity,\n        displayName,\n        accentColor,\n        enabled,\n        snapshot,\n        adapter,\n        textGeneration,\n      } satisfies ProviderInstance;\n    }),\n};\n","import * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Semaphore from \"effect/Semaphore\";\n\nimport {\n  NonNegativeInt,\n  TextGenerationError,\n  type ChatAttachment,\n  type ModelSelection,\n  type OpenCodeSettings,\n} from \"@t3tools/contracts\";\nimport { sanitizeBranchFragment, sanitizeFeatureBranchName } from \"@t3tools/shared/git\";\nimport { getModelSelectionStringOptionValue } from \"@t3tools/shared/model\";\nimport { extractJsonObject } from \"@t3tools/shared/schemaJson\";\n\nimport * as ServerConfig from \"../config.ts\";\nimport { resolveAttachmentPath } from \"../attachmentStore.ts\";\nimport {\n  buildBranchNamePrompt,\n  buildCommitMessagePrompt,\n  buildPrContentPrompt,\n  buildThreadTitlePrompt,\n} from \"./TextGenerationPrompts.ts\";\nimport * as TextGeneration from \"./TextGeneration.ts\";\nimport {\n  sanitizeCommitSubject,\n  sanitizePrTitle,\n  sanitizeThreadTitle,\n} from \"./TextGenerationUtils.ts\";\nimport * as OpenCodeRuntime from \"../provider/opencodeRuntime.ts\";\n\nconst OPENCODE_TEXT_GENERATION_IDLE_TTL = \"30 seconds\";\n\nconst OpenCodeTextGenerationOperation = Schema.Literals([\n  \"generateCommitMessage\",\n  \"generatePrContent\",\n  \"generateBranchName\",\n  \"generateThreadTitle\",\n]);\n\ntype OpenCodeTextGenerationOperation = typeof OpenCodeTextGenerationOperation.Type;\n\nconst openCodeTextGenerationErrorContext = {\n  operation: OpenCodeTextGenerationOperation,\n  cwd: Schema.String,\n};\n\nexport class OpenCodeTextGenerationSessionRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionRequestError>()(\n  \"OpenCodeTextGenerationSessionRequestError\",\n  {\n    ...openCodeTextGenerationErrorContext,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `OpenCode session creation request failed for ${this.operation} in ${this.cwd}.`;\n  }\n}\n\nexport class OpenCodeTextGenerationSessionPayloadError extends Schema.TaggedErrorClass<OpenCodeTextGenerationSessionPayloadError>()(\n  \"OpenCodeTextGenerationSessionPayloadError\",\n  openCodeTextGenerationErrorContext,\n) {\n  override get message(): string {\n    return `OpenCode session.create returned no session payload for ${this.operation} in ${this.cwd}.`;\n  }\n}\n\nconst openCodePromptErrorContext = {\n  ...openCodeTextGenerationErrorContext,\n  sessionId: Schema.String,\n  providerId: Schema.String,\n  modelId: Schema.String,\n};\n\nexport class OpenCodeTextGenerationPromptRequestError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptRequestError>()(\n  \"OpenCodeTextGenerationPromptRequestError\",\n  {\n    ...openCodePromptErrorContext,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `OpenCode prompt request failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}).`;\n  }\n}\n\nexport class OpenCodeTextGenerationPromptResponseError extends Schema.TaggedErrorClass<OpenCodeTextGenerationPromptResponseError>()(\n  \"OpenCodeTextGenerationPromptResponseError\",\n  {\n    ...openCodePromptErrorContext,\n    providerErrorName: Schema.optional(Schema.String),\n    providerMessage: Schema.String,\n  },\n) {\n  override get message(): string {\n    const providerError = this.providerErrorName ? ` ${this.providerErrorName}` : \"\";\n    return `OpenCode prompt${providerError} failed for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}): ${this.providerMessage}`;\n  }\n}\n\nexport class OpenCodeTextGenerationEmptyOutputError extends Schema.TaggedErrorClass<OpenCodeTextGenerationEmptyOutputError>()(\n  \"OpenCodeTextGenerationEmptyOutputError\",\n  {\n    ...openCodePromptErrorContext,\n    responsePartCount: NonNegativeInt,\n    textPartCount: NonNegativeInt,\n  },\n) {\n  override get message(): string {\n    return `OpenCode returned empty output for ${this.operation} in ${this.cwd} using ${this.providerId}/${this.modelId} (session ${this.sessionId}, ${this.responsePartCount} response parts, ${this.textPartCount} text parts).`;\n  }\n}\n\ninterface OpenCodePromptFailure {\n  readonly name?: string;\n  readonly message: string;\n}\n\ninterface OpenCodeTextPart {\n  readonly type: \"text\";\n  readonly text: string;\n}\n\nfunction getOpenCodePromptFailure(error: unknown): OpenCodePromptFailure | null {\n  if (!error || typeof error !== \"object\") {\n    return null;\n  }\n\n  const name =\n    \"name\" in error && typeof error.name === \"string\" && error.name.trim().length > 0\n      ? error.name.trim()\n      : undefined;\n  const message =\n    \"data\" in error &&\n    error.data &&\n    typeof error.data === \"object\" &&\n    \"message\" in error.data &&\n    typeof error.data.message === \"string\"\n      ? error.data.message.trim()\n      : \"\";\n  if (message.length > 0) {\n    return {\n      ...(name ? { name } : {}),\n      message,\n    };\n  }\n\n  if (name) {\n    return { name, message: name };\n  }\n\n  return null;\n}\n\nfunction isOpenCodeTextPart(part: unknown): part is OpenCodeTextPart {\n  return (\n    part !== null &&\n    typeof part === \"object\" &&\n    \"type\" in part &&\n    part.type === \"text\" &&\n    \"text\" in part &&\n    typeof part.text === \"string\"\n  );\n}\n\nfunction getOpenCodeTextResponse(parts: ReadonlyArray<unknown> | undefined): string {\n  return (parts ?? [])\n    .filter(isOpenCodeTextPart)\n    .map((part) => part.text)\n    .join(\"\")\n    .trim();\n}\n\ninterface SharedOpenCodeTextGenerationServerState {\n  server: OpenCodeRuntime.OpenCodeServerProcess | null;\n  /**\n   * The scope that owns the shared server's lifetime. Closing this scope\n   * terminates the OpenCode child process and interrupts any fibers the\n   * runtime forked during startup. We don't hold a `close()` function on\n   * the server handle anymore — the scope is the only lifecycle handle.\n   */\n  serverScope: Scope.Closeable | null;\n  binaryPath: string | null;\n  activeRequests: number;\n  idleCloseFiber: Fiber.Fiber<void, never> | null;\n}\n\nexport const makeOpenCodeTextGeneration = Effect.fn(\"makeOpenCodeTextGeneration\")(function* (\n  openCodeSettings: OpenCodeSettings,\n  environment?: NodeJS.ProcessEnv,\n) {\n  const serverConfig = yield* ServerConfig.ServerConfig;\n  const openCodeRuntime = yield* OpenCodeRuntime.OpenCodeRuntime;\n  const resolvedEnvironment = environment ?? process.env;\n  const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>\n    Scope.close(scope, Exit.void),\n  );\n  const sharedServerMutex = yield* Semaphore.make(1);\n  const sharedServerState: SharedOpenCodeTextGenerationServerState = {\n    server: null,\n    serverScope: null,\n    binaryPath: null,\n    activeRequests: 0,\n    idleCloseFiber: null,\n  };\n\n  const closeSharedServer = Effect.fn(\"closeSharedServer\")(function* () {\n    const scope = sharedServerState.serverScope;\n    sharedServerState.server = null;\n    sharedServerState.serverScope = null;\n    sharedServerState.binaryPath = null;\n    if (scope !== null) {\n      yield* Scope.close(scope, Exit.void).pipe(Effect.ignore);\n    }\n  });\n\n  const cancelIdleCloseFiber = Effect.fn(\"cancelIdleCloseFiber\")(function* () {\n    const idleCloseFiber = sharedServerState.idleCloseFiber;\n    sharedServerState.idleCloseFiber = null;\n    if (idleCloseFiber !== null) {\n      yield* Fiber.interrupt(idleCloseFiber).pipe(Effect.ignore);\n    }\n  });\n\n  const scheduleIdleClose = Effect.fn(\"scheduleIdleClose\")(function* (\n    server: OpenCodeRuntime.OpenCodeServerProcess,\n  ) {\n    yield* cancelIdleCloseFiber();\n    const fiber = yield* Effect.sleep(OPENCODE_TEXT_GENERATION_IDLE_TTL).pipe(\n      Effect.andThen(\n        sharedServerMutex.withPermit(\n          Effect.gen(function* () {\n            if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {\n              return;\n            }\n            sharedServerState.idleCloseFiber = null;\n            yield* closeSharedServer();\n          }),\n        ),\n      ),\n      Effect.forkIn(idleFiberScope),\n    );\n    sharedServerState.idleCloseFiber = fiber;\n  });\n\n  const acquireSharedServer = (input: {\n    readonly binaryPath: string;\n    readonly operation:\n      | \"generateCommitMessage\"\n      | \"generatePrContent\"\n      | \"generateBranchName\"\n      | \"generateThreadTitle\";\n  }) =>\n    sharedServerMutex.withPermit(\n      Effect.gen(function* () {\n        yield* cancelIdleCloseFiber();\n\n        const existingServer = sharedServerState.server;\n        if (existingServer !== null) {\n          if (\n            sharedServerState.binaryPath !== input.binaryPath &&\n            sharedServerState.activeRequests === 0\n          ) {\n            yield* closeSharedServer();\n          } else {\n            if (sharedServerState.binaryPath !== input.binaryPath) {\n              yield* Effect.logWarning(\n                \"OpenCode shared server binary path mismatch: requested \" +\n                  input.binaryPath +\n                  \" but active server uses \" +\n                  sharedServerState.binaryPath +\n                  \"; reusing existing server because there are active requests\",\n              );\n            }\n            sharedServerState.activeRequests += 1;\n            return existingServer;\n          }\n        }\n\n        // Create a fresh scope that owns this shared server. The runtime\n        // will attach its child-process and fiber finalizers to this scope;\n        // closing it kills the server and interrupts those fibers.\n        //\n        // The `Scope.make` / spawn / record-or-close transitions run inside\n        // `uninterruptibleMask` so an interrupt arriving between any two\n        // steps can't orphan the scope (and the child process attached to\n        // it) before we either close it on failure or hand ownership to\n        // `sharedServerState`. `restore` keeps the actual spawn\n        // interruptible; an interrupt during the spawn is captured by\n        // `Effect.exit` and drives us through the failure branch that\n        // closes the fresh scope.\n        return yield* Effect.uninterruptibleMask((restore) =>\n          Effect.gen(function* () {\n            const serverScope = yield* Scope.make();\n            const startedExit = yield* Effect.exit(\n              restore(\n                openCodeRuntime\n                  .startOpenCodeServerProcess({\n                    binaryPath: input.binaryPath,\n                    environment: resolvedEnvironment,\n                  })\n                  .pipe(\n                    Effect.provideService(Scope.Scope, serverScope),\n                    Effect.mapError(\n                      (cause) =>\n                        new TextGenerationError({\n                          operation: input.operation,\n                          detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),\n                          cause,\n                        }),\n                    ),\n                  ),\n              ),\n            );\n            if (startedExit._tag === \"Failure\") {\n              yield* Scope.close(serverScope, Exit.void).pipe(Effect.ignore);\n              return yield* Effect.failCause(startedExit.cause);\n            }\n\n            const server = startedExit.value;\n            sharedServerState.server = server;\n            sharedServerState.serverScope = serverScope;\n            sharedServerState.binaryPath = input.binaryPath;\n            sharedServerState.activeRequests = 1;\n            return server;\n          }),\n        );\n      }),\n    );\n\n  const releaseSharedServer = (server: OpenCodeRuntime.OpenCodeServerProcess) =>\n    sharedServerMutex.withPermit(\n      Effect.gen(function* () {\n        if (sharedServerState.server !== server) {\n          return;\n        }\n        sharedServerState.activeRequests = Math.max(0, sharedServerState.activeRequests - 1);\n        if (sharedServerState.activeRequests === 0) {\n          yield* scheduleIdleClose(server);\n        }\n      }),\n    );\n\n  // Module-level finalizer: on layer shutdown, cancel the idle close fiber\n  // and close the shared server scope. Consumers therefore cannot leak\n  // the shared OpenCode server by forgetting to call anything.\n  yield* Effect.addFinalizer(() =>\n    sharedServerMutex.withPermit(\n      Effect.gen(function* () {\n        yield* cancelIdleCloseFiber();\n        sharedServerState.activeRequests = 0;\n        yield* closeSharedServer();\n      }),\n    ),\n  );\n\n  const runOpenCodeJson = Effect.fn(\"runOpenCodeJson\")(function* <S extends Schema.Top>(input: {\n    readonly operation: OpenCodeTextGenerationOperation;\n    readonly cwd: string;\n    readonly prompt: string;\n    readonly outputSchemaJson: S;\n    readonly modelSelection: ModelSelection;\n    readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;\n  }) {\n    const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(input.modelSelection.model);\n    if (!parsedModel) {\n      return yield* new TextGenerationError({\n        operation: input.operation,\n        detail: \"OpenCode model selection must use the 'provider/model' format.\",\n      });\n    }\n\n    const fileParts = OpenCodeRuntime.toOpenCodeFileParts({\n      attachments: input.attachments,\n      resolveAttachmentPath: (attachment) =>\n        resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),\n    });\n\n    const runAgainstServer = Effect.fn(\"runOpenCodeJson.runAgainstServer\")(\n      function* (server: Pick<OpenCodeRuntime.OpenCodeServerConnection, \"url\">) {\n        const client = openCodeRuntime.createOpenCodeSdkClient({\n          baseUrl: server.url,\n          directory: input.cwd,\n          ...(openCodeSettings.serverUrl.length > 0 && openCodeSettings.serverPassword\n            ? { serverPassword: openCodeSettings.serverPassword }\n            : {}),\n        });\n        const session = yield* Effect.tryPromise({\n          try: () =>\n            client.session.create({\n              title: `Synaptic Code ${input.operation}`,\n              permission: [{ permission: \"*\", pattern: \"*\", action: \"deny\" }],\n            }),\n          catch: (cause) =>\n            new OpenCodeTextGenerationSessionRequestError({\n              operation: input.operation,\n              cwd: input.cwd,\n              cause,\n            }),\n        });\n        if (!session.data) {\n          return yield* new OpenCodeTextGenerationSessionPayloadError({\n            operation: input.operation,\n            cwd: input.cwd,\n          });\n        }\n        const selectedAgent = getModelSelectionStringOptionValue(input.modelSelection, \"agent\");\n        const selectedVariant = getModelSelectionStringOptionValue(input.modelSelection, \"variant\");\n        const promptContext = {\n          operation: input.operation,\n          cwd: input.cwd,\n          sessionId: session.data.id,\n          providerId: parsedModel.providerID,\n          modelId: parsedModel.modelID,\n        };\n\n        const result = yield* Effect.tryPromise({\n          try: () =>\n            client.session.prompt({\n              sessionID: session.data.id,\n              model: parsedModel,\n              ...(selectedAgent ? { agent: selectedAgent } : {}),\n              ...(selectedVariant ? { variant: selectedVariant } : {}),\n              parts: [{ type: \"text\", text: input.prompt }, ...fileParts],\n            }),\n          catch: (cause) =>\n            new OpenCodeTextGenerationPromptRequestError({\n              ...promptContext,\n              cause,\n            }),\n        });\n        const promptFailure = getOpenCodePromptFailure(result.data?.info?.error);\n        if (promptFailure) {\n          return yield* new OpenCodeTextGenerationPromptResponseError({\n            ...promptContext,\n            ...(promptFailure.name ? { providerErrorName: promptFailure.name } : {}),\n            providerMessage: promptFailure.message,\n          });\n        }\n        const responseParts = result.data?.parts ?? [];\n        const rawText = getOpenCodeTextResponse(responseParts);\n        if (rawText.length === 0) {\n          return yield* new OpenCodeTextGenerationEmptyOutputError({\n            ...promptContext,\n            responsePartCount: responseParts.length,\n            textPartCount: responseParts.filter(isOpenCodeTextPart).length,\n          });\n        }\n        return rawText;\n      },\n      Effect.catchTags({\n        OpenCodeTextGenerationSessionRequestError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation: cause.operation,\n              detail: \"OpenCode session.create request failed.\",\n              cause,\n            }),\n          ),\n        OpenCodeTextGenerationSessionPayloadError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation: cause.operation,\n              detail: \"OpenCode session.create returned no session payload.\",\n              cause,\n            }),\n          ),\n        OpenCodeTextGenerationPromptRequestError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation: cause.operation,\n              detail: \"OpenCode session.prompt request failed.\",\n              cause,\n            }),\n          ),\n        OpenCodeTextGenerationPromptResponseError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation: cause.operation,\n              detail: cause.providerMessage,\n              cause,\n            }),\n          ),\n        OpenCodeTextGenerationEmptyOutputError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation: cause.operation,\n              detail: \"OpenCode returned empty output.\",\n              cause,\n            }),\n          ),\n      }),\n    );\n\n    const rawOutput =\n      openCodeSettings.serverUrl.length > 0\n        ? yield* runAgainstServer({ url: openCodeSettings.serverUrl })\n        : yield* Effect.acquireUseRelease(\n            acquireSharedServer({\n              binaryPath: openCodeSettings.binaryPath,\n              operation: input.operation,\n            }),\n            runAgainstServer,\n            releaseSharedServer,\n          );\n\n    const decodeOutput = Schema.decodeEffect(Schema.fromJsonString(input.outputSchemaJson));\n    return yield* decodeOutput(extractJsonObject(rawOutput)).pipe(\n      Effect.catchTags({\n        SchemaError: (cause) =>\n          Effect.fail(\n            new TextGenerationError({\n              operation: input.operation,\n              detail: \"OpenCode returned invalid structured output.\",\n              cause,\n            }),\n          ),\n      }),\n    );\n  });\n\n  const generateCommitMessage: TextGeneration.TextGeneration[\"Service\"][\"generateCommitMessage\"] =\n    Effect.fn(\"OpenCodeTextGeneration.generateCommitMessage\")(function* (input) {\n      const { prompt, outputSchema } = buildCommitMessagePrompt({\n        branch: input.branch,\n        stagedSummary: input.stagedSummary,\n        stagedPatch: input.stagedPatch,\n        includeBranch: input.includeBranch === true,\n        policy: input.policy,\n      });\n      const generated = yield* runOpenCodeJson({\n        operation: \"generateCommitMessage\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        subject: sanitizeCommitSubject(generated.subject),\n        body: generated.body.trim(),\n        ...(\"branch\" in generated && typeof generated.branch === \"string\"\n          ? { branch: sanitizeFeatureBranchName(generated.branch) }\n          : {}),\n      };\n    });\n\n  const generatePrContent: TextGeneration.TextGeneration[\"Service\"][\"generatePrContent\"] =\n    Effect.fn(\"OpenCodeTextGeneration.generatePrContent\")(function* (input) {\n      const { prompt, outputSchema } = buildPrContentPrompt({\n        baseBranch: input.baseBranch,\n        headBranch: input.headBranch,\n        commitSummary: input.commitSummary,\n        diffSummary: input.diffSummary,\n        diffPatch: input.diffPatch,\n        policy: input.policy,\n        changeRequestTemplate: input.changeRequestTemplate,\n      });\n      const generated = yield* runOpenCodeJson({\n        operation: \"generatePrContent\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n      });\n\n      return {\n        title: sanitizePrTitle(generated.title),\n        body: generated.body.trim(),\n      };\n    });\n\n  const generateBranchName: TextGeneration.TextGeneration[\"Service\"][\"generateBranchName\"] =\n    Effect.fn(\"OpenCodeTextGeneration.generateBranchName\")(function* (input) {\n      const { prompt, outputSchema } = buildBranchNamePrompt({\n        message: input.message,\n        attachments: input.attachments,\n      });\n      const generated = yield* runOpenCodeJson({\n        operation: \"generateBranchName\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n        attachments: input.attachments,\n      });\n\n      return {\n        branch: sanitizeBranchFragment(generated.branch),\n      };\n    });\n\n  const generateThreadTitle: TextGeneration.TextGeneration[\"Service\"][\"generateThreadTitle\"] =\n    Effect.fn(\"OpenCodeTextGeneration.generateThreadTitle\")(function* (input) {\n      const { prompt, outputSchema } = buildThreadTitlePrompt({\n        message: input.message,\n        previousTitle: input.previousTitle,\n        attachments: input.attachments,\n      });\n      const generated = yield* runOpenCodeJson({\n        operation: \"generateThreadTitle\",\n        cwd: input.cwd,\n        prompt,\n        outputSchemaJson: outputSchema,\n        modelSelection: input.modelSelection,\n        attachments: input.attachments,\n      });\n\n      return {\n        title: sanitizeThreadTitle(generated.title),\n      };\n    });\n\n  return {\n    generateCommitMessage,\n    generatePrContent,\n    generateBranchName,\n    generateThreadTitle,\n  } satisfies TextGeneration.TextGeneration[\"Service\"];\n});\n","import {\n  EventId,\n  type OpenCodeSettings,\n  ProviderDriverKind,\n  ProviderInstanceId,\n  type ProviderRuntimeEvent,\n  type ProviderSession,\n  RuntimeItemId,\n  RuntimeRequestId,\n  ThreadId,\n  type ToolLifecycleItemType,\n  TurnId,\n  type UserInputQuestion,\n} from \"@t3tools/contracts\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from \"@opencode-ai/sdk/v2\";\nimport { getModelSelectionStringOptionValue } from \"@t3tools/shared/model\";\n\nimport { resolveAttachmentPath } from \"../../attachmentStore.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport * as McpProviderSession from \"../../mcp/McpProviderSession.ts\";\nimport { type EventNdjsonLogger, makeEventNdjsonLogger } from \"./EventNdjsonLogger.ts\";\nimport {\n  ProviderAdapterProcessError,\n  ProviderAdapterRequestError,\n  ProviderAdapterSessionClosedError,\n  ProviderAdapterSessionNotFoundError,\n  ProviderAdapterValidationError,\n} from \"../Errors.ts\";\nimport { type OpenCodeAdapterShape } from \"../Services/OpenCodeAdapter.ts\";\nimport {\n  buildOpenCodePermissionRules,\n  OpenCodeRuntime,\n  OpenCodeRuntimeError,\n  openCodeQuestionId,\n  openCodeRuntimeErrorDetail,\n  parseOpenCodeModelSlug,\n  runOpenCodeSdk,\n  toOpenCodeFileParts,\n  toOpenCodePermissionReply,\n  toOpenCodeQuestionAnswers,\n  type OpenCodeServerConnection,\n} from \"../opencodeRuntime.ts\";\nimport * as Option from \"effect/Option\";\n\nconst PROVIDER = ProviderDriverKind.make(\"opencode\");\n\n/**\n * Version tag stamped into the OpenCode resume cursor. Bump if the cursor\n * shape changes so stale-shaped cursors written by older builds are ignored\n * rather than misread (mirrors GROK_RESUME_VERSION / CURSOR_RESUME_VERSION).\n */\nconst OPENCODE_RESUME_VERSION = 1 as const;\n\n/**\n * Decode a persisted resume cursor into the upstream `ses_…` id. Anything\n * that isn't a current-version cursor with a non-empty id means \"no resume\"\n * rather than an error. Re-adopting the session id IS the resume mechanism —\n * OpenCode scopes a conversation's history by session id.\n */\nfunction parseOpenCodeResume(raw: unknown): { readonly sessionId: string } | undefined {\n  if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) {\n    return undefined;\n  }\n  const record = raw as Record<string, unknown>;\n  if (record.schemaVersion !== OPENCODE_RESUME_VERSION) {\n    return undefined;\n  }\n  if (typeof record.sessionId !== \"string\" || record.sessionId.trim().length === 0) {\n    return undefined;\n  }\n  return { sessionId: record.sessionId.trim() };\n}\n\n/**\n * Whether an error definitively reports a missing session. Only a confirmed\n * miss may silently start a fresh session; any other failure (the SDK client\n * is `throwOnError: true`, so `session.get` rejects on every non-2xx) must\n * propagate, or a transient blip resets a live thread to an empty one — the\n * #3604 silent context loss. Decides on structured signals only, never free\n * text: a numeric 404 or the exact `NotFoundError` name, found via a bounded walk\n * over `cause`/`body`/`error`/`data`. An explicit non-404 status seals its\n * subtree so a wrapped \"NotFound\" name can't reclassify a real failure.\n * Exported for unit testing.\n */\nexport function isOpenCodeNotFound(cause: unknown): boolean {\n  const seen = new Set<unknown>();\n  const queue: Array<unknown> = [cause];\n  for (let steps = 0; queue.length > 0 && steps < 32; steps += 1) {\n    const node = queue.shift();\n    if (node === null || typeof node !== \"object\" || seen.has(node)) {\n      continue;\n    }\n    seen.add(node);\n    const record = node as Record<string, unknown>;\n\n    const response = record.response;\n    const statuses = [\n      record.status,\n      record.statusCode,\n      response !== null && typeof response === \"object\"\n        ? (response as { readonly status?: unknown }).status\n        : undefined,\n    ].filter((status): status is number => typeof status === \"number\");\n    if (statuses.includes(404)) {\n      return true;\n    }\n    if (statuses.length > 0) {\n      continue;\n    }\n\n    const name = record.name;\n    if (typeof name === \"string\" && name.toLowerCase() === \"notfounderror\") {\n      return true;\n    }\n\n    for (const key of [\"cause\", \"body\", \"error\", \"data\"] as const) {\n      if (record[key] !== undefined) {\n        queue.push(record[key]);\n      }\n    }\n  }\n  return false;\n}\n\n/**\n * Whether two directory spellings name the same location. Raw string\n * equality misreads a trailing slash, `.`/`..` segment, or symlinked cwd\n * (macOS `/tmp` → `/private/tmp`) as a cwd change, needlessly forking the\n * session on every resume. Lexically equal paths short-circuit; otherwise\n * both sides go through `realPath`, each falling back to its lexical form\n * on failure (deleted directory, external-server path) — so the probe can\n * only widen matches, never split them. Takes the services as arguments so\n * adapter methods stay service-free. Exported for unit testing.\n */\nexport function isSameOpenCodeDirectory(\n  fileSystem: FileSystem.FileSystem,\n  path: Path.Path,\n  left: string,\n  right: string,\n): Effect.Effect<boolean> {\n  const lexicalLeft = path.resolve(left);\n  const lexicalRight = path.resolve(right);\n  if (lexicalLeft === lexicalRight) {\n    return Effect.succeed(true);\n  }\n  const canonicalize = (lexical: string) =>\n    fileSystem.realPath(lexical).pipe(Effect.orElseSucceed(() => lexical));\n  return Effect.zipWith(\n    canonicalize(lexicalLeft),\n    canonicalize(lexicalRight),\n    (canonicalLeft, canonicalRight) => canonicalLeft === canonicalRight,\n  );\n}\n\ninterface OpenCodeTurnSnapshot {\n  readonly id: TurnId;\n  readonly items: Array<unknown>;\n}\n\ntype OpenCodeSubscribedEvent =\n  Awaited<ReturnType<OpencodeClient[\"event\"][\"subscribe\"]>> extends {\n    readonly stream: AsyncIterable<infer TEvent>;\n  }\n    ? TEvent\n    : never;\n\nfunction trimText(value: string | undefined | null): string | undefined {\n  const trimmed = value?.trim();\n  return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction openCodeEventSessionId(event: OpenCodeSubscribedEvent): string | undefined {\n  const properties = \"properties\" in event ? event.properties : undefined;\n  if (!properties || typeof properties !== \"object\") {\n    return undefined;\n  }\n\n  const sessionID = (properties as { readonly sessionID?: unknown }).sessionID;\n  const sessionIDFromProperties = typeof sessionID === \"string\" ? sessionID : undefined;\n  if (sessionIDFromProperties) {\n    return sessionIDFromProperties;\n  }\n\n  const info = (properties as { readonly info?: { readonly id?: unknown } }).info;\n  return info && typeof info.id === \"string\" ? info.id : undefined;\n}\n\nfunction openCodeEventSessionTitle(event: OpenCodeSubscribedEvent): string | undefined {\n  if (event.type !== \"session.updated\") {\n    return undefined;\n  }\n\n  return trimText(event.properties.info.title);\n}\n\ninterface OpenCodeSessionContext {\n  session: ProviderSession;\n  readonly client: OpencodeClient;\n  readonly server: OpenCodeServerConnection;\n  readonly directory: string;\n  readonly openCodeSessionId: string;\n  readonly pendingPermissions: Map<string, PermissionRequest>;\n  readonly pendingQuestions: Map<string, QuestionRequest>;\n  readonly messageRoleById: Map<string, \"user\" | \"assistant\">;\n  readonly partById: Map<string, Part>;\n  readonly emittedTextByPartId: Map<string, string>;\n  readonly completedAssistantPartIds: Set<string>;\n  readonly turns: Array<OpenCodeTurnSnapshot>;\n  activeTurnId: TurnId | undefined;\n  activeAgent: string | undefined;\n  activeVariant: string | undefined;\n  /**\n   * One-shot guard flipped by `stopOpenCodeContext` / `emitUnexpectedExit`.\n   * The session lifecycle is owned by `sessionScope`; this Ref exists only\n   * so concurrent callers can race the transition safely via `getAndSet`.\n   */\n  readonly stopped: Ref.Ref<boolean>;\n  /**\n   * Sole lifecycle handle for the session. Closing this scope:\n   *   - aborts the `AbortController` registered as a finalizer\n   *     (cancels the in-flight `event.subscribe` fetch),\n   *   - interrupts the event-pump and server-exit fibers forked\n   *     via `Effect.forkIn(sessionScope)`,\n   *   - tears down the OpenCode server process for scope-owned servers.\n   */\n  readonly sessionScope: Scope.Closeable;\n}\n\nexport interface OpenCodeAdapterLiveOptions {\n  readonly instanceId?: ProviderInstanceId;\n  readonly environment?: NodeJS.ProcessEnv;\n  readonly nativeEventLogPath?: string;\n  readonly nativeEventLogger?: EventNdjsonLogger;\n}\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\n/**\n * Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into\n * the adapter-boundary `ProviderAdapterRequestError`. SDK-method-level call\n * sites pipe through this in `Effect.mapError` so they never build the error\n * shape by hand.\n */\nconst toRequestError = (cause: OpenCodeRuntimeError): ProviderAdapterRequestError =>\n  new ProviderAdapterRequestError({\n    provider: PROVIDER,\n    method: cause.operation,\n    detail: cause.detail,\n    cause: cause.cause,\n  });\n\n/**\n * Map a `Cause.squash`-ed failure into a `ProviderAdapterProcessError`. The\n * typed cause is usually an `OpenCodeRuntimeError` (from {@link runOpenCodeSdk}),\n * in which case we preserve its `detail`; otherwise we fall back to\n * {@link openCodeRuntimeErrorDetail} for unknown causes (defects, etc.).\n */\nconst toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProcessError =>\n  new ProviderAdapterProcessError({\n    provider: PROVIDER,\n    threadId,\n    detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),\n    cause,\n  });\n\ntype EventBaseInput = {\n  readonly threadId: ThreadId;\n  readonly turnId?: TurnId | undefined;\n  readonly itemId?: string | undefined;\n  readonly requestId?: string | undefined;\n  readonly createdAt?: string | undefined;\n  readonly raw?: unknown;\n};\n\nfunction toToolLifecycleItemType(toolName: string): ToolLifecycleItemType {\n  const normalized = toolName.toLowerCase();\n  if (normalized.includes(\"bash\") || normalized.includes(\"command\")) {\n    return \"command_execution\";\n  }\n  if (\n    normalized.includes(\"edit\") ||\n    normalized.includes(\"write\") ||\n    normalized.includes(\"patch\") ||\n    normalized.includes(\"multiedit\")\n  ) {\n    return \"file_change\";\n  }\n  if (normalized.includes(\"web\")) {\n    return \"web_search\";\n  }\n  if (normalized.includes(\"mcp\")) {\n    return \"mcp_tool_call\";\n  }\n  if (normalized.includes(\"image\")) {\n    return \"image_view\";\n  }\n  if (\n    normalized.includes(\"task\") ||\n    normalized.includes(\"agent\") ||\n    normalized.includes(\"subtask\")\n  ) {\n    return \"collab_agent_tool_call\";\n  }\n  return \"dynamic_tool_call\";\n}\n\nfunction mapPermissionToRequestType(\n  permission: string,\n): \"command_execution_approval\" | \"file_read_approval\" | \"file_change_approval\" | \"unknown\" {\n  switch (permission) {\n    case \"bash\":\n      return \"command_execution_approval\";\n    case \"read\":\n      return \"file_read_approval\";\n    case \"edit\":\n      return \"file_change_approval\";\n    default:\n      return \"unknown\";\n  }\n}\n\nfunction mapPermissionDecision(reply: \"once\" | \"always\" | \"reject\"): string {\n  switch (reply) {\n    case \"once\":\n      return \"accept\";\n    case \"always\":\n      return \"acceptForSession\";\n    case \"reject\":\n    default:\n      return \"decline\";\n  }\n}\n\nfunction resolveTurnSnapshot(\n  context: OpenCodeSessionContext,\n  turnId: TurnId,\n): OpenCodeTurnSnapshot {\n  const existing = context.turns.find((turn) => turn.id === turnId);\n  if (existing) {\n    return existing;\n  }\n\n  const created: OpenCodeTurnSnapshot = { id: turnId, items: [] };\n  context.turns.push(created);\n  return created;\n}\n\nfunction appendTurnItem(\n  context: OpenCodeSessionContext,\n  turnId: TurnId | undefined,\n  item: unknown,\n): void {\n  if (!turnId) {\n    return;\n  }\n  resolveTurnSnapshot(context, turnId).items.push(item);\n}\n\nconst ensureSessionContext = Effect.fn(\"ensureSessionContext\")(function* (\n  sessions: ReadonlyMap<ThreadId, OpenCodeSessionContext>,\n  threadId: ThreadId,\n) {\n  const session = sessions.get(threadId);\n  if (!session) {\n    return yield* new ProviderAdapterSessionNotFoundError({\n      provider: PROVIDER,\n      threadId,\n    });\n  }\n  if (yield* Ref.get(session.stopped)) {\n    return yield* new ProviderAdapterSessionClosedError({\n      provider: PROVIDER,\n      threadId,\n    });\n  }\n  return session;\n});\n\nfunction normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray<UserInputQuestion> {\n  return request.questions.map((question, index) => ({\n    id: openCodeQuestionId(index, question),\n    header: question.header,\n    question: question.question,\n    options: question.options.map((option) => ({\n      label: option.label,\n      description: option.description,\n    })),\n    ...(question.multiple ? { multiSelect: true } : {}),\n  }));\n}\n\nfunction resolveTextStreamKind(part: Part | undefined): \"assistant_text\" | \"reasoning_text\" {\n  return part?.type === \"reasoning\" ? \"reasoning_text\" : \"assistant_text\";\n}\n\nfunction textFromPart(part: Part): string | undefined {\n  switch (part.type) {\n    case \"text\":\n    case \"reasoning\":\n      return part.text;\n    default:\n      return undefined;\n  }\n}\n\nfunction commonPrefixLength(left: string, right: string): number {\n  let index = 0;\n  while (index < left.length && index < right.length && left[index] === right[index]) {\n    index += 1;\n  }\n  return index;\n}\n\nfunction resolveLatestAssistantText(previousText: string | undefined, nextText: string): string {\n  if (previousText && previousText.length > nextText.length && previousText.startsWith(nextText)) {\n    return previousText;\n  }\n  return nextText;\n}\n\nexport function mergeOpenCodeAssistantText(\n  previousText: string | undefined,\n  nextText: string,\n): {\n  readonly latestText: string;\n  readonly deltaToEmit: string;\n} {\n  const latestText = resolveLatestAssistantText(previousText, nextText);\n  return {\n    latestText,\n    deltaToEmit: latestText.slice(commonPrefixLength(previousText ?? \"\", latestText)),\n  };\n}\n\nexport function appendOpenCodeAssistantTextDelta(\n  previousText: string,\n  delta: string,\n): {\n  readonly nextText: string;\n  readonly deltaToEmit: string;\n} {\n  return {\n    nextText: previousText + delta,\n    deltaToEmit: delta,\n  };\n}\n\nconst isoFromEpochMs = (value: number) =>\n  DateTime.make(value).pipe(\n    Option.match({\n      onNone: () => undefined,\n      onSome: DateTime.formatIso,\n    }),\n  );\n\nfunction messageRoleForPart(\n  context: OpenCodeSessionContext,\n  part: Pick<Part, \"messageID\" | \"type\">,\n): \"assistant\" | \"user\" | undefined {\n  const known = context.messageRoleById.get(part.messageID);\n  if (known) {\n    return known;\n  }\n  return part.type === \"tool\" ? \"assistant\" : undefined;\n}\n\nfunction detailFromToolPart(part: Extract<Part, { type: \"tool\" }>): string | undefined {\n  switch (part.state.status) {\n    case \"completed\":\n      return part.state.output;\n    case \"error\":\n      return part.state.error;\n    case \"running\":\n      return part.state.title;\n    default:\n      return undefined;\n  }\n}\n\nfunction toolStateCreatedAt(part: Extract<Part, { type: \"tool\" }>): string | undefined {\n  switch (part.state.status) {\n    case \"running\":\n      return isoFromEpochMs(part.state.time.start);\n    case \"completed\":\n    case \"error\":\n      return isoFromEpochMs(part.state.time.end);\n    default:\n      return undefined;\n  }\n}\n\nfunction sessionErrorMessage(error: unknown): string {\n  if (!error || typeof error !== \"object\") {\n    return \"OpenCode session failed.\";\n  }\n  const data = \"data\" in error && error.data && typeof error.data === \"object\" ? error.data : null;\n  const message = data && \"message\" in data ? data.message : null;\n  return typeof message === \"string\" && message.trim().length > 0\n    ? message\n    : \"OpenCode session failed.\";\n}\n\nfunction updateProviderSession(\n  context: OpenCodeSessionContext,\n  patch: Partial<ProviderSession>,\n  options?: {\n    readonly clearActiveTurnId?: boolean;\n    readonly clearLastError?: boolean;\n  },\n): Effect.Effect<ProviderSession> {\n  return Effect.gen(function* () {\n    const updatedAt = yield* nowIso;\n    const nextSession = {\n      ...context.session,\n      ...patch,\n      updatedAt,\n    } as ProviderSession & Record<string, unknown>;\n    const mutableSession = nextSession as Record<string, unknown>;\n    if (options?.clearActiveTurnId) {\n      delete mutableSession.activeTurnId;\n    }\n    if (options?.clearLastError) {\n      delete mutableSession.lastError;\n    }\n    context.session = nextSession;\n    return nextSession;\n  });\n}\n\nconst stopOpenCodeContext = Effect.fn(\"stopOpenCodeContext\")(function* (\n  context: OpenCodeSessionContext,\n) {\n  // Race-safe one-shot: first caller flips the flag, everyone else no-ops.\n  if (yield* Ref.getAndSet(context.stopped, true)) {\n    return false;\n  }\n\n  // Best-effort remote abort. The scope close below tears down the local\n  // handles (event-pump fiber, server-exit fiber, event-subscribe fetch),\n  // but we still want to tell OpenCode that this session is done.\n  yield* runOpenCodeSdk(\"session.abort\", () =>\n    context.client.session.abort({ sessionID: context.openCodeSessionId }),\n  ).pipe(Effect.ignore({ log: true }));\n\n  // Closing the session scope interrupts every fiber forked into it and\n  // runs each finalizer we registered — the `AbortController.abort()` call,\n  // the child-process termination, etc.\n  yield* Scope.close(context.sessionScope, Exit.void);\n  return true;\n});\n\nexport function makeOpenCodeAdapter(\n  openCodeSettings: OpenCodeSettings,\n  options?: OpenCodeAdapterLiveOptions,\n) {\n  return Effect.gen(function* () {\n    const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make(\"opencode\");\n    const serverConfig = yield* ServerConfig;\n    const openCodeRuntime = yield* OpenCodeRuntime;\n    const crypto = yield* Crypto.Crypto;\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n    const sameDirectory = (left: string, right: string) =>\n      isSameOpenCodeDirectory(fileSystem, path, left, right);\n    const nativeEventLogger =\n      options?.nativeEventLogger ??\n      (options?.nativeEventLogPath !== undefined\n        ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {\n            stream: \"native\",\n          })\n        : undefined);\n    // Only close loggers we created. If the caller passed one in via\n    // `options.nativeEventLogger`, they own its lifecycle.\n    const managedNativeEventLogger =\n      options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;\n    const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();\n    const sessions = new Map<ThreadId, OpenCodeSessionContext>();\n    const randomUUIDv4 = crypto.randomUUIDv4.pipe(\n      Effect.mapError(\n        (cause) =>\n          new ProviderAdapterRequestError({\n            provider: PROVIDER,\n            method: \"crypto/randomUUIDv4\",\n            detail: \"Failed to generate OpenCode runtime identifier.\",\n            cause,\n          }),\n      ),\n    );\n    const buildEventBase = (input: EventBaseInput) =>\n      Effect.all({\n        eventId: randomUUIDv4.pipe(Effect.map(EventId.make)),\n        createdAt: input.createdAt === undefined ? nowIso : Effect.succeed(input.createdAt),\n      }).pipe(\n        Effect.map(({ eventId, createdAt }) => ({\n          eventId,\n          provider: PROVIDER,\n          threadId: input.threadId,\n          createdAt,\n          ...(input.turnId ? { turnId: input.turnId } : {}),\n          ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),\n          ...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}),\n          ...(input.raw !== undefined\n            ? {\n                raw: {\n                  source: \"opencode.sdk.event\" as const,\n                  payload: input.raw,\n                },\n              }\n            : {}),\n        })),\n      );\n\n    // Layer-level finalizer: when the adapter layer shuts down, stop every\n    // session. Each session's `Scope.close` tears down its spawned OpenCode\n    // server (via the `ChildProcessSpawner` finalizer installed in\n    // `startOpenCodeServerProcess`) and interrupts the forked event/exit\n    // fibers. Consumers that can't reason about Effect scopes therefore\n    // cannot leak OpenCode child processes by forgetting to call `stopAll`.\n    yield* Effect.addFinalizer(() =>\n      Effect.gen(function* () {\n        const contexts = [...sessions.values()];\n        sessions.clear();\n        // `ignoreCause` swallows both typed failures (none here) and defects\n        // from throwing scope finalizers so a sibling's death can't interrupt\n        // the remaining cleanups.\n        yield* Effect.forEach(\n          contexts,\n          (context) => Effect.ignoreCause(stopOpenCodeContext(context)),\n          { concurrency: \"unbounded\", discard: true },\n        );\n        // Close the logger AFTER session teardown so any final lifecycle\n        // events emitted during shutdown still get written. `close` flushes\n        // the `Logger.batched` window and closes each per-thread\n        // `RotatingFileSink` handle owned by the logger's internal scope.\n        if (managedNativeEventLogger !== undefined) {\n          yield* managedNativeEventLogger.close();\n        }\n      }).pipe(Effect.ensuring(Queue.shutdown(runtimeEvents))),\n    );\n\n    const emit = (event: ProviderRuntimeEvent) =>\n      Queue.offer(runtimeEvents, event).pipe(Effect.asVoid);\n    const writeNativeEvent = (\n      threadId: ThreadId,\n      event: {\n        readonly observedAt: string;\n        readonly event: Record<string, unknown>;\n      },\n    ) => (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void);\n    const writeNativeEventBestEffort = (\n      threadId: ThreadId,\n      event: {\n        readonly observedAt: string;\n        readonly event: Record<string, unknown>;\n      },\n    ) => writeNativeEvent(threadId, event).pipe(Effect.catchCause(() => Effect.void));\n\n    const emitUnexpectedExit = Effect.fn(\"emitUnexpectedExit\")(function* (\n      context: OpenCodeSessionContext,\n      message: string,\n    ) {\n      // Atomic one-shot: two fibers can race here (the event-pump on stream\n      // failure and the server-exit watcher). `getAndSet` flips the flag in\n      // a single step so the loser observes `true` and returns; a plain\n      // `Ref.get` would let both racers slip past and emit duplicates.\n      if (yield* Ref.getAndSet(context.stopped, true)) {\n        return;\n      }\n      const turnId = context.activeTurnId;\n      sessions.delete(context.session.threadId);\n      // Emit lifecycle events BEFORE tearing down the scope. Both call sites\n      // run this inside a fiber forked via `Effect.forkIn(context.sessionScope)`;\n      // closing that scope triggers the fiber-interrupt finalizer, so any\n      // subsequent yield point would unwind and silently drop these emits.\n      yield* emit({\n        ...(yield* buildEventBase({\n          threadId: context.session.threadId,\n          turnId,\n        })),\n        type: \"runtime.error\",\n        payload: {\n          message,\n          class: \"transport_error\",\n        },\n      }).pipe(Effect.ignore);\n      yield* emit({\n        ...(yield* buildEventBase({\n          threadId: context.session.threadId,\n          turnId,\n        })),\n        type: \"session.exited\",\n        payload: {\n          reason: message,\n          recoverable: false,\n          exitKind: \"error\",\n        },\n      }).pipe(Effect.ignore);\n      // Inline the teardown that `stopOpenCodeContext` would do; we can't\n      // delegate to it because our `getAndSet` above already flipped the\n      // one-shot guard, so the call would no-op.\n      yield* runOpenCodeSdk(\"session.abort\", () =>\n        context.client.session.abort({ sessionID: context.openCodeSessionId }),\n      ).pipe(Effect.ignore({ log: true }));\n      yield* Scope.close(context.sessionScope, Exit.void);\n    });\n\n    /** Emit content.delta and item.completed events for an assistant text part. */\n    const emitAssistantTextDelta = Effect.fn(\"emitAssistantTextDelta\")(function* (\n      context: OpenCodeSessionContext,\n      part: Part,\n      turnId: TurnId | undefined,\n      raw: unknown,\n    ) {\n      const text = textFromPart(part);\n      if (text === undefined) {\n        return;\n      }\n      const previousText = context.emittedTextByPartId.get(part.id);\n      const { latestText, deltaToEmit } = mergeOpenCodeAssistantText(previousText, text);\n      context.emittedTextByPartId.set(part.id, latestText);\n      if (latestText !== text) {\n        context.partById.set(\n          part.id,\n          (part.type === \"text\" || part.type === \"reasoning\"\n            ? { ...part, text: latestText }\n            : part) satisfies Part,\n        );\n      }\n      if (deltaToEmit.length > 0) {\n        yield* emit({\n          ...(yield* buildEventBase({\n            threadId: context.session.threadId,\n            turnId,\n            itemId: part.id,\n            createdAt:\n              (part.type === \"text\" || part.type === \"reasoning\") && part.time !== undefined\n                ? isoFromEpochMs(part.time.start)\n                : undefined,\n            raw,\n          })),\n          type: \"content.delta\",\n          payload: {\n            streamKind: resolveTextStreamKind(part),\n            delta: deltaToEmit,\n          },\n        });\n      }\n\n      if (\n        part.type === \"text\" &&\n        part.time?.end !== undefined &&\n        !context.completedAssistantPartIds.has(part.id)\n      ) {\n        context.completedAssistantPartIds.add(part.id);\n        yield* emit({\n          ...(yield* buildEventBase({\n            threadId: context.session.threadId,\n            turnId,\n            itemId: part.id,\n            createdAt: isoFromEpochMs(part.time.end),\n            raw,\n          })),\n          type: \"item.completed\",\n          payload: {\n            itemType: \"assistant_message\",\n            status: \"completed\",\n            title: \"Assistant message\",\n            ...(latestText.length > 0 ? { detail: latestText } : {}),\n          },\n        });\n      }\n    });\n\n    const handleSubscribedEvent = Effect.fn(\"handleSubscribedEvent\")(function* (\n      context: OpenCodeSessionContext,\n      event: OpenCodeSubscribedEvent,\n    ) {\n      const payloadSessionId = openCodeEventSessionId(event);\n      if (payloadSessionId !== context.openCodeSessionId) {\n        return;\n      }\n\n      const turnId = context.activeTurnId;\n      yield* writeNativeEventBestEffort(context.session.threadId, {\n        observedAt: yield* nowIso,\n        event: {\n          provider: PROVIDER,\n          threadId: context.session.threadId,\n          providerThreadId: context.openCodeSessionId,\n          type: event.type,\n          ...(turnId ? { turnId } : {}),\n          payload: event,\n        },\n      });\n\n      switch (event.type) {\n        case \"session.updated\": {\n          const title = openCodeEventSessionTitle(event);\n          if (title) {\n            yield* emit({\n              ...(yield* buildEventBase({\n                threadId: context.session.threadId,\n                raw: event,\n              })),\n              type: \"thread.metadata.updated\",\n              payload: {\n                name: title,\n                metadata: {\n                  sessionID: context.openCodeSessionId,\n                },\n              },\n            });\n          }\n          break;\n        }\n\n        case \"message.updated\": {\n          context.messageRoleById.set(event.properties.info.id, event.properties.info.role);\n          if (event.properties.info.role === \"assistant\") {\n            for (const part of context.partById.values()) {\n              if (part.messageID !== event.properties.info.id) {\n                continue;\n              }\n              yield* emitAssistantTextDelta(context, part, turnId, event);\n            }\n          }\n          break;\n        }\n\n        case \"message.removed\": {\n          context.messageRoleById.delete(event.properties.messageID);\n          break;\n        }\n\n        case \"message.part.delta\": {\n          const existingPart = context.partById.get(event.properties.partID);\n          if (!existingPart) {\n            break;\n          }\n          const role = messageRoleForPart(context, existingPart);\n          if (role !== \"assistant\") {\n            break;\n          }\n          const streamKind = resolveTextStreamKind(existingPart);\n          const delta = event.properties.delta;\n          if (delta.length === 0) {\n            break;\n          }\n          const previousText =\n            context.emittedTextByPartId.get(event.properties.partID) ??\n            textFromPart(existingPart) ??\n            \"\";\n          const { nextText, deltaToEmit } = appendOpenCodeAssistantTextDelta(previousText, delta);\n          if (deltaToEmit.length === 0) {\n            break;\n          }\n          context.emittedTextByPartId.set(event.properties.partID, nextText);\n          if (existingPart.type === \"text\" || existingPart.type === \"reasoning\") {\n            context.partById.set(event.properties.partID, {\n              ...existingPart,\n              text: nextText,\n            });\n          }\n          yield* emit({\n            ...(yield* buildEventBase({\n              threadId: context.session.threadId,\n              turnId,\n              itemId: event.properties.partID,\n              raw: event,\n            })),\n            type: \"content.delta\",\n            payload: {\n              streamKind,\n              delta: deltaToEmit,\n            },\n          });\n          break;\n        }\n\n        case \"message.part.updated\": {\n          const part = event.properties.part;\n          context.partById.set(part.id, part);\n          const messageRole = messageRoleForPart(context, part);\n\n          if (messageRole === \"assistant\") {\n            yield* emitAssistantTextDelta(context, part, turnId, event);\n          }\n\n          if (part.type === \"tool\") {\n            const itemType = toToolLifecycleItemType(part.tool);\n            const title =\n              part.state.status === \"running\" ? (part.state.title ?? part.tool) : part.tool;\n            const detail = detailFromToolPart(part);\n            const payload = {\n              itemType,\n              ...(part.state.status === \"error\"\n                ? { status: \"failed\" as const }\n                : part.state.status === \"completed\"\n                  ? { status: \"completed\" as const }\n                  : { status: \"inProgress\" as const }),\n              ...(title ? { title } : {}),\n              ...(detail ? { detail } : {}),\n              data: {\n                tool: part.tool,\n                state: part.state,\n              },\n            };\n            const runtimeEvent: ProviderRuntimeEvent = {\n              ...(yield* buildEventBase({\n                threadId: context.session.threadId,\n                turnId,\n                itemId: part.callID,\n                createdAt: toolStateCreatedAt(part),\n                raw: event,\n              })),\n              type:\n                part.state.status === \"pending\"\n                  ? \"item.started\"\n                  : part.state.status === \"completed\" || part.state.status === \"error\"\n                    ? \"item.completed\"\n                    : \"item.updated\",\n              payload,\n            };\n            appendTurnItem(context, turnId, part);\n            yield* emit(runtimeEvent);\n          }\n          break;\n        }\n\n        case \"permission.asked\": {\n          context.pendingPermissions.set(event.properties.id, event.properties);\n          yield* emit({\n            ...(yield* buildEventBase({\n              threadId: context.session.threadId,\n              turnId,\n              requestId: event.properties.id,\n              raw: event,\n            })),\n            type: \"request.opened\",\n            payload: {\n              requestType: mapPermissionToRequestType(event.properties.permission),\n              detail:\n                event.properties.patterns.length > 0\n                  ? event.properties.patterns.join(\"\\n\")\n                  : event.properties.permission,\n              args: event.properties.metadata,\n            },\n          });\n          break;\n        }\n\n        case \"permission.replied\": {\n          context.pendingPermissions.delete(event.properties.requestID);\n          yield* emit({\n            ...(yield* buildEventBase({\n              threadId: context.session.threadId,\n              turnId,\n              requestId: event.properties.requestID,\n              raw: event,\n            })),\n            type: \"request.resolved\",\n            payload: {\n              requestType: \"unknown\",\n              decision: mapPermissionDecision(event.properties.reply),\n            },\n          });\n          break;\n        }\n\n        case \"question.asked\": {\n          context.pendingQuestions.set(event.properties.id, event.properties);\n          yield* emit({\n            ...(yield* buildEventBase({\n              threadId: context.session.threadId,\n              turnId,\n              requestId: event.properties.id,\n              raw: event,\n            })),\n            type: \"user-input.requested\",\n            payload: {\n              questions: normalizeQuestionRequest(event.properties),\n            },\n          });\n          break;\n        }\n\n        case \"question.replied\": {\n          const request = context.pendingQuestions.get(event.properties.requestID);\n          context.pendingQuestions.delete(event.properties.requestID);\n          const answers = Object.fromEntries(\n            (request?.questions ?? []).map((question, index) => [\n              openCodeQuestionId(index, question),\n              event.properties.answers[index]?.join(\", \") ?? \"\",\n            ]),\n          );\n          yield* emit({\n            ...(yield* buildEventBase({\n              threadId: context.session.threadId,\n              turnId,\n              requestId: event.properties.requestID,\n              raw: event,\n            })),\n            type: \"user-input.resolved\",\n            payload: { answers },\n          });\n          break;\n        }\n\n        case \"question.rejected\": {\n          context.pendingQuestions.delete(event.properties.requestID);\n          yield* emit({\n            ...(yield* buildEventBase({\n              threadId: context.session.threadId,\n              turnId,\n              requestId: event.properties.requestID,\n              raw: event,\n            })),\n            type: \"user-input.resolved\",\n            payload: { answers: {} },\n          });\n          break;\n        }\n\n        case \"session.status\": {\n          if (event.properties.status.type === \"busy\") {\n            yield* updateProviderSession(context, {\n              status: \"running\",\n              activeTurnId: turnId,\n            });\n          }\n\n          if (event.properties.status.type === \"retry\") {\n            yield* emit({\n              ...(yield* buildEventBase({\n                threadId: context.session.threadId,\n                turnId,\n                raw: event,\n              })),\n              type: \"runtime.warning\",\n              payload: {\n                message: event.properties.status.message,\n                detail: event.properties.status,\n              },\n            });\n            break;\n          }\n\n          if (event.properties.status.type === \"idle\" && turnId) {\n            context.activeTurnId = undefined;\n            yield* updateProviderSession(context, { status: \"ready\" }, { clearActiveTurnId: true });\n            yield* emit({\n              ...(yield* buildEventBase({\n                threadId: context.session.threadId,\n                turnId,\n                raw: event,\n              })),\n              type: \"turn.completed\",\n              payload: {\n                state: \"completed\",\n              },\n            });\n          }\n          break;\n        }\n\n        case \"session.error\": {\n          const message = sessionErrorMessage(event.properties.error);\n          const activeTurnId = context.activeTurnId;\n          context.activeTurnId = undefined;\n          yield* updateProviderSession(\n            context,\n            {\n              status: \"error\",\n              lastError: message,\n            },\n            { clearActiveTurnId: true },\n          );\n          if (activeTurnId) {\n            yield* emit({\n              ...(yield* buildEventBase({\n                threadId: context.session.threadId,\n                turnId: activeTurnId,\n                raw: event,\n              })),\n              type: \"turn.completed\",\n              payload: {\n                state: \"failed\",\n                errorMessage: message,\n              },\n            });\n          }\n          yield* emit({\n            ...(yield* buildEventBase({\n              threadId: context.session.threadId,\n              raw: event,\n            })),\n            type: \"runtime.error\",\n            payload: {\n              message,\n              class: \"provider_error\",\n              detail: event.properties.error,\n            },\n          });\n          break;\n        }\n\n        default:\n          break;\n      }\n    });\n\n    const startEventPump = Effect.fn(\"startEventPump\")(function* (context: OpenCodeSessionContext) {\n      // One AbortController per session scope. The finalizer fires when\n      // the scope closes (explicit stop, unexpected exit, or layer\n      // shutdown) and cancels the in-flight `event.subscribe` fetch so\n      // the async iterable unwinds cleanly.\n      const eventsAbortController = new AbortController();\n      yield* Scope.addFinalizer(\n        context.sessionScope,\n        Effect.sync(() => eventsAbortController.abort()),\n      );\n\n      // Fibers forked into `context.sessionScope` are interrupted\n      // automatically when the scope closes — no bookkeeping required.\n      yield* Effect.flatMap(\n        runOpenCodeSdk(\"event.subscribe\", () =>\n          context.client.event.subscribe(undefined, {\n            signal: eventsAbortController.signal,\n          }),\n        ),\n        (subscription) =>\n          Stream.fromAsyncIterable(\n            subscription.stream,\n            (cause) =>\n              new OpenCodeRuntimeError({\n                operation: \"event.subscribe\",\n                detail: openCodeRuntimeErrorDetail(cause),\n                cause,\n              }),\n          ).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))),\n      ).pipe(\n        Effect.exit,\n        Effect.flatMap((exit) =>\n          Effect.gen(function* () {\n            // Expected paths: caller aborted the fetch or the session\n            // has already been marked stopped. Treat as a clean exit.\n            if (eventsAbortController.signal.aborted || (yield* Ref.get(context.stopped))) {\n              return;\n            }\n            if (Exit.isFailure(exit)) {\n              yield* emitUnexpectedExit(\n                context,\n                openCodeRuntimeErrorDetail(Cause.squash(exit.cause)),\n              );\n            }\n          }),\n        ),\n        Effect.forkIn(context.sessionScope),\n      );\n\n      if (!context.server.external && context.server.exitCode !== null) {\n        yield* context.server.exitCode.pipe(\n          Effect.flatMap((code) =>\n            Effect.gen(function* () {\n              if (yield* Ref.get(context.stopped)) {\n                return;\n              }\n              yield* emitUnexpectedExit(context, `OpenCode server exited unexpectedly (${code}).`);\n            }),\n          ),\n          Effect.forkIn(context.sessionScope),\n        );\n      }\n    });\n\n    const startSession: OpenCodeAdapterShape[\"startSession\"] = Effect.fn(\"startSession\")(\n      function* (input) {\n        const binaryPath = openCodeSettings.binaryPath;\n        const serverUrl = openCodeSettings.serverUrl;\n        const serverPassword = openCodeSettings.serverPassword;\n        const directory = input.cwd ?? serverConfig.cwd;\n        const resumeSessionId = parseOpenCodeResume(input.resumeCursor)?.sessionId;\n        const existing = sessions.get(input.threadId);\n        if (existing) {\n          yield* stopOpenCodeContext(existing);\n          sessions.delete(input.threadId);\n        }\n\n        const started = yield* Effect.gen(function* () {\n          const sessionScope = yield* Scope.make();\n          const startedExit = yield* Effect.exit(\n            Effect.gen(function* () {\n              // The runtime binds the server's lifetime to the Scope.Scope\n              // we provide below — closing `sessionScope` kills the child\n              // process automatically. No manual `server.close()` needed.\n              const server = yield* openCodeRuntime.connectToOpenCodeServer({\n                binaryPath,\n                serverUrl,\n                ...(options?.environment ? { environment: options.environment } : {}),\n              });\n              const client = openCodeRuntime.createOpenCodeSdkClient({\n                baseUrl: server.url,\n                directory,\n                ...(server.external && serverPassword ? { serverPassword } : {}),\n              });\n              const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);\n              if (mcpSession && !server.external) {\n                yield* runOpenCodeSdk(\"mcp.add\", () =>\n                  client.mcp.add({\n                    name: \"synaptic-code\",\n                    config: {\n                      type: \"remote\",\n                      url: mcpSession.endpoint,\n                      headers: {\n                        Authorization: mcpSession.authorizationHeader,\n                      },\n                      oauth: false,\n                    },\n                  }),\n                );\n              }\n              // Resume: re-adopt the session named by the durable cursor —\n              // OpenCode scopes history by session id. The probe recovers only\n              // a confirmed not-found (start fresh); transport/auth/server\n              // errors propagate instead of masking as a new empty session.\n              const resolved = yield* Effect.gen(function* () {\n                const adopted = resumeSessionId\n                  ? yield* runOpenCodeSdk(\"session.get\", () =>\n                      client.session.get({ sessionID: resumeSessionId }),\n                    ).pipe(\n                      Effect.map((response) => response.data),\n                      Effect.catchIf(\n                        (cause) => isOpenCodeNotFound(cause),\n                        () => Effect.void,\n                      ),\n                    )\n                  : undefined;\n\n                // Reuse in place only when the session still matches the\n                // requested cwd; on a cwd change it is forked below instead.\n                const reusable =\n                  adopted &&\n                  (!adopted.directory || (yield* sameDirectory(adopted.directory, directory)))\n                    ? adopted\n                    : undefined;\n\n                if (reusable) {\n                  // Resume skips `session.create`, so re-assert the ruleset —\n                  // a runtime-mode change would otherwise leave the session on\n                  // its original permissions.\n                  yield* runOpenCodeSdk(\"session.update\", () =>\n                    client.session.update({\n                      sessionID: reusable.id,\n                      permission: buildOpenCodePermissionRules(input.runtimeMode),\n                    }),\n                  );\n                  return { openCodeSession: reusable, created: false };\n                }\n\n                // The session lives under a different cwd (e.g. the thread\n                // moved into a git worktree). Fork it into the requested\n                // directory instead of minting an empty one — the fork carries\n                // the full history, so the follow-up keeps its context (#3604).\n                if (adopted) {\n                  yield* Effect.logInfo(\n                    `OpenCode session '${adopted.id}' was created under a different working directory; forking into '${directory}' to preserve conversation history.`,\n                  );\n                  const forkedSession = yield* runOpenCodeSdk(\"session.fork\", () =>\n                    client.session.fork({ sessionID: adopted.id, directory }),\n                  );\n                  const forked = forkedSession.data;\n                  if (!forked) {\n                    return yield* new OpenCodeRuntimeError({\n                      operation: \"session.fork\",\n                      detail: \"OpenCode session.fork returned no session payload.\",\n                    });\n                  }\n                  yield* runOpenCodeSdk(\"session.update\", () =>\n                    client.session.update({\n                      sessionID: forked.id,\n                      permission: buildOpenCodePermissionRules(input.runtimeMode),\n                    }),\n                  );\n                  return { openCodeSession: forked, created: true };\n                }\n\n                if (resumeSessionId) {\n                  yield* Effect.logWarning(\n                    `OpenCode session '${resumeSessionId}' no longer exists; starting a fresh session.`,\n                  );\n                }\n                const createdSession = yield* runOpenCodeSdk(\"session.create\", () =>\n                  client.session.create({\n                    permission: buildOpenCodePermissionRules(input.runtimeMode),\n                  }),\n                );\n                if (!createdSession.data) {\n                  return yield* new OpenCodeRuntimeError({\n                    operation: \"session.create\",\n                    detail: \"OpenCode session.create returned no session payload.\",\n                  });\n                }\n                return { openCodeSession: createdSession.data, created: true };\n              });\n\n              return {\n                sessionScope,\n                server,\n                client,\n                openCodeSession: resolved.openCodeSession,\n                created: resolved.created,\n              };\n            }).pipe(Effect.provideService(Scope.Scope, sessionScope)),\n          );\n          if (Exit.isFailure(startedExit)) {\n            yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore);\n            return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause));\n          }\n          return startedExit.value;\n        });\n\n        // Guard against a concurrent startSession call that may have raced\n        // and already inserted a session while we were awaiting async work.\n        const raceWinner = sessions.get(input.threadId);\n        if (raceWinner) {\n          // Another call won the race — clean up. Only abort the remote\n          // session if we created it here; a resumed one is shared upstream\n          // state the winner is now using.\n          if (started.created) {\n            yield* runOpenCodeSdk(\"session.abort\", () =>\n              started.client.session.abort({\n                sessionID: started.openCodeSession.id,\n              }),\n            ).pipe(Effect.ignore);\n          }\n          yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore);\n          return raceWinner.session;\n        }\n\n        const createdAt = yield* nowIso;\n        const session: ProviderSession = {\n          provider: PROVIDER,\n          providerInstanceId: boundInstanceId,\n          status: \"ready\",\n          runtimeMode: input.runtimeMode,\n          cwd: directory,\n          ...(input.modelSelection ? { model: input.modelSelection.model } : {}),\n          threadId: input.threadId,\n          // ProviderService persists this cursor and feeds it back into\n          // `startSession` after the in-memory session is lost (reaper /\n          // restart), so follow-ups continue the same conversation (#3604).\n          resumeCursor: {\n            schemaVersion: OPENCODE_RESUME_VERSION,\n            sessionId: started.openCodeSession.id,\n          },\n          createdAt,\n          updatedAt: createdAt,\n        };\n\n        const context: OpenCodeSessionContext = {\n          session,\n          client: started.client,\n          server: started.server,\n          directory,\n          openCodeSessionId: started.openCodeSession.id,\n          pendingPermissions: new Map(),\n          pendingQuestions: new Map(),\n          partById: new Map(),\n          emittedTextByPartId: new Map(),\n          messageRoleById: new Map(),\n          completedAssistantPartIds: new Set(),\n          turns: [],\n          activeTurnId: undefined,\n          activeAgent: undefined,\n          activeVariant: undefined,\n          stopped: yield* Ref.make(false),\n          sessionScope: started.sessionScope,\n        };\n        sessions.set(input.threadId, context);\n        yield* startEventPump(context);\n\n        yield* emit({\n          ...(yield* buildEventBase({ threadId: input.threadId })),\n          type: \"session.started\",\n          payload: {\n            message: \"OpenCode session started\",\n          },\n        });\n        yield* emit({\n          ...(yield* buildEventBase({ threadId: input.threadId })),\n          type: \"thread.started\",\n          payload: {\n            providerThreadId: started.openCodeSession.id,\n          },\n        });\n\n        return session;\n      },\n    );\n\n    const sendTurn: OpenCodeAdapterShape[\"sendTurn\"] = Effect.fn(\"sendTurn\")(function* (input) {\n      const context = yield* ensureSessionContext(sessions, input.threadId);\n      // A sendTurn while a turn is active is a steer: OpenCode queues the\n      // prompt into the busy session and the work continues as one turn, so\n      // the active turn id is reused instead of opening a new turn.\n      const steeringTurnId = context.activeTurnId;\n      const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);\n      const modelSelection =\n        input.modelSelection ??\n        (context.session.model\n          ? { instanceId: boundInstanceId, model: context.session.model }\n          : undefined);\n      if (modelSelection !== undefined && modelSelection.instanceId !== boundInstanceId) {\n        return yield* new ProviderAdapterValidationError({\n          provider: PROVIDER,\n          operation: \"sendTurn\",\n          issue: `OpenCode model selection is bound to instance '${modelSelection?.instanceId}', expected '${boundInstanceId}'.`,\n        });\n      }\n      const parsedModel = parseOpenCodeModelSlug(modelSelection?.model);\n      if (!parsedModel) {\n        return yield* new ProviderAdapterValidationError({\n          provider: PROVIDER,\n          operation: \"sendTurn\",\n          issue: \"OpenCode model selection must use the 'provider/model' format.\",\n        });\n      }\n\n      const text = input.input?.trim();\n      const fileParts = toOpenCodeFileParts({\n        attachments: input.attachments,\n        resolveAttachmentPath: (attachment) =>\n          resolveAttachmentPath({\n            attachmentsDir: serverConfig.attachmentsDir,\n            attachment,\n          }),\n      });\n      if ((!text || text.length === 0) && fileParts.length === 0) {\n        return yield* new ProviderAdapterValidationError({\n          provider: PROVIDER,\n          operation: \"sendTurn\",\n          issue: \"OpenCode turns require text input or at least one attachment.\",\n        });\n      }\n\n      const agent = getModelSelectionStringOptionValue(modelSelection, \"agent\");\n      const variant = getModelSelectionStringOptionValue(modelSelection, \"variant\");\n\n      context.activeTurnId = turnId;\n      context.activeAgent = agent ?? (input.interactionMode === \"plan\" ? \"plan\" : undefined);\n      context.activeVariant = variant;\n      yield* updateProviderSession(\n        context,\n        {\n          status: \"running\",\n          activeTurnId: turnId,\n          model: modelSelection?.model ?? context.session.model,\n        },\n        { clearLastError: true },\n      );\n\n      if (steeringTurnId === undefined) {\n        yield* emit({\n          ...(yield* buildEventBase({ threadId: input.threadId, turnId })),\n          type: \"turn.started\",\n          payload: {\n            model: modelSelection?.model ?? context.session.model,\n            ...(variant ? { effort: variant } : {}),\n          },\n        });\n      }\n\n      yield* runOpenCodeSdk(\"session.promptAsync\", () =>\n        context.client.session.promptAsync({\n          sessionID: context.openCodeSessionId,\n          model: parsedModel,\n          ...(context.activeAgent ? { agent: context.activeAgent } : {}),\n          ...(context.activeVariant ? { variant: context.activeVariant } : {}),\n          parts: [...(text ? [{ type: \"text\" as const, text }] : []), ...fileParts],\n        }),\n      ).pipe(\n        Effect.mapError(toRequestError),\n        // On failure of a fresh turn: clear active-turn state, flip the\n        // session back to ready with lastError set, emit turn.aborted, then\n        // let the typed error propagate. We don't need to rebuild the error\n        // here — `toRequestError` already produced the right shape. A failed\n        // steer leaves the still-running original turn untouched.\n        Effect.tapError((requestError) =>\n          steeringTurnId !== undefined\n            ? Effect.void\n            : Effect.gen(function* () {\n                context.activeTurnId = undefined;\n                context.activeAgent = undefined;\n                context.activeVariant = undefined;\n                yield* updateProviderSession(\n                  context,\n                  {\n                    status: \"ready\",\n                    model: modelSelection?.model ?? context.session.model,\n                    lastError: requestError.detail,\n                  },\n                  { clearActiveTurnId: true },\n                );\n                yield* emit({\n                  ...(yield* buildEventBase({\n                    threadId: input.threadId,\n                    turnId,\n                  })),\n                  type: \"turn.aborted\",\n                  payload: {\n                    reason: requestError.detail,\n                  },\n                });\n              }),\n        ),\n      );\n\n      return {\n        threadId: input.threadId,\n        turnId,\n        // Re-surface the durable cursor on every turn so the persisted binding\n        // is refreshed alongside last-seen/runtime state (mirrors Grok/Codex).\n        ...(context.session.resumeCursor !== undefined\n          ? { resumeCursor: context.session.resumeCursor }\n          : {}),\n      };\n    });\n\n    const interruptTurn: OpenCodeAdapterShape[\"interruptTurn\"] = Effect.fn(\"interruptTurn\")(\n      function* (threadId, turnId) {\n        const context = yield* ensureSessionContext(sessions, threadId);\n        yield* runOpenCodeSdk(\"session.abort\", () =>\n          context.client.session.abort({ sessionID: context.openCodeSessionId }),\n        ).pipe(Effect.mapError(toRequestError));\n        if (turnId ?? context.activeTurnId) {\n          yield* emit({\n            ...(yield* buildEventBase({\n              threadId,\n              turnId: turnId ?? context.activeTurnId,\n            })),\n            type: \"turn.aborted\",\n            payload: {\n              reason: \"Interrupted by user.\",\n            },\n          });\n        }\n      },\n    );\n\n    const respondToRequest: OpenCodeAdapterShape[\"respondToRequest\"] = Effect.fn(\n      \"respondToRequest\",\n    )(function* (threadId, requestId, decision) {\n      const context = yield* ensureSessionContext(sessions, threadId);\n      if (!context.pendingPermissions.has(requestId)) {\n        return yield* new ProviderAdapterRequestError({\n          provider: PROVIDER,\n          method: \"permission.reply\",\n          detail: `Unknown pending permission request: ${requestId}`,\n        });\n      }\n\n      yield* runOpenCodeSdk(\"permission.reply\", () =>\n        context.client.permission.reply({\n          requestID: requestId,\n          reply: toOpenCodePermissionReply(decision),\n        }),\n      ).pipe(Effect.mapError(toRequestError));\n    });\n\n    const respondToUserInput: OpenCodeAdapterShape[\"respondToUserInput\"] = Effect.fn(\n      \"respondToUserInput\",\n    )(function* (threadId, requestId, answers) {\n      const context = yield* ensureSessionContext(sessions, threadId);\n      const request = context.pendingQuestions.get(requestId);\n      if (!request) {\n        return yield* new ProviderAdapterRequestError({\n          provider: PROVIDER,\n          method: \"question.reply\",\n          detail: `Unknown pending user-input request: ${requestId}`,\n        });\n      }\n\n      yield* runOpenCodeSdk(\"question.reply\", () =>\n        context.client.question.reply({\n          requestID: requestId,\n          answers: toOpenCodeQuestionAnswers(request, answers),\n        }),\n      ).pipe(Effect.mapError(toRequestError));\n    });\n\n    const stopSession: OpenCodeAdapterShape[\"stopSession\"] = Effect.fn(\"stopSession\")(\n      function* (threadId) {\n        const context = sessions.get(threadId);\n        if (!context) {\n          return yield* new ProviderAdapterSessionNotFoundError({\n            provider: PROVIDER,\n            threadId,\n          });\n        }\n        const stopped = yield* stopOpenCodeContext(context);\n        sessions.delete(threadId);\n        if (!stopped) {\n          return;\n        }\n        yield* emit({\n          ...(yield* buildEventBase({ threadId })),\n          type: \"session.exited\",\n          payload: {\n            reason: \"Session stopped.\",\n            recoverable: false,\n            exitKind: \"graceful\",\n          },\n        });\n      },\n    );\n\n    const listSessions: OpenCodeAdapterShape[\"listSessions\"] = () =>\n      Effect.sync(() => [...sessions.values()].map((context) => context.session));\n\n    const hasSession: OpenCodeAdapterShape[\"hasSession\"] = (threadId) =>\n      Effect.sync(() => sessions.has(threadId));\n\n    const readThread: OpenCodeAdapterShape[\"readThread\"] = Effect.fn(\"readThread\")(\n      function* (threadId) {\n        const context = yield* ensureSessionContext(sessions, threadId);\n        const messages = yield* runOpenCodeSdk(\"session.messages\", () =>\n          context.client.session.messages({\n            sessionID: context.openCodeSessionId,\n          }),\n        ).pipe(Effect.mapError(toRequestError));\n\n        const turns: Array<OpenCodeTurnSnapshot> = [];\n        for (const entry of messages.data ?? []) {\n          if (entry.info.role === \"assistant\") {\n            turns.push({\n              id: TurnId.make(entry.info.id),\n              items: [entry.info, ...entry.parts],\n            });\n          }\n        }\n\n        return {\n          threadId,\n          turns,\n        };\n      },\n    );\n\n    const rollbackThread: OpenCodeAdapterShape[\"rollbackThread\"] = Effect.fn(\"rollbackThread\")(\n      function* (threadId, numTurns) {\n        const context = yield* ensureSessionContext(sessions, threadId);\n        const messages = yield* runOpenCodeSdk(\"session.messages\", () =>\n          context.client.session.messages({\n            sessionID: context.openCodeSessionId,\n          }),\n        ).pipe(Effect.mapError(toRequestError));\n\n        const assistantMessages = (messages.data ?? []).filter(\n          (entry) => entry.info.role === \"assistant\",\n        );\n        const targetIndex = assistantMessages.length - numTurns - 1;\n        const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null;\n        yield* runOpenCodeSdk(\"session.revert\", () =>\n          context.client.session.revert({\n            sessionID: context.openCodeSessionId,\n            ...(target ? { messageID: target.info.id } : {}),\n          }),\n        ).pipe(Effect.mapError(toRequestError));\n\n        return yield* readThread(threadId);\n      },\n    );\n\n    const stopAll: OpenCodeAdapterShape[\"stopAll\"] = () =>\n      Effect.gen(function* () {\n        const contexts = [...sessions.values()];\n        sessions.clear();\n        // `stopOpenCodeContext` is typed as never-failing — SDK aborts are\n        // already `Effect.ignore`'d inside it. `ignoreCause` here also\n        // swallows defects from throwing finalizers so one bad close can't\n        // interrupt the sibling fibers. Same pattern as the layer finalizer.\n        yield* Effect.forEach(\n          contexts,\n          (context) => Effect.ignoreCause(stopOpenCodeContext(context)),\n          { concurrency: \"unbounded\", discard: true },\n        );\n      });\n\n    return {\n      provider: PROVIDER,\n      capabilities: {\n        sessionModelSwitch: \"in-session\",\n      },\n      startSession,\n      sendTurn,\n      interruptTurn,\n      respondToRequest,\n      respondToUserInput,\n      stopSession,\n      listSessions,\n      hasSession,\n      readThread,\n      rollbackThread,\n      stopAll,\n      get streamEvents() {\n        return Stream.fromQueue(runtimeEvents);\n      },\n    } satisfies OpenCodeAdapterShape;\n  });\n}\n","import {\n  type ModelCapabilities,\n  type OpenCodeSettings,\n  type ServerProviderModel,\n} from \"@t3tools/contracts\";\nimport * as Cause from \"effect/Cause\";\nimport * as Data from \"effect/Data\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\n\nimport { createModelCapabilities } from \"@t3tools/shared/model\";\nimport { compareSemverVersions } from \"@t3tools/shared/semver\";\nimport {\n  buildServerProvider,\n  nonEmptyTrimmed,\n  parseGenericCliVersion,\n  providerModelsFromSettings,\n  type ServerProviderDraft,\n} from \"../providerSnapshot.ts\";\nimport {\n  OpenCodeRuntime,\n  openCodeRuntimeErrorDetail,\n  type OpenCodeInventory,\n} from \"../opencodeRuntime.ts\";\nimport type { Agent, ProviderListResponse } from \"@opencode-ai/sdk/v2\";\n\nconst OPENCODE_PRESENTATION = {\n  displayName: \"OpenCode\",\n  showInteractionModeToggle: false,\n} as const;\nconst MINIMUM_OPENCODE_VERSION = \"1.14.19\";\n\nclass OpenCodeProbeError extends Data.TaggedError(\"OpenCodeProbeError\")<{\n  readonly cause: unknown;\n  readonly detail: string;\n}> {}\n\nfunction normalizeProbeMessage(message: string): string | undefined {\n  const trimmed = message.trim();\n  if (trimmed.length === 0) {\n    return undefined;\n  }\n  if (\n    trimmed === \"An error occurred in Effect.tryPromise\" ||\n    trimmed === \"An error occurred in Effect.try\"\n  ) {\n    return undefined;\n  }\n  return trimmed;\n}\n\nfunction normalizedErrorMessage(cause: unknown): string | undefined {\n  if (cause instanceof OpenCodeProbeError) {\n    return normalizeProbeMessage(cause.detail);\n  }\n\n  if (!(cause instanceof Error)) {\n    return undefined;\n  }\n\n  return normalizeProbeMessage(cause.message);\n}\n\nfunction formatOpenCodeProbeError(input: {\n  readonly cause: unknown;\n  readonly isExternalServer: boolean;\n  readonly serverUrl: string;\n}): { readonly installed: boolean; readonly message: string } {\n  const detail = normalizedErrorMessage(input.cause);\n  const lower = detail?.toLowerCase() ?? \"\";\n\n  if (input.isExternalServer) {\n    if (\n      lower.includes(\"401\") ||\n      lower.includes(\"403\") ||\n      lower.includes(\"unauthorized\") ||\n      lower.includes(\"forbidden\")\n    ) {\n      return {\n        installed: true,\n        message: \"OpenCode server rejected authentication. Check the server URL and password.\",\n      };\n    }\n\n    if (\n      lower.includes(\"econnrefused\") ||\n      lower.includes(\"enotfound\") ||\n      lower.includes(\"fetch failed\") ||\n      lower.includes(\"networkerror\") ||\n      lower.includes(\"timed out\") ||\n      lower.includes(\"timeout\") ||\n      lower.includes(\"socket hang up\")\n    ) {\n      return {\n        installed: true,\n        message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,\n      };\n    }\n\n    return {\n      installed: true,\n      message: detail ?? \"Failed to connect to the configured OpenCode server.\",\n    };\n  }\n\n  if (lower.includes(\"enoent\") || lower.includes(\"notfound\")) {\n    return {\n      installed: false,\n      message: \"OpenCode CLI (`opencode`) is not installed or not on PATH.\",\n    };\n  }\n\n  if (lower.includes(\"quarantine\")) {\n    return {\n      installed: true,\n      message:\n        \"macOS is blocking the OpenCode binary (quarantine). Run `xattr -d com.apple.quarantine $(which opencode)` to fix this.\",\n    };\n  }\n\n  if (lower.includes(\"invalid code signature\") || lower.includes(\"corrupted\")) {\n    return {\n      installed: true,\n      message:\n        \"macOS killed the OpenCode process due to an invalid code signature. The binary may be corrupted — try reinstalling OpenCode.\",\n    };\n  }\n\n  return {\n    installed: true,\n    message: detail\n      ? `Failed to execute OpenCode CLI health check: ${detail}`\n      : \"Failed to execute OpenCode CLI health check.\",\n  };\n}\n\nfunction titleCaseSlug(value: string): string {\n  const segments: Array<string> = [];\n  for (const segment of value.split(/[-_/]+/)) {\n    if (segment.length > 0) {\n      segments.push(segment.charAt(0).toUpperCase() + segment.slice(1));\n    }\n  }\n  return segments.join(\" \");\n}\n\nfunction inferDefaultVariant(\n  providerID: string,\n  variants: ReadonlyArray<string>,\n): string | undefined {\n  if (variants.length === 1) {\n    return variants[0];\n  }\n  if (providerID === \"anthropic\" || providerID.startsWith(\"google\")) {\n    return variants.includes(\"high\") ? \"high\" : undefined;\n  }\n  if (providerID === \"openai\" || providerID === \"opencode\") {\n    return variants.includes(\"medium\") ? \"medium\" : variants.includes(\"high\") ? \"high\" : undefined;\n  }\n  return undefined;\n}\n\nfunction inferDefaultAgent(agents: ReadonlyArray<Agent>): string | undefined {\n  return agents.find((agent) => agent.name === \"build\")?.name ?? agents[0]?.name ?? undefined;\n}\n\nconst DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({\n  optionDescriptors: [],\n});\n\nfunction openCodeCapabilitiesForModel(input: {\n  readonly providerID: string;\n  readonly model: ProviderListResponse[\"all\"][number][\"models\"][string];\n  readonly agents: ReadonlyArray<Agent>;\n}): ModelCapabilities {\n  const variantValues = Object.keys(input.model.variants ?? {});\n  const defaultVariant = inferDefaultVariant(input.providerID, variantValues);\n  const variantOptions = variantValues.map((value) =>\n    defaultVariant === value\n      ? { id: value, label: titleCaseSlug(value), isDefault: true as const }\n      : { id: value, label: titleCaseSlug(value) },\n  );\n  const primaryAgents = input.agents.filter(\n    (agent) => !agent.hidden && (agent.mode === \"primary\" || agent.mode === \"all\"),\n  );\n  const defaultAgent = inferDefaultAgent(primaryAgents);\n  const agentOptions = primaryAgents.map((agent) =>\n    defaultAgent === agent.name\n      ? { id: agent.name, label: titleCaseSlug(agent.name), isDefault: true as const }\n      : { id: agent.name, label: titleCaseSlug(agent.name) },\n  );\n  return createModelCapabilities({\n    optionDescriptors: [\n      ...(variantOptions.length > 0\n        ? [\n            {\n              id: \"variant\",\n              label: \"Variant\",\n              type: \"select\" as const,\n              options: variantOptions,\n              ...(defaultVariant ? { currentValue: defaultVariant } : {}),\n            },\n          ]\n        : []),\n      ...(agentOptions.length > 0\n        ? [\n            {\n              id: \"agent\",\n              label: \"Agent\",\n              type: \"select\" as const,\n              options: agentOptions,\n              ...(defaultAgent ? { currentValue: defaultAgent } : {}),\n            },\n          ]\n        : []),\n    ],\n  });\n}\n\nfunction flattenOpenCodeModels(input: OpenCodeInventory): ReadonlyArray<ServerProviderModel> {\n  const connected = new Set(input.providerList.connected);\n  const models: Array<ServerProviderModel> = [];\n\n  for (const provider of input.providerList.all) {\n    if (!connected.has(provider.id)) {\n      continue;\n    }\n\n    for (const model of Object.values(provider.models)) {\n      const name = nonEmptyTrimmed(model.name);\n      if (!name) {\n        continue;\n      }\n\n      const subProvider = nonEmptyTrimmed(provider.name);\n      models.push({\n        slug: `${provider.id}/${model.id}`,\n        name,\n        ...(subProvider ? { subProvider } : {}),\n        isCustom: false,\n        capabilities: openCodeCapabilitiesForModel({\n          providerID: provider.id,\n          model,\n          agents: input.agents,\n        }),\n      });\n    }\n  }\n\n  return models.toSorted((left, right) => left.name.localeCompare(right.name));\n}\n\nexport const makePendingOpenCodeProvider = (\n  openCodeSettings: OpenCodeSettings,\n): Effect.Effect<ServerProviderDraft> =>\n  Effect.gen(function* () {\n    const checkedAt = yield* Effect.map(DateTime.now, DateTime.formatIso);\n    const models = providerModelsFromSettings(\n      [],\n      openCodeSettings.customModels,\n      DEFAULT_OPENCODE_MODEL_CAPABILITIES,\n    );\n\n    if (!openCodeSettings.enabled) {\n      return buildServerProvider({\n        presentation: OPENCODE_PRESENTATION,\n        enabled: false,\n        checkedAt,\n        models,\n        probe: {\n          installed: false,\n          version: null,\n          status: \"warning\",\n          auth: { status: \"unknown\" },\n          message:\n            openCodeSettings.serverUrl.trim().length > 0\n              ? \"OpenCode is disabled in Synaptic Code settings. A server URL is configured.\"\n              : \"OpenCode is disabled in Synaptic Code settings.\",\n        },\n      });\n    }\n\n    return buildServerProvider({\n      presentation: OPENCODE_PRESENTATION,\n      enabled: true,\n      checkedAt,\n      models,\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: \"OpenCode provider status has not been checked in this session yet.\",\n      },\n    });\n  });\n\nexport const checkOpenCodeProviderStatus = Effect.fn(\"checkOpenCodeProviderStatus\")(function* (\n  openCodeSettings: OpenCodeSettings,\n  cwd: string,\n  environment?: NodeJS.ProcessEnv,\n): Effect.fn.Return<ServerProviderDraft, never, OpenCodeRuntime> {\n  const openCodeRuntime = yield* OpenCodeRuntime;\n  const resolvedEnvironment = environment ?? process.env;\n  const checkedAt = DateTime.formatIso(yield* DateTime.now);\n  const customModels = openCodeSettings.customModels;\n  const isExternalServer = openCodeSettings.serverUrl.trim().length > 0;\n\n  const fallback = (cause: unknown, version: string | null = null) => {\n    const failure = formatOpenCodeProbeError({\n      cause,\n      isExternalServer,\n      serverUrl: openCodeSettings.serverUrl,\n    });\n    return buildServerProvider({\n      presentation: OPENCODE_PRESENTATION,\n      enabled: openCodeSettings.enabled,\n      checkedAt,\n      models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),\n      probe: {\n        installed: failure.installed,\n        version,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: failure.message,\n      },\n    });\n  };\n\n  if (!openCodeSettings.enabled) {\n    return buildServerProvider({\n      presentation: OPENCODE_PRESENTATION,\n      enabled: false,\n      checkedAt,\n      models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),\n      probe: {\n        installed: false,\n        version: null,\n        status: \"warning\",\n        auth: { status: \"unknown\" },\n        message: isExternalServer\n          ? \"OpenCode is disabled in Synaptic Code settings. A server URL is configured.\"\n          : \"OpenCode is disabled in Synaptic Code settings.\",\n      },\n    });\n  }\n\n  let version: string | null = null;\n  if (!isExternalServer) {\n    const versionExit = yield* Effect.exit(\n      openCodeRuntime\n        .runOpenCodeCommand({\n          binaryPath: openCodeSettings.binaryPath,\n          args: [\"--version\"],\n          environment: resolvedEnvironment,\n        })\n        .pipe(\n          Effect.mapError(\n            (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),\n          ),\n        ),\n    );\n    if (versionExit._tag === \"Failure\") {\n      return fallback(Cause.squash(versionExit.cause));\n    }\n    version = parseGenericCliVersion(versionExit.value.stdout) ?? null;\n\n    if (!version) {\n      return fallback(\n        new Error(\n          `Unable to determine OpenCode version from \\`opencode --version\\` output. Synaptic Code requires OpenCode v${MINIMUM_OPENCODE_VERSION} or newer.`,\n        ),\n        null,\n      );\n    }\n    if (compareSemverVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {\n      return buildServerProvider({\n        presentation: OPENCODE_PRESENTATION,\n        enabled: openCodeSettings.enabled,\n        checkedAt,\n        models: providerModelsFromSettings([], customModels, DEFAULT_OPENCODE_MODEL_CAPABILITIES),\n        probe: {\n          installed: true,\n          version,\n          status: \"error\",\n          auth: { status: \"unknown\" },\n          message: `OpenCode v${version} is too old. Upgrade to v${MINIMUM_OPENCODE_VERSION} or newer.`,\n        },\n      });\n    }\n  }\n\n  const inventoryExit = yield* Effect.exit(\n    (isExternalServer\n      ? Effect.scoped(\n          Effect.gen(function* () {\n            const server = yield* openCodeRuntime.connectToOpenCodeServer({\n              binaryPath: openCodeSettings.binaryPath,\n              serverUrl: openCodeSettings.serverUrl,\n              environment: resolvedEnvironment,\n            });\n            return yield* openCodeRuntime.loadOpenCodeInventory(\n              openCodeRuntime.createOpenCodeSdkClient({\n                baseUrl: server.url,\n                directory: cwd,\n                ...(openCodeSettings.serverPassword\n                  ? { serverPassword: openCodeSettings.serverPassword }\n                  : {}),\n              }),\n            );\n          }),\n        )\n      : openCodeRuntime.loadInventoryFromCli({\n          binaryPath: openCodeSettings.binaryPath,\n          environment: resolvedEnvironment,\n        })\n    ).pipe(\n      Effect.mapError(\n        (cause) => new OpenCodeProbeError({ cause, detail: openCodeRuntimeErrorDetail(cause) }),\n      ),\n    ),\n  );\n  if (inventoryExit._tag === \"Failure\") {\n    return fallback(Cause.squash(inventoryExit.cause), version);\n  }\n\n  const models = providerModelsFromSettings(\n    flattenOpenCodeModels(inventoryExit.value),\n    customModels,\n    DEFAULT_OPENCODE_MODEL_CAPABILITIES,\n  );\n  const connectedCount = inventoryExit.value.providerList.connected.length;\n  return buildServerProvider({\n    presentation: OPENCODE_PRESENTATION,\n    enabled: true,\n    checkedAt,\n    models,\n    probe: {\n      installed: true,\n      version,\n      status: connectedCount > 0 ? \"ready\" : \"warning\",\n      auth: {\n        status: connectedCount > 0 ? \"authenticated\" : \"unknown\",\n        type: \"opencode\",\n      },\n      message:\n        connectedCount > 0\n          ? `${connectedCount} upstream provider${connectedCount === 1 ? \"\" : \"s\"} connected through ${isExternalServer ? \"the configured OpenCode server\" : \"OpenCode\"}.`\n          : isExternalServer\n            ? \"Connected to the configured OpenCode server, but it did not report any connected upstream providers.\"\n            : \"OpenCode is available, but it did not report any connected upstream providers.\",\n    },\n  });\n});\n","/**\n * OpenCodeDriver — `ProviderDriver` for the OpenCode runtime.\n *\n * Mirrors the Codex / Claude drivers: a plain value whose `create()`\n * bundles `snapshot` / `adapter` / `textGeneration` closures over the\n * per-instance `OpenCodeSettings`.\n *\n * Two instances with different `serverUrl`s therefore talk to independent\n * OpenCode servers; when no `serverUrl` is set, the adapter + text-generation\n * shares spin up their own scoped child processes, and those child\n * processes are released when the registry scope closes.\n *\n * @module provider/Drivers/OpenCodeDriver\n */\nimport { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from \"@t3tools/contracts\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport { HttpClient } from \"effect/unstable/http\";\nimport { ChildProcessSpawner } from \"effect/unstable/process\";\n\nimport { makeOpenCodeTextGeneration } from \"../../textGeneration/OpenCodeTextGeneration.ts\";\nimport * as BackgroundPolicy from \"../../background/BackgroundPolicy.ts\";\nimport { ServerConfig } from \"../../config.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { ProviderDriverError } from \"../Errors.ts\";\nimport { makeOpenCodeAdapter } from \"../Layers/OpenCodeAdapter.ts\";\nimport {\n  checkOpenCodeProviderStatus,\n  makePendingOpenCodeProvider,\n} from \"../Layers/OpenCodeProvider.ts\";\nimport { ProviderEventLoggers } from \"../Layers/ProviderEventLoggers.ts\";\nimport { makeManagedServerProvider } from \"../makeManagedServerProvider.ts\";\nimport { OpenCodeRuntime } from \"../opencodeRuntime.ts\";\nimport {\n  defaultProviderContinuationIdentity,\n  type ProviderDriver,\n  type ProviderInstance,\n} from \"../ProviderDriver.ts\";\nimport type { ServerProviderDraft } from \"../providerSnapshot.ts\";\nimport { mergeProviderInstanceEnvironment } from \"../ProviderInstanceEnvironment.ts\";\nimport {\n  enrichProviderSnapshotWithVersionAdvisory,\n  makePackageManagedProviderMaintenanceResolver,\n  normalizeCommandPath,\n  resolveProviderMaintenanceCapabilitiesEffect,\n} from \"../providerMaintenance.ts\";\nimport {\n  haveProviderSnapshotSettingsChanged,\n  makeProviderSnapshotSettingsSource,\n  type ProviderSnapshotSettings,\n} from \"../providerUpdateSettings.ts\";\nconst decodeOpenCodeSettings = Schema.decodeSync(OpenCodeSettings);\n\nconst DRIVER_KIND = ProviderDriverKind.make(\"opencode\");\n\nfunction isOpenCodeNativeCommandPath(commandPath: string): boolean {\n  const normalized = normalizeCommandPath(commandPath);\n  return (\n    normalized.endsWith(\"/.opencode/bin/opencode\") ||\n    normalized.endsWith(\"/.opencode/bin/opencode.exe\")\n  );\n}\n\nconst UPDATE = makePackageManagedProviderMaintenanceResolver({\n  provider: DRIVER_KIND,\n  npmPackageName: \"opencode-ai\",\n  homebrewFormula: \"anomalyco/tap/opencode\",\n  nativeUpdate: {\n    executable: \"opencode\",\n    args: [\"upgrade\"],\n    lockKey: \"opencode-native\",\n    isCommandPath: isOpenCodeNativeCommandPath,\n  },\n});\n\nexport type OpenCodeDriverEnv =\n  | BackgroundPolicy.BackgroundPolicy\n  | ChildProcessSpawner.ChildProcessSpawner\n  | Crypto.Crypto\n  | FileSystem.FileSystem\n  | HttpClient.HttpClient\n  | OpenCodeRuntime\n  | Path.Path\n  | ProviderEventLoggers\n  | ServerConfig\n  | ServerSettingsService;\n\nconst withInstanceIdentity =\n  (input: {\n    readonly instanceId: ProviderInstance[\"instanceId\"];\n    readonly displayName: string | undefined;\n    readonly accentColor: string | undefined;\n    readonly continuationGroupKey: string;\n  }) =>\n  (snapshot: ServerProviderDraft): ServerProvider => ({\n    ...snapshot,\n    instanceId: input.instanceId,\n    driver: DRIVER_KIND,\n    ...(input.displayName ? { displayName: input.displayName } : {}),\n    ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n    continuation: { groupKey: input.continuationGroupKey },\n  });\n\nexport const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {\n  driverKind: DRIVER_KIND,\n  metadata: {\n    displayName: \"OpenCode\",\n    supportsMultipleInstances: true,\n  },\n  configSchema: OpenCodeSettings,\n  defaultConfig: (): OpenCodeSettings => decodeOpenCodeSettings({}),\n  create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>\n    Effect.gen(function* () {\n      const openCodeRuntime = yield* OpenCodeRuntime;\n      const serverConfig = yield* ServerConfig;\n      const httpClient = yield* HttpClient.HttpClient;\n      const serverSettings = yield* ServerSettingsService;\n      const eventLoggers = yield* ProviderEventLoggers;\n      const processEnv = mergeProviderInstanceEnvironment(environment);\n      const continuationIdentity = defaultProviderContinuationIdentity({\n        driverKind: DRIVER_KIND,\n        instanceId,\n      });\n      const stampIdentity = withInstanceIdentity({\n        instanceId,\n        displayName,\n        accentColor,\n        continuationGroupKey: continuationIdentity.continuationKey,\n      });\n      const effectiveConfig = { ...config, enabled } satisfies OpenCodeSettings;\n      const maintenanceCapabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(UPDATE, {\n        binaryPath: effectiveConfig.binaryPath,\n        env: processEnv,\n      });\n\n      const adapter = yield* makeOpenCodeAdapter(effectiveConfig, {\n        instanceId,\n        environment: processEnv,\n        ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}),\n      });\n      const textGeneration = yield* makeOpenCodeTextGeneration(effectiveConfig, processEnv);\n\n      const checkProvider = checkOpenCodeProviderStatus(\n        effectiveConfig,\n        serverConfig.cwd,\n        processEnv,\n      ).pipe(Effect.map(stampIdentity), Effect.provideService(OpenCodeRuntime, openCodeRuntime));\n\n      const snapshotSettings = makeProviderSnapshotSettingsSource(effectiveConfig, serverSettings);\n      const snapshot = yield* makeManagedServerProvider<ProviderSnapshotSettings<OpenCodeSettings>>(\n        {\n          maintenanceCapabilities,\n          getSettings: snapshotSettings.getSettings,\n          streamSettings: snapshotSettings.streamSettings,\n          haveSettingsChanged: haveProviderSnapshotSettingsChanged,\n          initialSnapshot: (settings) =>\n            makePendingOpenCodeProvider(settings.provider).pipe(Effect.map(stampIdentity)),\n          checkProvider,\n          enrichSnapshot: ({ settings, snapshot, publishSnapshot }) =>\n            enrichProviderSnapshotWithVersionAdvisory(snapshot, maintenanceCapabilities, {\n              enableProviderUpdateChecks: settings.enableProviderUpdateChecks,\n            }).pipe(\n              Effect.provideService(HttpClient.HttpClient, httpClient),\n              Effect.flatMap((enrichedSnapshot) => publishSnapshot(enrichedSnapshot)),\n            ),\n        },\n      ).pipe(\n        Effect.mapError(\n          (cause) =>\n            new ProviderDriverError({\n              driver: DRIVER_KIND,\n              instanceId,\n              detail: `Failed to build OpenCode snapshot: ${cause.message ?? String(cause)}`,\n              cause,\n            }),\n        ),\n      );\n\n      return {\n        instanceId,\n        driverKind: DRIVER_KIND,\n        continuationIdentity,\n        displayName,\n        accentColor,\n        enabled,\n        snapshot,\n        adapter,\n        textGeneration,\n      } satisfies ProviderInstance;\n    }),\n};\n","/**\n * BUILT_IN_DRIVERS — the static set of `ProviderDriver`s this build ships\n * with.\n *\n * Every driver that the server knows how to instantiate from settings is\n * listed here. The `ProviderInstanceRegistry` iterates this array when\n * resolving `providerInstances` entries; anything not in the array surfaces\n * as an `\"unavailable\"` shadow snapshot at runtime (see\n * `buildUnavailableProviderSnapshot`).\n *\n * Adding a new first-party driver means:\n *   1. implement `ProviderDriver` in a sibling `Drivers/<Name>Driver.ts`,\n *   2. add it to this array,\n *   3. ensure the runtime layer satisfies its declared `R`.\n *\n * The aggregated `BuiltInDriversEnv` type is the union of every driver's\n * env requirement — the registry layer's `R` is this type, and the runtime\n * layer (ChildProcessSpawner, FileSystem, Path, ServerConfig,\n * OpenCodeRuntime, …) must satisfy it.\n *\n * @module provider/builtInDrivers\n */\nimport { ClaudeDriver, type ClaudeDriverEnv } from \"./Drivers/ClaudeDriver.ts\";\nimport { CodexDriver, type CodexDriverEnv } from \"./Drivers/CodexDriver.ts\";\nimport { CursorDriver, type CursorDriverEnv } from \"./Drivers/CursorDriver.ts\";\nimport { GrokDriver, type GrokDriverEnv } from \"./Drivers/GrokDriver.ts\";\nimport { OpenCodeDriver, type OpenCodeDriverEnv } from \"./Drivers/OpenCodeDriver.ts\";\nimport type { AnyProviderDriver } from \"./ProviderDriver.ts\";\n\n/**\n * Union of infrastructure services required to construct any built-in\n * driver. The registry layer declares `R = BuiltInDriversEnv`; the runtime\n * layer must provide every service in this union.\n */\nexport type BuiltInDriversEnv =\n  | ClaudeDriverEnv\n  | CodexDriverEnv\n  | CursorDriverEnv\n  | GrokDriverEnv\n  | OpenCodeDriverEnv;\n\n/**\n * Ordered list of built-in drivers. Order matters only for tie-breaking in\n * UI presentation — the registry itself is keyed by `driverKind`, so\n * iteration order has no functional effect on instance lookup.\n */\nexport const BUILT_IN_DRIVERS: ReadonlyArray<AnyProviderDriver<BuiltInDriversEnv>> = [\n  CodexDriver,\n  ClaudeDriver,\n  CursorDriver,\n  GrokDriver,\n  OpenCodeDriver,\n];\n","/**\n * ProviderInstanceRegistryMutator — internal handle used by the hydration\n * layer to reconcile the live registry with a fresh\n * `ProviderInstanceConfigMap`.\n *\n * Kept separate from the public `ProviderInstanceRegistry` service tag so\n * downstream consumers (drivers, reactors, `ProviderService`) can only read\n * from the registry. Only the hydration layer — which watches\n * `ServerSettingsService.streamChanges` and applies diffs — imports this\n * tag.\n *\n * The mutator exposes a single entry point, `reconcile(configMap)`, which:\n *\n *   1. Diffs the incoming map against the live one keyed by instance id.\n *   2. Closes the per-instance `Scope` of every removed or replaced entry\n *      (tearing down adapter processes, refresh fibres, temp files) BEFORE\n *      creating the replacement — `reconcile` guarantees \"at most one live\n *      instance per id\" at all times.\n *   3. Opens a fresh child `Scope` for every added or replaced entry, runs\n *      the driver's `create`, and stores the resulting `ProviderInstance`\n *      plus its scope.\n *   4. Publishes one `void` tick on the registry's `streamChanges` PubSub at\n *      the end of the batch — consumers re-pull `listInstances` /\n *      `listUnavailable`.\n *\n * `reconcile` is idempotent: calling it with an unchanged config map is a\n * no-op (no scope churn, no pubsub emission).\n *\n * @module provider/Services/ProviderInstanceRegistryMutator\n */\nimport type { ProviderInstanceConfigMap } from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\n\nexport interface ProviderInstanceRegistryMutatorShape {\n  /**\n   * Bring the live registry in line with the supplied config map. See\n   * module docs for the add / remove / replace semantics.\n   *\n   * The effect never fails: individual driver `create` failures are\n   * captured as \"unavailable\" shadow snapshots inside the registry, the\n   * same way boot-time failures are handled by\n   * `makeProviderInstanceRegistry`. This keeps settings-watcher loops from\n   * erroring out on a single bad entry.\n   */\n  readonly reconcile: (configMap: ProviderInstanceConfigMap) => Effect.Effect<void>;\n}\n\nexport class ProviderInstanceRegistryMutator extends Context.Service<\n  ProviderInstanceRegistryMutator,\n  ProviderInstanceRegistryMutatorShape\n>()(\"t3/provider/Services/ProviderInstanceRegistryMutator\") {}\n","/**\n * Helpers for synthesizing \"unavailable\" `ServerProvider` snapshots.\n *\n * When `ServerSettings.providerInstances` (or persisted thread/session\n * state) references a driver this build does not ship — typical after a\n * downgrade from a fork or a feature-branch test session — the runtime\n * needs to surface the entry to the UI without crashing. This module\n * produces shadow snapshots that satisfy `ServerProvider`'s wire shape\n * while signalling unavailability.\n *\n * @module unavailableProviderSnapshot\n */\nimport {\n  ProviderDriverKind,\n  type ProviderInstanceId,\n  type ServerProvider,\n} from \"@t3tools/contracts\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\n\nimport { buildServerProvider } from \"./providerSnapshot.ts\";\n\nexport interface UnavailableProviderSnapshotInput {\n  readonly driverKind: ProviderDriverKind | string;\n  readonly instanceId: ProviderInstanceId;\n  readonly displayName?: string | undefined;\n  readonly accentColor?: string | undefined;\n  readonly reason: string;\n  /**\n   * Optional override for `checkedAt`. Defaulted to the current Effect\n   * `DateTime` so callers\n   * (notably tests) don't have to pass it.\n   */\n  readonly checkedAt?: string;\n}\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\n/**\n * Produce a `ServerProvider` snapshot representing a configured instance\n * whose driver the running build does not implement. The result is safe\n * to broadcast over the wire and is structured so the web UI can render\n * a \"missing driver\" affordance without special-casing.\n */\nexport function buildUnavailableProviderSnapshot(\n  input: UnavailableProviderSnapshotInput,\n): Effect.Effect<ServerProvider> {\n  return Effect.gen(function* () {\n    const checkedAt = input.checkedAt ?? (yield* nowIso);\n    const displayName = input.displayName?.trim() || (input.driverKind as string);\n\n    const base = buildServerProvider({\n      presentation: { displayName },\n      enabled: false,\n      checkedAt,\n      models: [],\n      skills: [],\n      probe: {\n        installed: false,\n        version: null,\n        status: \"error\",\n        auth: { status: \"unknown\" },\n        message: input.reason,\n      },\n    });\n\n    return {\n      ...base,\n      instanceId: input.instanceId,\n      ...(input.accentColor ? { accentColor: input.accentColor } : {}),\n      driver:\n        typeof input.driverKind === \"string\"\n          ? ProviderDriverKind.make(input.driverKind)\n          : input.driverKind,\n      availability: \"unavailable\",\n      unavailableReason: input.reason,\n    };\n  });\n}\n","/**\n * ProviderInstanceRegistryLive — runtime implementation of\n * `ProviderInstanceRegistry` plus its sibling mutator.\n *\n * Materializes every entry in a `ProviderInstanceConfigMap`:\n *\n *   - When the entry's `driver` matches a registered driver, the registry\n *     decodes the opaque `config` envelope through `driver.configSchema`\n *     and calls `driver.create()` inside a fresh child scope. The\n *     resulting `ProviderInstance` is stored keyed by instance id,\n *     alongside its scope so the entry can be torn down independently.\n *   - When the entry's `driver` is unknown to this build (fork, rollback,\n *     in-flight PR branch), the registry emits an `\"unavailable\"` shadow\n *     `ServerProvider` snapshot instead of failing. This is what makes\n *     downgrades and fork-hopping safe per the\n *     `forward/backward compatibility invariant` in\n *     `packages/contracts/src/providerInstance.ts`.\n *   - When the entry's config fails schema decode, the registry logs and\n *     emits a shadow snapshot with the schema detail — same bucket as an\n *     unknown driver.\n *\n * Unlike the pre-Slice-D layer, the registry now holds mutable state\n * (`Ref`s + `PubSub`) and exposes an internal mutator\n * (`ProviderInstanceRegistryMutator`) whose `reconcile` method diffs a\n * fresh config map against the live state, tearing down removed instances\n * and building new ones without disturbing unaffected instances.\n *\n * Every live instance runs inside its own child `Scope`. The registry's\n * own scope owns all child scopes via finalizers, so closing the registry\n * tears every instance down in reverse order; closing a single instance\n * (via `reconcile` removing it) leaves the rest untouched.\n *\n * @module provider/Layers/ProviderInstanceRegistryLive\n */\nimport {\n  defaultInstanceIdForDriver,\n  ProviderInstanceId,\n  type ProviderInstanceConfig,\n  type ProviderInstanceConfigMap,\n  type ProviderDriverKind,\n  type ServerProvider,\n} from \"@t3tools/contracts\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { buildUnavailableProviderSnapshot } from \"../unavailableProviderSnapshot.ts\";\nimport {\n  ProviderInstanceRegistry,\n  type ProviderInstanceRegistryShape,\n} from \"../Services/ProviderInstanceRegistry.ts\";\nimport {\n  ProviderInstanceRegistryMutator,\n  type ProviderInstanceRegistryMutatorShape,\n} from \"../Services/ProviderInstanceRegistryMutator.ts\";\nimport type { AnyProviderDriver, ProviderInstance } from \"../ProviderDriver.ts\";\n\n/**\n * Live registry entry: the materialized `ProviderInstance` + the fresh\n * child scope its `create` effect ran in + the original `entry` envelope\n * so `reconcile` can cheaply detect \"no-op\" updates.\n */\ninterface LiveEntry {\n  readonly instance: ProviderInstance;\n  readonly scope: Scope.Closeable;\n  readonly entry: ProviderInstanceConfig;\n}\n\n/**\n * Internal state shared between the public registry service and the\n * mutator service. Both services are thin shells around these refs.\n */\ninterface RegistryState {\n  readonly entries: Ref.Ref<ReadonlyMap<ProviderInstanceId, LiveEntry>>;\n  readonly unavailable: Ref.Ref<ReadonlyMap<ProviderInstanceId, ServerProvider>>;\n  readonly changes: PubSub.PubSub<void>;\n}\n\n/**\n * Structural equality on `ProviderInstanceConfig` envelopes. Used by\n * `reconcile` to skip rebuilds when settings arrive unchanged. Config\n * payloads are opaque `unknown` at the envelope layer; `Equal.equals`\n * falls back to structural equality for plain records, which matches how\n * the schema decode output is constructed.\n */\nconst entryEqual = (a: ProviderInstanceConfig, b: ProviderInstanceConfig): boolean =>\n  Equal.equals(a, b);\n\nconst decodedConfigEnabled = (config: unknown): boolean | undefined => {\n  if (!config || typeof config !== \"object\" || globalThis.Array.isArray(config)) {\n    return undefined;\n  }\n  const enabled = (config as { readonly enabled?: unknown }).enabled;\n  return typeof enabled === \"boolean\" ? enabled : undefined;\n};\n\n/**\n * Build one live entry from a raw config envelope. Returns either a\n * `LiveEntry` plus undefined unavailable shadow, or a shadow snapshot and\n * undefined entry — callers dispatch to the appropriate Ref bucket.\n */\nconst buildEntry = <R>(input: {\n  readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;\n  readonly parentScope: Scope.Scope;\n  readonly instanceId: ProviderInstanceId;\n  readonly rawInstanceId: string;\n  readonly entry: ProviderInstanceConfig;\n}): Effect.Effect<\n  | { readonly kind: \"live\"; readonly live: LiveEntry }\n  | { readonly kind: \"unavailable\"; readonly snapshot: ServerProvider },\n  never,\n  R\n> =>\n  Effect.gen(function* () {\n    const { driversById, parentScope, instanceId, rawInstanceId, entry } = input;\n    const driver = driversById.get(entry.driver);\n    if (!driver) {\n      return {\n        kind: \"unavailable\" as const,\n        snapshot: yield* buildUnavailableProviderSnapshot({\n          driverKind: entry.driver,\n          instanceId,\n          displayName: entry.displayName,\n          accentColor: entry.accentColor,\n          reason: `Driver '${entry.driver}' is not registered in this build.`,\n        }),\n      };\n    }\n\n    const decoder = Schema.decodeUnknownEffect(driver.configSchema);\n    const decodeResult = yield* decoder(entry.config ?? driver.defaultConfig()).pipe(Effect.result);\n    if (decodeResult._tag === \"Failure\") {\n      const issue = decodeResult.failure;\n      const detail = issue.message ?? String(issue);\n      yield* Effect.logError(\"Failed to decode provider instance config\", {\n        instanceId: rawInstanceId,\n        driver: entry.driver,\n        detail,\n      });\n      return {\n        kind: \"unavailable\" as const,\n        snapshot: yield* buildUnavailableProviderSnapshot({\n          driverKind: entry.driver,\n          instanceId,\n          displayName: entry.displayName,\n          accentColor: entry.accentColor,\n          reason: `Invalid config for instance '${rawInstanceId}': ${detail}`,\n        }),\n      };\n    }\n\n    const typedConfig = decodeResult.success;\n    const childScope = yield* Scope.make();\n    // Attach the child scope to the registry's parent scope: if the\n    // registry scope closes, each surviving instance's child scope is\n    // closed through this finalizer. `reconcile` manually closes the\n    // child scope on remove/replace; subsequent close via the parent's\n    // finalizer is a no-op because `Scope.close` is idempotent.\n    yield* Scope.addFinalizer(parentScope, Scope.close(childScope, Exit.void).pipe(Effect.ignore));\n\n    const createResult = yield* driver\n      .create({\n        instanceId,\n        displayName: entry.displayName,\n        accentColor: entry.accentColor,\n        environment: entry.environment ?? [],\n        enabled: entry.enabled ?? decodedConfigEnabled(typedConfig) ?? true,\n        config: typedConfig,\n      })\n      .pipe(Effect.provideService(Scope.Scope, childScope), Effect.result);\n    if (createResult._tag === \"Failure\") {\n      yield* Effect.logError(\"Failed to create provider instance\", {\n        instanceId: rawInstanceId,\n        driver: entry.driver,\n        detail: createResult.failure.detail,\n      });\n      yield* Scope.close(childScope, Exit.void).pipe(Effect.ignore);\n      return {\n        kind: \"unavailable\" as const,\n        snapshot: yield* buildUnavailableProviderSnapshot({\n          driverKind: entry.driver,\n          instanceId,\n          displayName: entry.displayName,\n          accentColor: entry.accentColor,\n          reason: `Driver '${entry.driver}' failed to create instance: ${createResult.failure.detail}`,\n        }),\n      };\n    }\n\n    return {\n      kind: \"live\" as const,\n      live: {\n        instance: createResult.success,\n        scope: childScope,\n        entry,\n      },\n    };\n  });\n\n/**\n * Reconcile-only implementation of the mutator. Exposed to the hydration\n * layer; never called directly by the rest of the server.\n */\nconst makeReconcile = <R>(input: {\n  readonly state: RegistryState;\n  readonly driversById: ReadonlyMap<ProviderDriverKind, AnyProviderDriver<R>>;\n  readonly parentScope: Scope.Scope;\n}): ((configMap: ProviderInstanceConfigMap) => Effect.Effect<void, never, R>) => {\n  const { state, driversById, parentScope } = input;\n  return (configMap: ProviderInstanceConfigMap) =>\n    Effect.gen(function* () {\n      const previousEntries = yield* Ref.get(state.entries);\n      const previousUnavailable = yield* Ref.get(state.unavailable);\n      const nextRaw = Object.entries(configMap);\n      const nextKeys = new Set<ProviderInstanceId>(\n        nextRaw.map(([raw]) => ProviderInstanceId.make(raw)),\n      );\n\n      // 1. Close scopes for instances that disappeared or whose config\n      //    changed. Do this BEFORE creating replacements so ids map 1-to-1\n      //    to live scopes at all times.\n      const removedIds: Array<ProviderInstanceId> = [];\n      const replacedIds = new Set<ProviderInstanceId>();\n      for (const [instanceId, live] of previousEntries) {\n        if (!nextKeys.has(instanceId)) {\n          removedIds.push(instanceId);\n          continue;\n        }\n        const nextEntry = configMap[instanceId];\n        if (nextEntry !== undefined && !entryEqual(live.entry, nextEntry)) {\n          replacedIds.add(instanceId);\n        }\n      }\n      for (const id of [...removedIds, ...replacedIds]) {\n        const live = previousEntries.get(id);\n        if (live) {\n          yield* Scope.close(live.scope, Exit.void).pipe(Effect.ignore);\n        }\n      }\n\n      // 2. Build additions and replacements. Walk `nextRaw` so the final\n      //    entry order follows settings-author order.\n      const builtEntries = new Map<ProviderInstanceId, LiveEntry>();\n      const builtUnavailable = new Map<ProviderInstanceId, ServerProvider>();\n      let orderChanged = false;\n      const previousOrder = [...previousEntries.keys()];\n      const nextOrder: Array<ProviderInstanceId> = [];\n\n      for (const [rawInstanceId, entry] of nextRaw) {\n        const instanceId = ProviderInstanceId.make(rawInstanceId);\n        nextOrder.push(instanceId);\n\n        const existing = previousEntries.get(instanceId);\n        if (existing !== undefined && !replacedIds.has(instanceId)) {\n          // No-op update: keep the existing live entry and scope.\n          builtEntries.set(instanceId, existing);\n          continue;\n        }\n\n        const result = yield* buildEntry({\n          driversById,\n          parentScope,\n          instanceId,\n          rawInstanceId,\n          entry,\n        });\n        if (result.kind === \"live\") {\n          builtEntries.set(instanceId, result.live);\n        } else {\n          builtUnavailable.set(instanceId, result.snapshot);\n        }\n      }\n\n      if (previousOrder.length === nextOrder.length) {\n        for (let i = 0; i < previousOrder.length; i++) {\n          if (previousOrder[i] !== nextOrder[i]) {\n            orderChanged = true;\n            break;\n          }\n        }\n      } else {\n        orderChanged = true;\n      }\n\n      const entriesChanged =\n        orderChanged ||\n        removedIds.length > 0 ||\n        replacedIds.size > 0 ||\n        builtEntries.size !== previousEntries.size;\n      const unavailableChanged =\n        builtUnavailable.size !== previousUnavailable.size ||\n        [...builtUnavailable].some(([id, snapshot]) => {\n          const prev = previousUnavailable.get(id);\n          return prev === undefined || !Equal.equals(prev, snapshot);\n        }) ||\n        [...previousUnavailable].some(([id]) => !builtUnavailable.has(id));\n\n      yield* Ref.set(state.entries, builtEntries);\n      yield* Ref.set(state.unavailable, builtUnavailable);\n\n      if (entriesChanged || unavailableChanged) {\n        yield* PubSub.publish(state.changes, undefined);\n      }\n    });\n};\n\n/**\n * Build the registry's runtime state from a concrete configMap. Returns a\n * record containing:\n *\n *   - `registry`: the read-only `ProviderInstanceRegistryShape` to expose\n *     under `ProviderInstanceRegistry`.\n *   - `mutator`: the `ProviderInstanceRegistryMutatorShape` to expose\n *     under `ProviderInstanceRegistryMutator`.\n *   - `reconcile`: the raw reconcile function, provided for convenience so\n *     boot-time layers can hydrate an initial map before publishing the\n *     services.\n *\n * The scope that this effect runs in owns every per-instance child scope\n * created during `reconcile`. Closing that scope closes every live\n * instance.\n */\nexport const makeProviderInstanceRegistry = <R>(input: {\n  readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;\n  readonly configMap: ProviderInstanceConfigMap;\n}): Effect.Effect<\n  {\n    readonly registry: ProviderInstanceRegistryShape;\n    readonly mutator: ProviderInstanceRegistryMutatorShape;\n  },\n  never,\n  R | Scope.Scope\n> =>\n  Effect.gen(function* () {\n    const driversById = new Map<ProviderDriverKind, AnyProviderDriver<R>>(\n      input.drivers.map((driver) => [driver.driverKind, driver]),\n    );\n\n    // Capture the enclosing scope so per-instance child scopes can be\n    // attached to it at `reconcile` time. Without this, `reconcile`\n    // called later (e.g. from the hydration layer) would attach child\n    // scopes to the *caller's* scope instead of the registry's.\n    const parentScope = yield* Scope.Scope;\n\n    // Capture the driver R context at construction time so `reconcile`\n    // can be invoked later without re-providing driver dependencies.\n    // The service tag's declared `reconcile: Effect<void>` hides R from\n    // consumers — we materialize that here.\n    const driverContext = yield* Effect.context<R>();\n\n    const entries = yield* Ref.make<ReadonlyMap<ProviderInstanceId, LiveEntry>>(new Map());\n    const unavailable = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ServerProvider>>(new Map());\n    const changes = yield* PubSub.unbounded<void>();\n    yield* Effect.addFinalizer(() => PubSub.shutdown(changes));\n\n    const state: RegistryState = { entries, unavailable, changes };\n    const reconcileWithR = makeReconcile({ state, driversById, parentScope });\n    const reconcile: ProviderInstanceRegistryMutatorShape[\"reconcile\"] = (configMap) =>\n      reconcileWithR(configMap).pipe(Effect.provideContext(driverContext));\n\n    // Hydrate the initial configMap synchronously so callers can read\n    // `listInstances` immediately after this effect completes.\n    yield* reconcile(input.configMap);\n\n    const registry: ProviderInstanceRegistryShape = {\n      getInstance: (id) => Ref.get(entries).pipe(Effect.map((map) => map.get(id)?.instance)),\n      listInstances: Ref.get(entries).pipe(\n        Effect.map(\n          (map) =>\n            Array.from(map.values(), (live) => live.instance) as ReadonlyArray<ProviderInstance>,\n        ),\n      ),\n      listUnavailable: Ref.get(unavailable).pipe(\n        Effect.map((map) => Array.from(map.values()) as ReadonlyArray<ServerProvider>),\n      ),\n      // Getters: each read constructs a fresh Stream / Effect descriptor\n      // so multiple consumers don't share a single already-started\n      // Channel or subscription. Matches the pattern `ProviderRegistry`\n      // uses for its own `streamChanges`.\n      get streamChanges() {\n        return Stream.fromPubSub(changes);\n      },\n      // Synchronous subscribe — callers that need to consume changes\n      // from a forked fibre must acquire the subscription in their own\n      // fibre first (via `yield* registry.subscribeChanges`) and only\n      // then fork a consumer loop on `Stream.fromSubscription(...)` /\n      // `PubSub.take(...)`. See the shape docs for the race this avoids.\n      get subscribeChanges() {\n        return PubSub.subscribe(changes);\n      },\n    };\n\n    const mutator: ProviderInstanceRegistryMutatorShape = { reconcile };\n\n    return { registry, mutator };\n  });\n\n/**\n * Assemble a `ProviderInstanceRegistry` Layer bound to a fixed set of\n * drivers and a pre-resolved `ProviderInstanceConfigMap`. Used by tests\n * that want explicit control over the registry's source-of-truth without\n * wiring up the settings watcher.\n *\n * Only exposes the public registry tag — hot-reload consumers should use\n * `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.\n */\nexport const ProviderInstanceRegistryLayer = <R>(input: {\n  readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;\n  readonly configMap: ProviderInstanceConfigMap;\n}): Layer.Layer<ProviderInstanceRegistry, never, R> =>\n  Layer.effect(\n    ProviderInstanceRegistry,\n    makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),\n  ) as Layer.Layer<ProviderInstanceRegistry, never, R>;\n\n/**\n * Layer variant that also exposes the mutator tag. Consumed by\n * `ProviderInstanceRegistryHydrationLive` to reconcile on settings\n * changes. Tests that exercise the mutator directly can pair this Layer\n * with a test-local `ServerSettingsService`.\n */\nexport const ProviderInstanceRegistryMutableLayer = <R>(input: {\n  readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;\n  readonly configMap: ProviderInstanceConfigMap;\n}): Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R> =>\n  Layer.effectContext(\n    makeProviderInstanceRegistry(input).pipe(\n      Effect.map(({ registry, mutator }) =>\n        Context.make(ProviderInstanceRegistry, registry).pipe(\n          Context.add(ProviderInstanceRegistryMutator, mutator),\n        ),\n      ),\n    ),\n  ) as Layer.Layer<ProviderInstanceRegistry | ProviderInstanceRegistryMutator, never, R>;\n\nexport { defaultInstanceIdForDriver };\n","/**\n * ProviderInstanceRegistryHydration — derive a `ProviderInstanceConfigMap`\n * from `ServerSettings` and keep `ProviderInstanceRegistry` in sync with it.\n *\n * The server still reads two shapes:\n *\n *   1. `settings.providerInstances` — the new driver-agnostic map the\n *      registry expects. Keyed by `ProviderInstanceId`, values are\n *      `ProviderInstanceConfig` envelopes.\n *   2. `settings.providers.<kind>` — the legacy single-instance-per-driver\n *      fields (`providers.codex`, `providers.claudeAgent`, …). These are\n *      the source of truth for every deployment that hasn't been migrated\n *      yet to an explicit `providerInstances` entry.\n *\n * This module bridges (2) into (1) and wires the resulting map into a\n * mutable registry. For every built-in driver whose id is not already\n * present in `providerInstances` (keyed on\n * `defaultInstanceIdForDriver(driverKind)` — literally the driver kind as a\n * routing slug), we synthesize an envelope from the legacy field. The\n * registry decodes both flavours through the same `configSchema` and ends\n * up with one uniform `ProviderInstance` per entry.\n *\n * Explicit `providerInstances` entries always win — users can already\n * override the legacy `providers.<kind>` blob by authoring a\n * `providerInstances.codex` entry with a matching driver, and we don't\n * want the synthesized envelope to silently stomp their config.\n *\n * Hot-reload\n * ----------\n * On layer build we:\n *   1. Read the current `ServerSettings` once and use it to seed the\n *      registry's initial state via `ProviderInstanceRegistryMutableLayer`.\n *   2. Fork a daemon fiber (lifetime tied to the layer's scope) that\n *      subscribes to `ServerSettingsService.streamChanges` and calls\n *      `ProviderInstanceRegistryMutator.reconcile` on every emission.\n *\n * Failures inside the watcher are logged and swallowed so a single bad\n * settings emission cannot kill the registry. Unknown drivers and invalid\n * configs already round-trip through the registry's own \"unavailable\"\n * shadow bucket.\n *\n * @module provider/Layers/ProviderInstanceRegistryHydration\n */\nimport {\n  defaultInstanceIdForDriver,\n  type ProviderInstanceConfig,\n  type ProviderInstanceConfigMap,\n  ServerSettings,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Stream from \"effect/Stream\";\n\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\nimport { BUILT_IN_DRIVERS, type BuiltInDriversEnv } from \"../builtInDrivers.ts\";\nimport { ProviderInstanceRegistry } from \"../Services/ProviderInstanceRegistry.ts\";\nimport { ProviderInstanceRegistryMutator } from \"../Services/ProviderInstanceRegistryMutator.ts\";\nimport { ProviderInstanceRegistryMutableLayer } from \"./ProviderInstanceRegistryLive.ts\";\n\n/**\n * Synthesize a `ProviderInstanceConfigMap` from a `ServerSettings` snapshot.\n *\n * Strategy:\n *   1. Copy all explicit `settings.providerInstances` entries verbatim.\n *   2. For each built-in driver whose `defaultInstanceIdForDriver(id)` key\n *      is *not* already in the explicit map, synthesize an entry from the\n *      matching legacy `settings.providers.<kind>` blob.\n *\n * The returned map is the input the registry consumes; pure & exported\n * separately so the hydration logic can be exercised by unit tests\n * without layering.\n */\nexport const deriveProviderInstanceConfigMap = (\n  settings: ServerSettings,\n): ProviderInstanceConfigMap => {\n  const merged: Record<string, ProviderInstanceConfig> = { ...settings.providerInstances };\n\n  for (const driver of BUILT_IN_DRIVERS) {\n    const instanceId = defaultInstanceIdForDriver(driver.driverKind);\n    if (instanceId in merged) {\n      // Explicit `providerInstances` entry for this slot — user-authored\n      // config always wins over the legacy mirror.\n      continue;\n    }\n\n    // Only built-in drivers have a legacy mirror; the registry's\n    // `providers` struct is keyed on the same literal slug as\n    // `driverKind`. Access is dynamic (the driver kind is a branded string),\n    // but it's constrained to `keyof settings.providers` by the union of\n    // built-in driver kinds.\n    const legacyKey = driver.driverKind as keyof ServerSettings[\"providers\"];\n    const legacyConfig = settings.providers[legacyKey];\n    if (legacyConfig === undefined) {\n      continue;\n    }\n\n    merged[instanceId] = {\n      driver: driver.driverKind,\n      config: legacyConfig,\n    };\n  }\n\n  return merged as ProviderInstanceConfigMap;\n};\n\n/**\n * Layer that consumes `ProviderInstanceRegistryMutator` and forks a\n * settings-watcher fiber. The fiber's lifetime is tied to the enclosing\n * layer scope (process lifetime in production), so it is interrupted on\n * shutdown without leaking.\n *\n * Errors inside the watcher are logged and swallowed — the registry's own\n * \"unavailable\" bucket already absorbs unknown drivers and invalid\n * configs, so the only way the watcher could fail is a settings stream\n * tear-down, which logs and exits cleanly.\n */\nconst SettingsWatcherLive = Layer.effectDiscard(\n  Effect.gen(function* () {\n    const mutator = yield* ProviderInstanceRegistryMutator;\n    const serverSettings = yield* ServerSettingsService;\n    yield* serverSettings.streamChanges.pipe(\n      Stream.runForEach((next) =>\n        mutator\n          .reconcile(deriveProviderInstanceConfigMap(next))\n          .pipe(\n            Effect.catchCause((cause) =>\n              Effect.logError(\"ProviderInstanceRegistry reconcile failed\", cause),\n            ),\n          ),\n      ),\n      Effect.forkScoped,\n    );\n  }),\n);\n\n/**\n * Hydrate `ProviderInstanceRegistry` from `ServerSettings` and keep it in\n * sync with subsequent `streamChanges` emissions.\n *\n * The Layer's two halves:\n *   - `ProviderInstanceRegistryMutableLayer` produces the registry +\n *     mutator from the initial config map. Its scope owns every\n *     per-instance child scope created during reconcile.\n *   - `SettingsWatcherLive` consumes the mutator and runs a daemon fiber\n *     in the same scope.\n *\n * Composing via `Layer.provideMerge` makes the watcher's deps available\n * from the mutable layer while still surfacing the registry as an output.\n * The mutator tag is technically also exposed; only this module imports\n * it, so the visibility leak is harmless in practice.\n */\nexport const ProviderInstanceRegistryHydrationLive: Layer.Layer<\n  ProviderInstanceRegistry,\n  never,\n  BuiltInDriversEnv | ServerSettingsService\n> = Layer.unwrap(\n  Effect.gen(function* () {\n    const serverSettings = yield* ServerSettingsService;\n    const initialSettings: ServerSettings | undefined = yield* serverSettings.getSettings.pipe(\n      Effect.orElseSucceed(() => undefined),\n    );\n    const initialConfigMap =\n      initialSettings === undefined\n        ? ({} as ProviderInstanceConfigMap)\n        : deriveProviderInstanceConfigMap(initialSettings);\n\n    const mutableLayer = ProviderInstanceRegistryMutableLayer({\n      drivers: BUILT_IN_DRIVERS,\n      configMap: initialConfigMap,\n    });\n\n    return SettingsWatcherLive.pipe(Layer.provideMerge(mutableLayer));\n  }),\n) as Layer.Layer<ProviderInstanceRegistry, never, BuiltInDriversEnv | ServerSettingsService>;\n","import {\n  PreviewAutomationClickInput,\n  PreviewAutomationError,\n  PreviewAutomationEvaluateInput,\n  PreviewAutomationNavigateInput,\n  PreviewAutomationOpenInput,\n  PreviewAutomationPressInput,\n  PreviewAutomationRecordingArtifact,\n  PreviewAutomationRecordingStatus,\n  PreviewAutomationResizeInput,\n  PreviewAutomationResizeResult,\n  PreviewAutomationScrollInput,\n  PreviewAutomationSetColorSchemeInput,\n  PreviewAutomationSetColorSchemeResult,\n  PreviewAutomationSnapshot,\n  PreviewAutomationStatus,\n  PreviewAutomationTabTargetInput,\n  PreviewAutomationTypeInput,\n  PreviewAutomationWaitForInput,\n} from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport * as McpInvocationContext from \"../../McpInvocationContext.ts\";\nimport * as PreviewAutomationBroker from \"../../PreviewAutomationBroker.ts\";\n\nconst dependencies = [\n  McpInvocationContext.McpInvocationContext,\n  PreviewAutomationBroker.PreviewAutomationBroker,\n];\n\nconst browserTool = <T extends Tool.Any>(tool: T): T =>\n  tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T;\n\nconst safeBrowserTool = <T extends Tool.Any>(tool: T): T =>\n  browserTool(tool).annotate(Tool.Destructive, false) as T;\n\nconst readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>\n  safeBrowserTool(tool).annotate(Tool.Readonly, true).annotate(Tool.Idempotent, true) as T;\n\nexport const PreviewStatusTool = Tool.make(\"preview_status\", {\n  description:\n    \"Report whether a collaborative browser tab is automation-capable, including its URL, title, visibility, loading state, viewport mode, and measured CSS-pixel size. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab.\",\n  parameters: PreviewAutomationTabTargetInput,\n  success: PreviewAutomationStatus,\n  failure: PreviewAutomationError,\n  dependencies,\n})\n  .annotate(Tool.Title, \"Get preview status\")\n  .annotate(Tool.Readonly, true)\n  .annotate(Tool.Destructive, false)\n  .annotate(Tool.Idempotent, true);\n\nexport const PreviewOpenTool = browserTool(\n  Tool.make(\"preview_open\", {\n    description:\n      \"Initialize a collaborative browser tab and open its thread-bound inline preview by default. Set open=false for background-only automation. Pass tabId to reuse a specific existing tab, set reuseExistingTab=false to create another tab, or omit both to use this agent session's current tab.\",\n    parameters: PreviewAutomationOpenInput,\n    success: PreviewAutomationStatus,\n    failure: PreviewAutomationError,\n    dependencies,\n  })\n    .annotate(Tool.Title, \"Open browser preview\")\n    .annotate(Tool.Destructive, false),\n);\n\nexport const PreviewNavigateTool = safeBrowserTool(\n  Tool.make(\"preview_navigate\", {\n    description:\n      \"Navigate a collaborative browser tab. Pass tabId to target a specific tab, plus {url:'https://t3.chat'} for a website or {target:{kind:'environment-port',port:5173}} for a dev server. Exactly one of url or target is required.\",\n    parameters: PreviewAutomationNavigateInput,\n    success: PreviewAutomationStatus,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Navigate browser preview\"),\n);\n\nexport const PreviewResizeTool = safeBrowserTool(\n  Tool.make(\"preview_resize\", {\n    description:\n      \"Resize a collaborative browser tab, optionally selected by tabId. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent.\",\n    parameters: PreviewAutomationResizeInput,\n    success: PreviewAutomationResizeResult,\n    failure: PreviewAutomationError,\n    dependencies,\n  })\n    .annotate(Tool.Title, \"Resize browser viewport\")\n    .annotate(Tool.Idempotent, true),\n);\n\nexport const PreviewSetAppearanceTool = safeBrowserTool(\n  Tool.make(\"preview_set_appearance\", {\n    description:\n      \"Emulate prefers-color-scheme in a collaborative browser tab, optionally selected by tabId. Use {colorScheme:'dark'} or {colorScheme:'light'} to preview the page in that appearance, and {colorScheme:'system'} to clear the override and follow the OS appearance.\",\n    parameters: PreviewAutomationSetColorSchemeInput,\n    success: PreviewAutomationSetColorSchemeResult,\n    failure: PreviewAutomationError,\n    dependencies,\n  })\n    .annotate(Tool.Title, \"Set preview appearance\")\n    .annotate(Tool.Idempotent, true),\n);\n\nexport const PreviewSnapshotTool = readonlyBrowserTool(\n  Tool.make(\"preview_snapshot\", {\n    description:\n      \"Inspect a page before interacting. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab. Returns page state, semantic elements, diagnostics, action history, and a PNG screenshot.\",\n    parameters: PreviewAutomationTabTargetInput,\n    success: PreviewAutomationSnapshot,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Inspect browser page\"),\n);\n\nexport const PreviewClickTool = browserTool(\n  Tool.make(\"preview_click\", {\n    description:\n      \"Click exactly one target in the tab selected by tabId, or this agent session's current tab when omitted. Prefer a Playwright locator; selector accepts legacy CSS; x and y must be supplied together.\",\n    parameters: PreviewAutomationClickInput,\n    success: Schema.Null,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Click preview page\"),\n);\n\nexport const PreviewTypeTool = browserTool(\n  Tool.make(\"preview_type\", {\n    description:\n      \"Insert literal text into one input in the tab selected by tabId, or this agent session's current tab when omitted. Prefer a Playwright locator; set clear=true to replace existing text.\",\n    parameters: PreviewAutomationTypeInput,\n    success: Schema.Null,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Type into preview page\"),\n);\n\nexport const PreviewPressTool = browserTool(\n  Tool.make(\"preview_press\", {\n    description:\n      \"Press one keyboard key in the tab selected by tabId, or this agent session's current tab when omitted. Examples: {key:'Enter'}, {key:'Escape'}, or {key:'a',modifiers:['Meta']}.\",\n    parameters: PreviewAutomationPressInput,\n    success: Schema.Null,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Press key in preview page\"),\n);\n\nexport const PreviewScrollTool = safeBrowserTool(\n  Tool.make(\"preview_scroll\", {\n    description:\n      \"Scroll the tab selected by tabId, or this agent session's current tab when omitted. Positive deltaY scrolls down and positive deltaX scrolls right; a locator/selector targets a container.\",\n    parameters: PreviewAutomationScrollInput,\n    success: Schema.Null,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Scroll preview page\"),\n);\n\nexport const PreviewEvaluateTool = browserTool(\n  Tool.make(\"preview_evaluate\", {\n    description:\n      \"Evaluate JavaScript in the tab selected by tabId, or this agent session's current tab when omitted. Returns a serializable result up to 64 KB; the expression may mutate page state.\",\n    parameters: PreviewAutomationEvaluateInput,\n    success: Schema.Unknown,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Evaluate JavaScript in preview\"),\n);\n\nexport const PreviewWaitForTool = readonlyBrowserTool(\n  Tool.make(\"preview_wait_for\", {\n    description:\n      \"Wait in the tab selected by tabId, or this agent session's current tab when omitted, until all supplied locator, selector, text, and URL conditions match.\",\n    parameters: PreviewAutomationWaitForInput,\n    success: Schema.Null,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Wait for preview page condition\"),\n);\n\nexport const PreviewRecordingStartTool = safeBrowserTool(\n  Tool.make(\"preview_recording_start\", {\n    description:\n      \"Start recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted.\",\n    parameters: PreviewAutomationTabTargetInput,\n    success: PreviewAutomationRecordingStatus,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Start browser recording\"),\n);\n\nexport const PreviewRecordingStopTool = safeBrowserTool(\n  Tool.make(\"preview_recording_stop\", {\n    description:\n      \"Stop recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted, and save it as a local evidence artifact.\",\n    parameters: PreviewAutomationTabTargetInput,\n    success: PreviewAutomationRecordingArtifact,\n    failure: PreviewAutomationError,\n    dependencies,\n  }).annotate(Tool.Title, \"Stop browser recording\"),\n);\n\nexport const PreviewToolkit = Toolkit.make(\n  PreviewStatusTool,\n  PreviewOpenTool,\n  PreviewNavigateTool,\n  PreviewResizeTool,\n  PreviewSetAppearanceTool,\n  PreviewSnapshotTool,\n  PreviewClickTool,\n  PreviewTypeTool,\n  PreviewPressTool,\n  PreviewScrollTool,\n  PreviewEvaluateTool,\n  PreviewWaitForTool,\n  PreviewRecordingStartTool,\n  PreviewRecordingStopTool,\n);\n\nexport const PreviewStandardToolkit = Toolkit.make(\n  PreviewStatusTool,\n  PreviewOpenTool,\n  PreviewNavigateTool,\n  PreviewResizeTool,\n  PreviewSetAppearanceTool,\n  PreviewClickTool,\n  PreviewTypeTool,\n  PreviewPressTool,\n  PreviewScrollTool,\n  PreviewEvaluateTool,\n  PreviewWaitForTool,\n  PreviewRecordingStartTool,\n  PreviewRecordingStopTool,\n);\n\nexport const PreviewSnapshotToolkit = Toolkit.make(PreviewSnapshotTool);\n","import * as Effect from \"effect/Effect\";\nimport type {\n  PreviewAutomationOperation,\n  PreviewAutomationOpenInput,\n  PreviewAutomationRecordingArtifact,\n  PreviewAutomationRecordingStatus,\n  PreviewAutomationResizeResult,\n  PreviewAutomationSetColorSchemeResult,\n  PreviewAutomationSnapshot,\n  PreviewAutomationStatus,\n  PreviewTabId,\n} from \"@t3tools/contracts\";\n\nimport * as McpInvocationContext from \"../../McpInvocationContext.ts\";\nimport * as PreviewAutomationBroker from \"../../PreviewAutomationBroker.ts\";\nimport { PreviewSnapshotToolkit, PreviewStandardToolkit, PreviewToolkit } from \"./tools.ts\";\n\nexport function normalizePreviewOpenInput(\n  input: PreviewAutomationOpenInput,\n): PreviewAutomationOpenInput {\n  const open = input.open ?? input.show ?? true;\n  return {\n    ...input,\n    open,\n    show: open,\n    reuseExistingTab: input.reuseExistingTab ?? true,\n  };\n}\n\nconst invoke = Effect.fn(\"PreviewToolkit.invoke\")(function* <A>(\n  operation: PreviewAutomationOperation,\n  input: unknown,\n  timeoutMs?: number,\n  tabId?: PreviewTabId,\n): Effect.fn.Return<\n  A,\n  import(\"@t3tools/contracts\").PreviewAutomationError,\n  McpInvocationContext.McpInvocationContext | PreviewAutomationBroker.PreviewAutomationBroker\n> {\n  const scope = yield* McpInvocationContext.requireMcpCapability(\"preview\");\n  const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;\n  return yield* broker.invoke<A>({\n    scope,\n    operation,\n    input,\n    ...(timeoutMs === undefined ? {} : { timeoutMs }),\n    ...(tabId === undefined ? {} : { tabId }),\n  });\n});\n\nconst invokeTargeted = <A>(\n  operation: PreviewAutomationOperation,\n  input: {\n    readonly tabId?: PreviewTabId | undefined;\n    readonly [key: string]: unknown;\n  },\n  timeoutMs?: number,\n) => {\n  const { tabId, ...operationInput } = input;\n  return invoke<A>(operation, operationInput, timeoutMs, tabId);\n};\n\nconst handlers = {\n  preview_status: (input) => invokeTargeted<PreviewAutomationStatus>(\"status\", input ?? {}),\n  preview_open: (input) =>\n    invokeTargeted<PreviewAutomationStatus>(\"open\", normalizePreviewOpenInput(input)),\n  preview_navigate: (input) =>\n    invokeTargeted<PreviewAutomationStatus>(\"navigate\", input, input.timeoutMs),\n  preview_resize: (input) =>\n    invokeTargeted<PreviewAutomationResizeResult>(\"resize\", input, input.timeoutMs),\n  preview_set_appearance: (input) =>\n    invokeTargeted<PreviewAutomationSetColorSchemeResult>(\"setColorScheme\", input),\n  preview_snapshot: (input) => invokeTargeted<PreviewAutomationSnapshot>(\"snapshot\", input ?? {}),\n  preview_click: (input) =>\n    invokeTargeted<void>(\"click\", input, input.timeoutMs).pipe(Effect.as(null)),\n  preview_type: (input) =>\n    invokeTargeted<void>(\"type\", input, input.timeoutMs).pipe(Effect.as(null)),\n  preview_press: (input) => invokeTargeted<void>(\"press\", input).pipe(Effect.as(null)),\n  preview_scroll: (input) => invokeTargeted<void>(\"scroll\", input).pipe(Effect.as(null)),\n  preview_evaluate: (input) =>\n    invokeTargeted<unknown>(\"evaluate\", input).pipe(Effect.map((result) => result ?? null)),\n  preview_wait_for: (input) =>\n    invokeTargeted<void>(\"waitFor\", input, input.timeoutMs).pipe(Effect.as(null)),\n  preview_recording_start: (input) =>\n    invokeTargeted<PreviewAutomationRecordingStatus>(\"recordingStart\", input ?? {}),\n  preview_recording_stop: (input) =>\n    invokeTargeted<PreviewAutomationRecordingArtifact>(\"recordingStop\", input ?? {}),\n} satisfies Parameters<typeof PreviewToolkit.toLayer>[0];\n\nconst { preview_snapshot, ...standardHandlers } = handlers;\n\nexport const PreviewStandardToolkitHandlersLive = PreviewStandardToolkit.toLayer(standardHandlers);\n\nexport const PreviewSnapshotToolkitHandlersLive = PreviewSnapshotToolkit.toLayer({\n  preview_snapshot,\n});\n\nexport const PreviewToolkitHandlersLive = PreviewToolkit.toLayer(handlers);\n","import * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Sink from \"effect/Sink\";\nimport * as Stream from \"effect/Stream\";\nimport type * as Types from \"effect/Types\";\nimport { McpProtocol, McpSchema, McpServer, Tool } from \"effect/unstable/ai\";\nimport { HttpRouter, HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\";\n\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport * as McpInvocationContext from \"./McpInvocationContext.ts\";\nimport * as McpSessionRegistry from \"./McpSessionRegistry.ts\";\nimport * as PreviewAutomationBroker from \"./PreviewAutomationBroker.ts\";\nimport {\n  PreviewSnapshotToolkitHandlersLive,\n  PreviewStandardToolkitHandlersLive,\n} from \"./toolkits/preview/handlers.ts\";\nimport {\n  PreviewSnapshotTool,\n  PreviewSnapshotToolkit,\n  PreviewStandardToolkit,\n} from \"./toolkits/preview/tools.ts\";\n\nconst unauthorized = HttpServerResponse.jsonUnsafe(\n  {\n    error: \"invalid_mcp_credential\",\n    message: \"A valid provider-scoped MCP bearer credential is required.\",\n  },\n  {\n    status: 401,\n    headers: {\n      \"cache-control\": \"no-store\",\n      \"www-authenticate\": \"Bearer\",\n    },\n  },\n);\n\ntype AuthenticatedHttpEffect = Effect.Effect<\n  HttpServerResponse.HttpServerResponse,\n  Types.unhandled,\n  McpInvocationContext.McpInvocationContext\n>;\n\ntype McpAuthMiddleware = (\n  httpEffect: AuthenticatedHttpEffect,\n) => Effect.Effect<\n  HttpServerResponse.HttpServerResponse,\n  Types.unhandled,\n  HttpServerRequest.HttpServerRequest\n>;\n\nexport const normalizeMcpHttpResponse = (\n  response: HttpServerResponse.HttpServerResponse,\n): HttpServerResponse.HttpServerResponse => {\n  const bodyIsEmpty =\n    response.body._tag === \"Empty\" ||\n    (response.body._tag === \"Uint8Array\" && response.body.contentLength === 0) ||\n    (response.body._tag === \"Raw\" && response.body.contentLength === 0);\n  return response.status === 200 && bodyIsEmpty\n    ? HttpServerResponse.setStatus(response, 202)\n    : response;\n};\n\nconst makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(\n  Effect.map(\n    (registry): McpAuthMiddleware =>\n      Effect.fn(\"McpHttpServer.authenticateRequest\")(function* (httpEffect) {\n        const request = yield* HttpServerRequest.HttpServerRequest;\n        const authorization = request.headers.authorization;\n        const token =\n          authorization?.startsWith(\"Bearer \") === true\n            ? authorization.slice(\"Bearer \".length).trim()\n            : \"\";\n        const invocation = yield* registry.resolve(token);\n        if (!invocation) {\n          // Without this the only symptom of a dead credential is the agent\n          // quietly losing the whole `synaptic-code` toolkit for the rest of its\n          // session, with nothing on the server to explain why.\n          yield* Effect.logWarning(\"rejected MCP request with an unusable credential\", {\n            reason: token.length === 0 ? \"missing_bearer_token\" : \"unknown_or_expired_token\",\n          });\n          return unauthorized;\n        }\n        return yield* httpEffect.pipe(\n          Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),\n          Effect.map(normalizeMcpHttpResponse),\n        );\n      }),\n  ),\n  Effect.withSpan(\"McpHttpServer.makeAuthMiddleware\"),\n);\n\nconst McpAuthMiddlewareLive = HttpRouter.middleware<{\n  provides: McpInvocationContext.McpInvocationContext;\n}>()(makeMcpAuthMiddleware).layer;\n\nconst previewSnapshotFailure = <E>(cause: Cause.Cause<E>) => {\n  if (Cause.hasInterrupts(cause) || cause.reasons.some(Cause.isDieReason)) {\n    return Effect.failCause(cause).pipe(Effect.orDie);\n  }\n  const failures = cause.reasons.filter(Cause.isFailReason);\n  const firstFailure = failures[0]?.error;\n  const errorTag =\n    typeof firstFailure === \"object\" &&\n    firstFailure !== null &&\n    \"_tag\" in firstFailure &&\n    typeof firstFailure._tag === \"string\"\n      ? firstFailure._tag\n      : \"PreviewSnapshotError\";\n  const result = new McpSchema.CallToolResult({\n    isError: true,\n    structuredContent: {\n      error: {\n        _tag: errorTag,\n        operation: \"snapshot\",\n        failureCount: failures.length,\n      },\n    },\n    content: [{ type: \"text\", text: \"Preview snapshot failed.\" }],\n  });\n  return Effect.logWarning(\"preview snapshot failed\", {\n    operation: \"snapshot\",\n    errorTag,\n    failureCount: failures.length,\n  }).pipe(Effect.as(result));\n};\n\nconst registerPreviewSnapshot = Effect.fn(\"McpHttpServer.registerPreviewSnapshot\")(function* () {\n  const server = yield* McpServer.McpServer;\n  const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;\n  const built = yield* PreviewSnapshotToolkit;\n  const tool = PreviewSnapshotTool;\n  yield* server.addTool({\n    tool: new McpSchema.Tool({\n      name: tool.name,\n      description: Tool.getDescription(tool),\n      inputSchema: Tool.getJsonSchema(tool),\n      annotations: {\n        ...Context.getOption(tool.annotations, Tool.Title).pipe(\n          Option.map((title) => ({ title })),\n          Option.getOrUndefined,\n        ),\n        readOnlyHint: Context.get(tool.annotations, Tool.Readonly),\n        destructiveHint: Context.get(tool.annotations, Tool.Destructive),\n        idempotentHint: Context.get(tool.annotations, Tool.Idempotent),\n        openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),\n      },\n    }),\n    annotations: tool.annotations,\n    handle: (payload) =>\n      Effect.withFiber((fiber) => {\n        const invocation = Context.getUnsafe(\n          fiber.context,\n          McpInvocationContext.McpInvocationContext,\n        );\n        return built.handle(\"preview_snapshot\", payload).pipe(\n          Stream.unwrap,\n          Stream.run(Sink.last()),\n          Effect.flatMap(Effect.fromOption),\n          Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),\n          Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),\n          Effect.matchCauseEffect({\n            onFailure: previewSnapshotFailure,\n            onSuccess: ({ encodedResult }) => {\n              const snapshot = encodedResult as {\n                readonly screenshot: {\n                  readonly mimeType: \"image/png\";\n                  readonly data: string;\n                  readonly width: number;\n                  readonly height: number;\n                };\n                readonly [key: string]: unknown;\n              };\n              const { screenshot, ...page } = snapshot;\n              const metadata = {\n                ...page,\n                screenshot: {\n                  mimeType: screenshot.mimeType,\n                  width: screenshot.width,\n                  height: screenshot.height,\n                },\n              };\n              return Effect.succeed(\n                new McpSchema.CallToolResult({\n                  isError: false,\n                  structuredContent: metadata,\n                  content: [\n                    { type: \"text\", text: JSON.stringify(metadata) },\n                    {\n                      type: \"image\",\n                      data: new Uint8Array(Buffer.from(screenshot.data, \"base64\")),\n                      mimeType: screenshot.mimeType,\n                    },\n                  ],\n                }),\n              );\n            },\n          }),\n        );\n      }),\n  });\n});\n\nconst PreviewStandardToolkitRegistrationLive = McpServer.toolkit(PreviewStandardToolkit).pipe(\n  Layer.provide(PreviewStandardToolkitHandlersLive),\n);\n\nconst PreviewSnapshotRegistrationLive = Layer.effectDiscard(registerPreviewSnapshot()).pipe(\n  Layer.provide(PreviewSnapshotToolkitHandlersLive),\n);\n\nexport const PreviewToolkitRegistrationLive = Layer.mergeAll(\n  PreviewStandardToolkitRegistrationLive,\n  PreviewSnapshotRegistrationLive,\n);\n\nconst McpTransportLive = McpServer.layerHttp({\n  name: \"Synaptic Code\",\n  version: packageJson.version,\n  path: \"/mcp\",\n  protocols: [McpProtocol.v2025_06_18],\n}).pipe(Layer.provide(McpAuthMiddlewareLive));\n\nexport const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));\n","/**\n * CheckpointReactor - Checkpoint reaction service interface.\n *\n * Owns background workers that react to orchestration checkpoint lifecycle\n * events and apply checkpoint side effects.\n *\n * @module CheckpointReactor\n */\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\n/**\n * CheckpointReactorShape - Service API for checkpoint reactor lifecycle.\n */\nexport interface CheckpointReactorShape {\n  /**\n   * Start the checkpoint reactor.\n   *\n   * The returned effect must be run in a scope so all worker fibers can be\n   * finalized on shutdown.\n   *\n   * Consumes both orchestration-domain and provider-runtime events via an\n   * internal queue.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n\n  /**\n   * Resolves when the internal processing queue is empty and idle.\n   * Intended for test use to replace timing-sensitive sleeps.\n   */\n  readonly drain: Effect.Effect<void>;\n}\n\n/**\n * CheckpointReactor - Service tag for checkpoint reactor workers.\n */\nexport class CheckpointReactor extends Context.Service<CheckpointReactor, CheckpointReactorShape>()(\n  \"t3/orchestration/Services/CheckpointReactor\",\n) {}\n","/**\n * ProviderCommandReactor - Provider command reaction service interface.\n *\n * Owns background workers that react to orchestration intent events and\n * dispatch provider-side command execution.\n *\n * @module ProviderCommandReactor\n */\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\n/**\n * ProviderCommandReactorShape - Service API for provider command reactors.\n */\nexport interface ProviderCommandReactorShape {\n  /**\n   * Start reacting to provider-intent orchestration domain events.\n   *\n   * The returned effect must be run in a scope so all worker fibers can be\n   * finalized on shutdown.\n   *\n   * Filters orchestration domain events to provider-intent types before\n   * processing.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n\n  /**\n   * Resolves when the internal processing queue is empty and idle.\n   * Intended for test use to replace timing-sensitive sleeps.\n   */\n  readonly drain: Effect.Effect<void>;\n}\n\n/**\n * ProviderCommandReactor - Service tag for provider command reaction workers.\n */\nexport class ProviderCommandReactor extends Context.Service<\n  ProviderCommandReactor,\n  ProviderCommandReactorShape\n>()(\"t3/orchestration/Services/ProviderCommandReactor\") {}\n","/**\n * ProviderRuntimeIngestionService - Provider runtime ingestion service interface.\n *\n * Owns background workers that consume provider runtime streams and emit\n * orchestration commands/events.\n *\n * @module ProviderRuntimeIngestionService\n */\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\n/**\n * ProviderRuntimeIngestionShape - Service API for runtime ingestion lifecycle.\n */\nexport interface ProviderRuntimeIngestionShape {\n  /**\n   * Start ingesting provider runtime events into orchestration commands.\n   *\n   * The returned effect must be run in a scope so all worker fibers can be\n   * finalized on shutdown.\n   *\n   * Uses an internal queue and continues after non-interrupt failures by\n   * logging warnings.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n\n  /**\n   * Resolves when the internal processing queue is empty and idle.\n   * Intended for test use to replace timing-sensitive sleeps.\n   */\n  readonly drain: Effect.Effect<void>;\n}\n\n/**\n * ProviderRuntimeIngestionService - Service tag for runtime ingestion workers.\n */\nexport class ProviderRuntimeIngestionService extends Context.Service<\n  ProviderRuntimeIngestionService,\n  ProviderRuntimeIngestionShape\n>()(\"t3/orchestration/Services/ProviderRuntimeIngestion/ProviderRuntimeIngestionService\") {}\n","/**\n * ThreadDeletionReactor - Thread deletion cleanup reactor service interface.\n *\n * Owns background workers that react to thread deletion domain events and\n * perform best-effort runtime cleanup for provider sessions and terminals.\n *\n * @module ThreadDeletionReactor\n */\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Scope from \"effect/Scope\";\n\n/**\n * ThreadDeletionReactorShape - Service API for thread deletion cleanup.\n */\nexport interface ThreadDeletionReactorShape {\n  /**\n   * Start reacting to thread.deleted orchestration domain events.\n   *\n   * The returned effect must be run in a scope so all worker fibers can be\n   * finalized on shutdown.\n   */\n  readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n\n  /**\n   * Resolves when the internal processing queue is empty and idle.\n   * Intended for test use to replace timing-sensitive sleeps.\n   */\n  readonly drain: Effect.Effect<void>;\n}\n\n/**\n * ThreadDeletionReactor - Service tag for thread deletion cleanup workers.\n */\nexport class ThreadDeletionReactor extends Context.Service<\n  ThreadDeletionReactor,\n  ThreadDeletionReactorShape\n>()(\"t3/orchestration/Services/ThreadDeletionReactor\") {}\n","import type {\n  EnvironmentId,\n  OrchestrationProjectShell,\n  OrchestrationThreadShell,\n  ThreadId,\n} from \"@t3tools/contracts\";\n\nexport type AgentAwarenessPhase =\n  | \"starting\"\n  | \"running\"\n  | \"waiting_for_approval\"\n  | \"waiting_for_input\"\n  | \"completed\"\n  | \"failed\"\n  | \"stale\";\n\nexport interface AgentAwarenessState {\n  readonly environmentId: EnvironmentId;\n  readonly threadId: ThreadId;\n  readonly projectTitle: string;\n  readonly threadTitle: string;\n  readonly phase: AgentAwarenessPhase;\n  readonly headline: string;\n  readonly detail?: string;\n  readonly modelTitle: string;\n  readonly updatedAt: string;\n  readonly deepLink: string;\n}\n\nexport interface ProjectThreadAwarenessInput {\n  readonly environmentId: EnvironmentId;\n  readonly project: Pick<OrchestrationProjectShell, \"title\">;\n  readonly thread: Pick<\n    OrchestrationThreadShell,\n    | \"id\"\n    | \"title\"\n    | \"modelSelection\"\n    | \"session\"\n    | \"latestTurn\"\n    | \"updatedAt\"\n    | \"hasPendingApprovals\"\n    | \"hasPendingUserInput\"\n  >;\n}\n\nexport function buildAgentAwarenessDeepLink(input: {\n  readonly environmentId: EnvironmentId;\n  readonly threadId: ThreadId;\n}): string {\n  return `/threads/${encodeURIComponent(input.environmentId)}/${encodeURIComponent(input.threadId)}`;\n}\n\nexport function projectThreadAwareness(\n  input: ProjectThreadAwarenessInput,\n): AgentAwarenessState | null {\n  const { environmentId, project, thread } = input;\n  const phase = resolveThreadAwarenessPhase(thread);\n  if (!phase) {\n    return null;\n  }\n\n  const detail = detailForPhase(phase, thread);\n  return {\n    environmentId,\n    threadId: thread.id,\n    projectTitle: project.title,\n    threadTitle: thread.title,\n    phase,\n    headline: headlineForPhase(phase),\n    ...(detail === undefined ? {} : { detail }),\n    modelTitle: thread.modelSelection.model,\n    updatedAt: thread.updatedAt,\n    deepLink: buildAgentAwarenessDeepLink({ environmentId, threadId: thread.id }),\n  };\n}\n\nfunction resolveThreadAwarenessPhase(\n  thread: ProjectThreadAwarenessInput[\"thread\"],\n): AgentAwarenessPhase | null {\n  if (thread.hasPendingApprovals) {\n    return \"waiting_for_approval\";\n  }\n  if (thread.hasPendingUserInput) {\n    return \"waiting_for_input\";\n  }\n  if (thread.session?.status === \"error\" || thread.latestTurn?.state === \"error\") {\n    return \"failed\";\n  }\n  if (thread.session?.status === \"starting\") {\n    return \"starting\";\n  }\n  if (thread.session?.status === \"running\" || thread.latestTurn?.state === \"running\") {\n    return \"running\";\n  }\n  if (thread.latestTurn?.state === \"completed\") {\n    return \"completed\";\n  }\n  // A turn that finished can still read as \"interrupted\" here: session\n  // teardown settles still-running turns by session status, and that write\n  // can race the turn.completed one. completedAt survives the race — a turn\n  // that has a completion timestamp finished, whatever the state column says.\n  // Without this, quick finish-then-teardown threads resolve to null\n  // persistently and get tombstoned instead of published as completed.\n  if (thread.latestTurn?.state === \"interrupted\" && thread.latestTurn.completedAt !== null) {\n    return \"completed\";\n  }\n  // Threads whose turns never produce a checkpoint (no code changes) have no\n  // materialized latestTurn in the shell at all, and the session-set\n  // projection clears latest_turn_id the moment the session settles. The\n  // session status is then the only surviving completion signal: a live\n  // session at \"ready\"/\"idle\" with nothing pending and nothing running means\n  // the agent finished and is waiting for the next prompt — Done.\n  if (thread.session?.status === \"ready\" || thread.session?.status === \"idle\") {\n    return \"completed\";\n  }\n  return null;\n}\n\nfunction headlineForPhase(phase: AgentAwarenessPhase): string {\n  switch (phase) {\n    case \"starting\":\n      return \"Starting agent\";\n    case \"running\":\n      return \"Agent is working\";\n    case \"waiting_for_approval\":\n      return \"Approval needed\";\n    case \"waiting_for_input\":\n      return \"Waiting for input\";\n    case \"completed\":\n      return \"Agent finished\";\n    case \"failed\":\n      return \"Agent failed\";\n    case \"stale\":\n      return \"Update delayed\";\n  }\n}\n\nfunction detailForPhase(\n  phase: AgentAwarenessPhase,\n  thread: ProjectThreadAwarenessInput[\"thread\"],\n): string | undefined {\n  if (phase === \"failed\") {\n    return thread.session?.lastError ?? undefined;\n  }\n  if (phase === \"completed\") {\n    return \"Review the completed task.\";\n  }\n  if (phase === \"running\" && thread.session?.providerName) {\n    return `${thread.session.providerName} is active.`;\n  }\n  return undefined;\n}\n","/**\n * DrainableWorker - A queue-based worker that exposes a `drain()` effect.\n *\n * Wraps the common `Queue.unbounded` + `Effect.forever` pattern and adds\n * a signal that resolves when the queue is empty **and** the current item\n * has finished processing. This lets tests replace timing-sensitive\n * `Effect.sleep` calls with deterministic `drain()`.\n *\n * @module DrainableWorker\n */\nimport * as Scope from \"effect/Scope\";\nimport * as Effect from \"effect/Effect\";\nimport * as TxQueue from \"effect/TxQueue\";\nimport * as TxRef from \"effect/TxRef\";\n\nexport interface DrainableWorker<A> {\n  /**\n   * Enqueue a work item and track it for `drain()`.\n   *\n   * This wraps `Queue.offer` so drain state is updated atomically with the\n   * enqueue path instead of inferring it from queue internals.\n   */\n  readonly enqueue: (item: A) => Effect.Effect<void>;\n\n  /**\n   * Resolves when the queue is empty and the worker is idle (not processing).\n   */\n  readonly drain: Effect.Effect<void>;\n}\n\n/**\n * Create a drainable worker that processes items from an unbounded queue.\n *\n * The worker is forked into the current scope and will be interrupted when\n * the scope closes. A finalizer shuts down the queue.\n *\n * @param process - The effect to run for each queued item.\n * @returns A `DrainableWorker` with `queue` and `drain`.\n */\nexport const makeDrainableWorker = <A, E, R>(\n  process: (item: A) => Effect.Effect<void, E, R>,\n): Effect.Effect<DrainableWorker<A>, never, Scope.Scope | R> =>\n  Effect.gen(function* () {\n    const queue = yield* Effect.acquireRelease(TxQueue.unbounded<A>(), TxQueue.shutdown);\n    const outstanding = yield* TxRef.make(0);\n\n    yield* TxQueue.take(queue).pipe(\n      Effect.tap((a) =>\n        Effect.ensuring(\n          process(a),\n          TxRef.update(outstanding, (n) => n - 1),\n        ),\n      ),\n      Effect.forever,\n      Effect.forkScoped,\n    );\n\n    const drain: DrainableWorker<A>[\"drain\"] = TxRef.get(outstanding).pipe(\n      Effect.tap((n) => (n > 0 ? Effect.txRetry : Effect.void)),\n      Effect.tx,\n    );\n\n    const enqueue = (element: A): Effect.Effect<boolean, never, never> =>\n      TxQueue.offer(queue, element).pipe(\n        Effect.tap(() => TxRef.update(outstanding, (n) => n + 1)),\n        Effect.tx,\n      );\n\n    return { enqueue, drain } satisfies DrainableWorker<A>;\n  });\n","export const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n    const size = buffers.reduce((acc, { length }) => acc + length, 0);\n    const buf = new Uint8Array(size);\n    let i = 0;\n    for (const buffer of buffers) {\n        buf.set(buffer, i);\n        i += buffer.length;\n    }\n    return buf;\n}\nfunction writeUInt32BE(buf, value, offset) {\n    if (value < 0 || value >= MAX_INT32) {\n        throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n    }\n    buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n    const high = Math.floor(value / MAX_INT32);\n    const low = value % MAX_INT32;\n    const buf = new Uint8Array(8);\n    writeUInt32BE(buf, high, 0);\n    writeUInt32BE(buf, low, 4);\n    return buf;\n}\nexport function uint32be(value) {\n    const buf = new Uint8Array(4);\n    writeUInt32BE(buf, value);\n    return buf;\n}\nexport function encode(string) {\n    const bytes = new Uint8Array(string.length);\n    for (let i = 0; i < string.length; i++) {\n        const code = string.charCodeAt(i);\n        if (code > 127) {\n            throw new TypeError('non-ASCII string encountered in encode()');\n        }\n        bytes[i] = code;\n    }\n    return bytes;\n}\n","export function encodeBase64(input) {\n    if (Uint8Array.prototype.toBase64) {\n        return input.toBase64();\n    }\n    const CHUNK_SIZE = 0x8000;\n    const arr = [];\n    for (let i = 0; i < input.length; i += CHUNK_SIZE) {\n        arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));\n    }\n    return btoa(arr.join(''));\n}\nexport function decodeBase64(encoded) {\n    if (Uint8Array.fromBase64) {\n        return Uint8Array.fromBase64(encoded);\n    }\n    const binary = atob(encoded);\n    const bytes = new Uint8Array(binary.length);\n    for (let i = 0; i < binary.length; i++) {\n        bytes[i] = binary.charCodeAt(i);\n    }\n    return bytes;\n}\n","import { encoder, decoder } from '../lib/buffer_utils.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nexport function decode(input) {\n    if (Uint8Array.fromBase64) {\n        return Uint8Array.fromBase64(typeof input === 'string' ? input : decoder.decode(input), {\n            alphabet: 'base64url',\n        });\n    }\n    let encoded = input;\n    if (encoded instanceof Uint8Array) {\n        encoded = decoder.decode(encoded);\n    }\n    encoded = encoded.replace(/-/g, '+').replace(/_/g, '/');\n    try {\n        return decodeBase64(encoded);\n    }\n    catch {\n        throw new TypeError('The input to be decoded is not correctly encoded.');\n    }\n}\nexport function encode(input) {\n    let unencoded = input;\n    if (typeof unencoded === 'string') {\n        unencoded = encoder.encode(unencoded);\n    }\n    if (Uint8Array.prototype.toBase64) {\n        return unencoded.toBase64({ alphabet: 'base64url', omitPadding: true });\n    }\n    return encodeBase64(unencoded).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","const unusable = (name, prop = 'algorithm.name') => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\nconst isAlgorithm = (algorithm, name) => algorithm.name === name;\nfunction getHashLength(hash) {\n    return parseInt(hash.name.slice(4), 10);\n}\nfunction checkHashLength(algorithm, expected) {\n    const actual = getHashLength(algorithm.hash);\n    if (actual !== expected)\n        throw unusable(`SHA-${expected}`, 'algorithm.hash');\n}\nfunction getNamedCurve(alg) {\n    switch (alg) {\n        case 'ES256':\n            return 'P-256';\n        case 'ES384':\n            return 'P-384';\n        case 'ES512':\n            return 'P-521';\n        default:\n            throw new Error('unreachable');\n    }\n}\nfunction checkUsage(key, usage) {\n    if (usage && !key.usages.includes(usage)) {\n        throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);\n    }\n}\nexport function checkSigCryptoKey(key, alg, usage) {\n    switch (alg) {\n        case 'HS256':\n        case 'HS384':\n        case 'HS512': {\n            if (!isAlgorithm(key.algorithm, 'HMAC'))\n                throw unusable('HMAC');\n            checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n            break;\n        }\n        case 'RS256':\n        case 'RS384':\n        case 'RS512': {\n            if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n                throw unusable('RSASSA-PKCS1-v1_5');\n            checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n            break;\n        }\n        case 'PS256':\n        case 'PS384':\n        case 'PS512': {\n            if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n                throw unusable('RSA-PSS');\n            checkHashLength(key.algorithm, parseInt(alg.slice(2), 10));\n            break;\n        }\n        case 'Ed25519':\n        case 'EdDSA': {\n            if (!isAlgorithm(key.algorithm, 'Ed25519'))\n                throw unusable('Ed25519');\n            break;\n        }\n        case 'ML-DSA-44':\n        case 'ML-DSA-65':\n        case 'ML-DSA-87': {\n            if (!isAlgorithm(key.algorithm, alg))\n                throw unusable(alg);\n            break;\n        }\n        case 'ES256':\n        case 'ES384':\n        case 'ES512': {\n            if (!isAlgorithm(key.algorithm, 'ECDSA'))\n                throw unusable('ECDSA');\n            const expected = getNamedCurve(alg);\n            const actual = key.algorithm.namedCurve;\n            if (actual !== expected)\n                throw unusable(expected, 'algorithm.namedCurve');\n            break;\n        }\n        default:\n            throw new TypeError('CryptoKey does not support this operation');\n    }\n    checkUsage(key, usage);\n}\nexport function checkEncCryptoKey(key, alg, usage) {\n    switch (alg) {\n        case 'A128GCM':\n        case 'A192GCM':\n        case 'A256GCM': {\n            if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n                throw unusable('AES-GCM');\n            const expected = parseInt(alg.slice(1, 4), 10);\n            const actual = key.algorithm.length;\n            if (actual !== expected)\n                throw unusable(expected, 'algorithm.length');\n            break;\n        }\n        case 'A128KW':\n        case 'A192KW':\n        case 'A256KW': {\n            if (!isAlgorithm(key.algorithm, 'AES-KW'))\n                throw unusable('AES-KW');\n            const expected = parseInt(alg.slice(1, 4), 10);\n            const actual = key.algorithm.length;\n            if (actual !== expected)\n                throw unusable(expected, 'algorithm.length');\n            break;\n        }\n        case 'ECDH': {\n            switch (key.algorithm.name) {\n                case 'ECDH':\n                case 'X25519':\n                    break;\n                default:\n                    throw unusable('ECDH or X25519');\n            }\n            break;\n        }\n        case 'PBES2-HS256+A128KW':\n        case 'PBES2-HS384+A192KW':\n        case 'PBES2-HS512+A256KW':\n            if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n                throw unusable('PBKDF2');\n            break;\n        case 'RSA-OAEP':\n        case 'RSA-OAEP-256':\n        case 'RSA-OAEP-384':\n        case 'RSA-OAEP-512': {\n            if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n                throw unusable('RSA-OAEP');\n            checkHashLength(key.algorithm, parseInt(alg.slice(9), 10) || 1);\n            break;\n        }\n        default:\n            throw new TypeError('CryptoKey does not support this operation');\n    }\n    checkUsage(key, usage);\n}\n","function message(msg, actual, ...types) {\n    types = types.filter(Boolean);\n    if (types.length > 2) {\n        const last = types.pop();\n        msg += `one of type ${types.join(', ')}, or ${last}.`;\n    }\n    else if (types.length === 2) {\n        msg += `one of type ${types[0]} or ${types[1]}.`;\n    }\n    else {\n        msg += `of type ${types[0]}.`;\n    }\n    if (actual == null) {\n        msg += ` Received ${actual}`;\n    }\n    else if (typeof actual === 'function' && actual.name) {\n        msg += ` Received function ${actual.name}`;\n    }\n    else if (typeof actual === 'object' && actual != null) {\n        if (actual.constructor?.name) {\n            msg += ` Received an instance of ${actual.constructor.name}`;\n        }\n    }\n    return msg;\n}\nexport const invalidKeyInput = (actual, ...types) => message('Key must be ', actual, ...types);\nexport const withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);\n","export class JOSEError extends Error {\n    static code = 'ERR_JOSE_GENERIC';\n    code = 'ERR_JOSE_GENERIC';\n    constructor(message, options) {\n        super(message, options);\n        this.name = this.constructor.name;\n        Error.captureStackTrace?.(this, this.constructor);\n    }\n}\nexport class JWTClaimValidationFailed extends JOSEError {\n    static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n    code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n    claim;\n    reason;\n    payload;\n    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n        super(message, { cause: { claim, reason, payload } });\n        this.claim = claim;\n        this.reason = reason;\n        this.payload = payload;\n    }\n}\nexport class JWTExpired extends JOSEError {\n    static code = 'ERR_JWT_EXPIRED';\n    code = 'ERR_JWT_EXPIRED';\n    claim;\n    reason;\n    payload;\n    constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n        super(message, { cause: { claim, reason, payload } });\n        this.claim = claim;\n        this.reason = reason;\n        this.payload = payload;\n    }\n}\nexport class JOSEAlgNotAllowed extends JOSEError {\n    static code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n    code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n}\nexport class JOSENotSupported extends JOSEError {\n    static code = 'ERR_JOSE_NOT_SUPPORTED';\n    code = 'ERR_JOSE_NOT_SUPPORTED';\n}\nexport class JWEDecryptionFailed extends JOSEError {\n    static code = 'ERR_JWE_DECRYPTION_FAILED';\n    code = 'ERR_JWE_DECRYPTION_FAILED';\n    constructor(message = 'decryption operation failed', options) {\n        super(message, options);\n    }\n}\nexport class JWEInvalid extends JOSEError {\n    static code = 'ERR_JWE_INVALID';\n    code = 'ERR_JWE_INVALID';\n}\nexport class JWSInvalid extends JOSEError {\n    static code = 'ERR_JWS_INVALID';\n    code = 'ERR_JWS_INVALID';\n}\nexport class JWTInvalid extends JOSEError {\n    static code = 'ERR_JWT_INVALID';\n    code = 'ERR_JWT_INVALID';\n}\nexport class JWKInvalid extends JOSEError {\n    static code = 'ERR_JWK_INVALID';\n    code = 'ERR_JWK_INVALID';\n}\nexport class JWKSInvalid extends JOSEError {\n    static code = 'ERR_JWKS_INVALID';\n    code = 'ERR_JWKS_INVALID';\n}\nexport class JWKSNoMatchingKey extends JOSEError {\n    static code = 'ERR_JWKS_NO_MATCHING_KEY';\n    code = 'ERR_JWKS_NO_MATCHING_KEY';\n    constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n        super(message, options);\n    }\n}\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n    [Symbol.asyncIterator];\n    static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n    code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n    constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n        super(message, options);\n    }\n}\nexport class JWKSTimeout extends JOSEError {\n    static code = 'ERR_JWKS_TIMEOUT';\n    code = 'ERR_JWKS_TIMEOUT';\n    constructor(message = 'request timed out', options) {\n        super(message, options);\n    }\n}\nexport class JWSSignatureVerificationFailed extends JOSEError {\n    static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n    code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n    constructor(message = 'signature verification failed', options) {\n        super(message, options);\n    }\n}\n","export function assertCryptoKey(key) {\n    if (!isCryptoKey(key)) {\n        throw new Error('CryptoKey instance expected');\n    }\n}\nexport const isCryptoKey = (key) => {\n    if (key?.[Symbol.toStringTag] === 'CryptoKey')\n        return true;\n    try {\n        return key instanceof CryptoKey;\n    }\n    catch {\n        return false;\n    }\n};\nexport const isKeyObject = (key) => key?.[Symbol.toStringTag] === 'KeyObject';\nexport const isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);\n","import { decode } from '../util/base64url.js';\nexport const unprotected = Symbol();\nexport function assertNotSet(value, name) {\n    if (value) {\n        throw new TypeError(`${name} can only be called once`);\n    }\n}\nexport function decodeBase64url(value, label, ErrorClass) {\n    try {\n        return decode(value);\n    }\n    catch {\n        throw new ErrorClass(`Failed to base64url decode the ${label}`);\n    }\n}\nexport async function digest(algorithm, data) {\n    const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n    return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n}\n","const isObjectLike = (value) => typeof value === 'object' && value !== null;\nexport function isObject(input) {\n    if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n        return false;\n    }\n    if (Object.getPrototypeOf(input) === null) {\n        return true;\n    }\n    let proto = input;\n    while (Object.getPrototypeOf(proto) !== null) {\n        proto = Object.getPrototypeOf(proto);\n    }\n    return Object.getPrototypeOf(input) === proto;\n}\nexport function isDisjoint(...headers) {\n    const sources = headers.filter(Boolean);\n    if (sources.length === 0 || sources.length === 1) {\n        return true;\n    }\n    let acc;\n    for (const header of sources) {\n        const parameters = Object.keys(header);\n        if (!acc || acc.size === 0) {\n            acc = new Set(parameters);\n            continue;\n        }\n        for (const parameter of parameters) {\n            if (acc.has(parameter)) {\n                return false;\n            }\n            acc.add(parameter);\n        }\n    }\n    return true;\n}\nexport const isJWK = (key) => isObject(key) && typeof key.kty === 'string';\nexport const isPrivateJWK = (key) => key.kty !== 'oct' &&\n    ((key.kty === 'AKP' && typeof key.priv === 'string') || typeof key.d === 'string');\nexport const isPublicJWK = (key) => key.kty !== 'oct' && key.d === undefined && key.priv === undefined;\nexport const isSecretJWK = (key) => key.kty === 'oct' && typeof key.k === 'string';\n","import { JOSENotSupported } from '../util/errors.js';\nimport { checkSigCryptoKey } from './crypto_key.js';\nimport { invalidKeyInput } from './invalid_key_input.js';\nexport function checkKeyLength(alg, key) {\n    if (alg.startsWith('RS') || alg.startsWith('PS')) {\n        const { modulusLength } = key.algorithm;\n        if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n            throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n        }\n    }\n}\nfunction subtleAlgorithm(alg, algorithm) {\n    const hash = `SHA-${alg.slice(-3)}`;\n    switch (alg) {\n        case 'HS256':\n        case 'HS384':\n        case 'HS512':\n            return { hash, name: 'HMAC' };\n        case 'PS256':\n        case 'PS384':\n        case 'PS512':\n            return { hash, name: 'RSA-PSS', saltLength: parseInt(alg.slice(-3), 10) >> 3 };\n        case 'RS256':\n        case 'RS384':\n        case 'RS512':\n            return { hash, name: 'RSASSA-PKCS1-v1_5' };\n        case 'ES256':\n        case 'ES384':\n        case 'ES512':\n            return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };\n        case 'Ed25519':\n        case 'EdDSA':\n            return { name: 'Ed25519' };\n        case 'ML-DSA-44':\n        case 'ML-DSA-65':\n        case 'ML-DSA-87':\n            return { name: alg };\n        default:\n            throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n    }\n}\nasync function getSigKey(alg, key, usage) {\n    if (key instanceof Uint8Array) {\n        if (!alg.startsWith('HS')) {\n            throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n        }\n        return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);\n    }\n    checkSigCryptoKey(key, alg, usage);\n    return key;\n}\nexport async function sign(alg, key, data) {\n    const cryptoKey = await getSigKey(alg, key, 'sign');\n    checkKeyLength(alg, cryptoKey);\n    const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);\n    return new Uint8Array(signature);\n}\nexport async function verify(alg, key, signature, data) {\n    const cryptoKey = await getSigKey(alg, key, 'verify');\n    checkKeyLength(alg, cryptoKey);\n    const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);\n    try {\n        return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);\n    }\n    catch {\n        return false;\n    }\n}\n","import { JOSENotSupported } from '../util/errors.js';\nconst unsupportedAlg = 'Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value';\nfunction subtleMapping(jwk) {\n    let algorithm;\n    let keyUsages;\n    switch (jwk.kty) {\n        case 'AKP': {\n            switch (jwk.alg) {\n                case 'ML-DSA-44':\n                case 'ML-DSA-65':\n                case 'ML-DSA-87':\n                    algorithm = { name: jwk.alg };\n                    keyUsages = jwk.priv ? ['sign'] : ['verify'];\n                    break;\n                default:\n                    throw new JOSENotSupported(unsupportedAlg);\n            }\n            break;\n        }\n        case 'RSA': {\n            switch (jwk.alg) {\n                case 'PS256':\n                case 'PS384':\n                case 'PS512':\n                    algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };\n                    keyUsages = jwk.d ? ['sign'] : ['verify'];\n                    break;\n                case 'RS256':\n                case 'RS384':\n                case 'RS512':\n                    algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };\n                    keyUsages = jwk.d ? ['sign'] : ['verify'];\n                    break;\n                case 'RSA-OAEP':\n                case 'RSA-OAEP-256':\n                case 'RSA-OAEP-384':\n                case 'RSA-OAEP-512':\n                    algorithm = {\n                        name: 'RSA-OAEP',\n                        hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,\n                    };\n                    keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];\n                    break;\n                default:\n                    throw new JOSENotSupported(unsupportedAlg);\n            }\n            break;\n        }\n        case 'EC': {\n            switch (jwk.alg) {\n                case 'ES256':\n                case 'ES384':\n                case 'ES512':\n                    algorithm = {\n                        name: 'ECDSA',\n                        namedCurve: { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' }[jwk.alg],\n                    };\n                    keyUsages = jwk.d ? ['sign'] : ['verify'];\n                    break;\n                case 'ECDH-ES':\n                case 'ECDH-ES+A128KW':\n                case 'ECDH-ES+A192KW':\n                case 'ECDH-ES+A256KW':\n                    algorithm = { name: 'ECDH', namedCurve: jwk.crv };\n                    keyUsages = jwk.d ? ['deriveBits'] : [];\n                    break;\n                default:\n                    throw new JOSENotSupported(unsupportedAlg);\n            }\n            break;\n        }\n        case 'OKP': {\n            switch (jwk.alg) {\n                case 'Ed25519':\n                case 'EdDSA':\n                    algorithm = { name: 'Ed25519' };\n                    keyUsages = jwk.d ? ['sign'] : ['verify'];\n                    break;\n                case 'ECDH-ES':\n                case 'ECDH-ES+A128KW':\n                case 'ECDH-ES+A192KW':\n                case 'ECDH-ES+A256KW':\n                    algorithm = { name: jwk.crv };\n                    keyUsages = jwk.d ? ['deriveBits'] : [];\n                    break;\n                default:\n                    throw new JOSENotSupported(unsupportedAlg);\n            }\n            break;\n        }\n        default:\n            throw new JOSENotSupported('Invalid or unsupported JWK \"kty\" (Key Type) Parameter value');\n    }\n    return { algorithm, keyUsages };\n}\nexport async function jwkToKey(jwk) {\n    if (!jwk.alg) {\n        throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n    }\n    const { algorithm, keyUsages } = subtleMapping(jwk);\n    const keyData = { ...jwk };\n    if (keyData.kty !== 'AKP') {\n        delete keyData.alg;\n    }\n    delete keyData.use;\n    return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);\n}\n","import { isJWK } from './type_checks.js';\nimport { decode } from '../util/base64url.js';\nimport { jwkToKey } from './jwk_to_key.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nconst unusableForAlg = 'given KeyObject instance cannot be used for this algorithm';\nlet cache;\nconst handleJWK = async (key, jwk, alg, freeze = false) => {\n    cache ||= new WeakMap();\n    let cached = cache.get(key);\n    if (cached?.[alg]) {\n        return cached[alg];\n    }\n    const cryptoKey = await jwkToKey({ ...jwk, alg });\n    if (freeze)\n        Object.freeze(key);\n    if (!cached) {\n        cache.set(key, { [alg]: cryptoKey });\n    }\n    else {\n        cached[alg] = cryptoKey;\n    }\n    return cryptoKey;\n};\nconst handleKeyObject = (keyObject, alg) => {\n    cache ||= new WeakMap();\n    let cached = cache.get(keyObject);\n    if (cached?.[alg]) {\n        return cached[alg];\n    }\n    const isPublic = keyObject.type === 'public';\n    const extractable = isPublic ? true : false;\n    let cryptoKey;\n    if (keyObject.asymmetricKeyType === 'x25519') {\n        switch (alg) {\n            case 'ECDH-ES':\n            case 'ECDH-ES+A128KW':\n            case 'ECDH-ES+A192KW':\n            case 'ECDH-ES+A256KW':\n                break;\n            default:\n                throw new TypeError(unusableForAlg);\n        }\n        cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ['deriveBits']);\n    }\n    if (keyObject.asymmetricKeyType === 'ed25519') {\n        if (alg !== 'EdDSA' && alg !== 'Ed25519') {\n            throw new TypeError(unusableForAlg);\n        }\n        cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n            isPublic ? 'verify' : 'sign',\n        ]);\n    }\n    switch (keyObject.asymmetricKeyType) {\n        case 'ml-dsa-44':\n        case 'ml-dsa-65':\n        case 'ml-dsa-87': {\n            if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {\n                throw new TypeError(unusableForAlg);\n            }\n            cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [\n                isPublic ? 'verify' : 'sign',\n            ]);\n        }\n    }\n    if (keyObject.asymmetricKeyType === 'rsa') {\n        let hash;\n        switch (alg) {\n            case 'RSA-OAEP':\n                hash = 'SHA-1';\n                break;\n            case 'RS256':\n            case 'PS256':\n            case 'RSA-OAEP-256':\n                hash = 'SHA-256';\n                break;\n            case 'RS384':\n            case 'PS384':\n            case 'RSA-OAEP-384':\n                hash = 'SHA-384';\n                break;\n            case 'RS512':\n            case 'PS512':\n            case 'RSA-OAEP-512':\n                hash = 'SHA-512';\n                break;\n            default:\n                throw new TypeError(unusableForAlg);\n        }\n        if (alg.startsWith('RSA-OAEP')) {\n            return keyObject.toCryptoKey({\n                name: 'RSA-OAEP',\n                hash,\n            }, extractable, isPublic ? ['encrypt'] : ['decrypt']);\n        }\n        cryptoKey = keyObject.toCryptoKey({\n            name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',\n            hash,\n        }, extractable, [isPublic ? 'verify' : 'sign']);\n    }\n    if (keyObject.asymmetricKeyType === 'ec') {\n        const nist = new Map([\n            ['prime256v1', 'P-256'],\n            ['secp384r1', 'P-384'],\n            ['secp521r1', 'P-521'],\n        ]);\n        const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);\n        if (!namedCurve) {\n            throw new TypeError(unusableForAlg);\n        }\n        const expectedCurve = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' };\n        if (expectedCurve[alg] && namedCurve === expectedCurve[alg]) {\n            cryptoKey = keyObject.toCryptoKey({\n                name: 'ECDSA',\n                namedCurve,\n            }, extractable, [isPublic ? 'verify' : 'sign']);\n        }\n        if (alg.startsWith('ECDH-ES')) {\n            cryptoKey = keyObject.toCryptoKey({\n                name: 'ECDH',\n                namedCurve,\n            }, extractable, isPublic ? [] : ['deriveBits']);\n        }\n    }\n    if (!cryptoKey) {\n        throw new TypeError(unusableForAlg);\n    }\n    if (!cached) {\n        cache.set(keyObject, { [alg]: cryptoKey });\n    }\n    else {\n        cached[alg] = cryptoKey;\n    }\n    return cryptoKey;\n};\nexport async function normalizeKey(key, alg) {\n    if (key instanceof Uint8Array) {\n        return key;\n    }\n    if (isCryptoKey(key)) {\n        return key;\n    }\n    if (isKeyObject(key)) {\n        if (key.type === 'secret') {\n            return key.export();\n        }\n        if ('toCryptoKey' in key && typeof key.toCryptoKey === 'function') {\n            try {\n                return handleKeyObject(key, alg);\n            }\n            catch (err) {\n                if (err instanceof TypeError) {\n                    throw err;\n                }\n            }\n        }\n        let jwk = key.export({ format: 'jwk' });\n        return handleJWK(key, jwk, alg);\n    }\n    if (isJWK(key)) {\n        if (key.k) {\n            return decode(key.k);\n        }\n        return handleJWK(key, key, alg, true);\n    }\n    throw new Error('unreachable');\n}\n","import { invalidKeyInput } from './invalid_key_input.js';\nimport { encodeBase64, decodeBase64 } from '../lib/base64.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isCryptoKey, isKeyObject } from './is_key_like.js';\nconst formatPEM = (b64, descriptor) => {\n    const newlined = (b64.match(/.{1,64}/g) || []).join('\\n');\n    return `-----BEGIN ${descriptor}-----\\n${newlined}\\n-----END ${descriptor}-----`;\n};\nconst genericExport = async (keyType, keyFormat, key) => {\n    if (isKeyObject(key)) {\n        if (key.type !== keyType) {\n            throw new TypeError(`key is not a ${keyType} key`);\n        }\n        return key.export({ format: 'pem', type: keyFormat });\n    }\n    if (!isCryptoKey(key)) {\n        throw new TypeError(invalidKeyInput(key, 'CryptoKey', 'KeyObject'));\n    }\n    if (!key.extractable) {\n        throw new TypeError('CryptoKey is not extractable');\n    }\n    if (key.type !== keyType) {\n        throw new TypeError(`key is not a ${keyType} key`);\n    }\n    return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);\n};\nexport const toSPKI = (key) => genericExport('public', 'spki', key);\nexport const toPKCS8 = (key) => genericExport('private', 'pkcs8', key);\nconst bytesEqual = (a, b) => {\n    if (a.byteLength !== b.length)\n        return false;\n    for (let i = 0; i < a.byteLength; i++) {\n        if (a[i] !== b[i])\n            return false;\n    }\n    return true;\n};\nconst createASN1State = (data) => ({ data, pos: 0 });\nconst parseLength = (state) => {\n    const first = state.data[state.pos++];\n    if (first & 0x80) {\n        const lengthOfLen = first & 0x7f;\n        let length = 0;\n        for (let i = 0; i < lengthOfLen; i++) {\n            length = (length << 8) | state.data[state.pos++];\n        }\n        return length;\n    }\n    return first;\n};\nconst skipElement = (state, count = 1) => {\n    if (count <= 0)\n        return;\n    state.pos++;\n    const length = parseLength(state);\n    state.pos += length;\n    if (count > 1) {\n        skipElement(state, count - 1);\n    }\n};\nconst expectTag = (state, expectedTag, errorMessage) => {\n    if (state.data[state.pos++] !== expectedTag) {\n        throw new Error(errorMessage);\n    }\n};\nconst getSubarray = (state, length) => {\n    const result = state.data.subarray(state.pos, state.pos + length);\n    state.pos += length;\n    return result;\n};\nconst parseAlgorithmOID = (state) => {\n    expectTag(state, 0x06, 'Expected algorithm OID');\n    const oidLen = parseLength(state);\n    return getSubarray(state, oidLen);\n};\nfunction parsePKCS8Header(state) {\n    expectTag(state, 0x30, 'Invalid PKCS#8 structure');\n    parseLength(state);\n    expectTag(state, 0x02, 'Expected version field');\n    const verLen = parseLength(state);\n    state.pos += verLen;\n    expectTag(state, 0x30, 'Expected algorithm identifier');\n    const algIdLen = parseLength(state);\n    const algIdStart = state.pos;\n    return { algIdStart, algIdLength: algIdLen };\n}\nfunction parseSPKIHeader(state) {\n    expectTag(state, 0x30, 'Invalid SPKI structure');\n    parseLength(state);\n    expectTag(state, 0x30, 'Expected algorithm identifier');\n    const algIdLen = parseLength(state);\n    const algIdStart = state.pos;\n    return { algIdStart, algIdLength: algIdLen };\n}\nconst parseECAlgorithmIdentifier = (state) => {\n    const algOid = parseAlgorithmOID(state);\n    if (bytesEqual(algOid, [0x2b, 0x65, 0x6e])) {\n        return 'X25519';\n    }\n    if (!bytesEqual(algOid, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01])) {\n        throw new Error('Unsupported key algorithm');\n    }\n    expectTag(state, 0x06, 'Expected curve OID');\n    const curveOidLen = parseLength(state);\n    const curveOid = getSubarray(state, curveOidLen);\n    for (const { name, oid } of [\n        { name: 'P-256', oid: [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07] },\n        { name: 'P-384', oid: [0x2b, 0x81, 0x04, 0x00, 0x22] },\n        { name: 'P-521', oid: [0x2b, 0x81, 0x04, 0x00, 0x23] },\n    ]) {\n        if (bytesEqual(curveOid, oid)) {\n            return name;\n        }\n    }\n    throw new Error('Unsupported named curve');\n};\nconst genericImport = async (keyFormat, keyData, alg, options) => {\n    let algorithm;\n    let keyUsages;\n    const isPublic = keyFormat === 'spki';\n    const getSigUsages = () => (isPublic ? ['verify'] : ['sign']);\n    const getEncUsages = () => isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];\n    switch (alg) {\n        case 'PS256':\n        case 'PS384':\n        case 'PS512':\n            algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n            keyUsages = getSigUsages();\n            break;\n        case 'RS256':\n        case 'RS384':\n        case 'RS512':\n            algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n            keyUsages = getSigUsages();\n            break;\n        case 'RSA-OAEP':\n        case 'RSA-OAEP-256':\n        case 'RSA-OAEP-384':\n        case 'RSA-OAEP-512':\n            algorithm = {\n                name: 'RSA-OAEP',\n                hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,\n            };\n            keyUsages = getEncUsages();\n            break;\n        case 'ES256':\n        case 'ES384':\n        case 'ES512': {\n            const curveMap = { ES256: 'P-256', ES384: 'P-384', ES512: 'P-521' };\n            algorithm = { name: 'ECDSA', namedCurve: curveMap[alg] };\n            keyUsages = getSigUsages();\n            break;\n        }\n        case 'ECDH-ES':\n        case 'ECDH-ES+A128KW':\n        case 'ECDH-ES+A192KW':\n        case 'ECDH-ES+A256KW': {\n            try {\n                const namedCurve = options.getNamedCurve(keyData);\n                algorithm = namedCurve === 'X25519' ? { name: 'X25519' } : { name: 'ECDH', namedCurve };\n            }\n            catch (cause) {\n                throw new JOSENotSupported('Invalid or unsupported key format');\n            }\n            keyUsages = isPublic ? [] : ['deriveBits'];\n            break;\n        }\n        case 'Ed25519':\n        case 'EdDSA':\n            algorithm = { name: 'Ed25519' };\n            keyUsages = getSigUsages();\n            break;\n        case 'ML-DSA-44':\n        case 'ML-DSA-65':\n        case 'ML-DSA-87':\n            algorithm = { name: alg };\n            keyUsages = getSigUsages();\n            break;\n        default:\n            throw new JOSENotSupported('Invalid or unsupported \"alg\" (Algorithm) value');\n    }\n    return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? (isPublic ? true : false), keyUsages);\n};\nconst processPEMData = (pem, pattern) => {\n    return decodeBase64(pem.replace(pattern, ''));\n};\nexport const fromPKCS8 = (pem, alg, options) => {\n    const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PRIVATE KEY-----|\\s)/g);\n    let opts = options;\n    if (alg?.startsWith?.('ECDH-ES')) {\n        opts ||= {};\n        opts.getNamedCurve = (keyData) => {\n            const state = createASN1State(keyData);\n            parsePKCS8Header(state);\n            return parseECAlgorithmIdentifier(state);\n        };\n    }\n    return genericImport('pkcs8', keyData, alg, opts);\n};\nexport const fromSPKI = (pem, alg, options) => {\n    const keyData = processPEMData(pem, /(?:-----(?:BEGIN|END) PUBLIC KEY-----|\\s)/g);\n    let opts = options;\n    if (alg?.startsWith?.('ECDH-ES')) {\n        opts ||= {};\n        opts.getNamedCurve = (keyData) => {\n            const state = createASN1State(keyData);\n            parseSPKIHeader(state);\n            return parseECAlgorithmIdentifier(state);\n        };\n    }\n    return genericImport('spki', keyData, alg, opts);\n};\nfunction spkiFromX509(buf) {\n    const state = createASN1State(buf);\n    expectTag(state, 0x30, 'Invalid certificate structure');\n    parseLength(state);\n    expectTag(state, 0x30, 'Invalid tbsCertificate structure');\n    parseLength(state);\n    if (buf[state.pos] === 0xa0) {\n        skipElement(state, 6);\n    }\n    else {\n        skipElement(state, 5);\n    }\n    const spkiStart = state.pos;\n    expectTag(state, 0x30, 'Invalid SPKI structure');\n    const spkiContentLen = parseLength(state);\n    return buf.subarray(spkiStart, spkiStart + spkiContentLen + (state.pos - spkiStart));\n}\nfunction extractX509SPKI(x509) {\n    const derBytes = processPEMData(x509, /(?:-----(?:BEGIN|END) CERTIFICATE-----|\\s)/g);\n    return spkiFromX509(derBytes);\n}\nexport const fromX509 = (pem, alg, options) => {\n    let spki;\n    try {\n        spki = extractX509SPKI(pem);\n    }\n    catch (cause) {\n        throw new TypeError('Failed to parse the X.509 certificate', { cause });\n    }\n    return fromSPKI(formatPEM(encodeBase64(spki), 'PUBLIC KEY'), alg, options);\n};\n","import { decode as decodeBase64URL } from '../util/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../lib/asn1.js';\nimport { jwkToKey } from '../lib/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { isObject } from '../lib/type_checks.js';\nexport async function importSPKI(spki, alg, options) {\n    if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n        throw new TypeError('\"spki\" must be SPKI formatted string');\n    }\n    return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n    if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n        throw new TypeError('\"x509\" must be X.509 formatted string');\n    }\n    return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n    if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n        throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n    }\n    return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg, options) {\n    if (!isObject(jwk)) {\n        throw new TypeError('JWK must be an object');\n    }\n    let ext;\n    alg ??= jwk.alg;\n    ext ??= options?.extractable ?? jwk.ext;\n    switch (jwk.kty) {\n        case 'oct':\n            if (typeof jwk.k !== 'string' || !jwk.k) {\n                throw new TypeError('missing \"k\" (Key Value) Parameter value');\n            }\n            return decodeBase64URL(jwk.k);\n        case 'RSA':\n            if ('oth' in jwk && jwk.oth !== undefined) {\n                throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n            }\n            return jwkToKey({ ...jwk, alg, ext });\n        case 'AKP': {\n            if (typeof jwk.alg !== 'string' || !jwk.alg) {\n                throw new TypeError('missing \"alg\" (Algorithm) Parameter value');\n            }\n            if (alg !== undefined && alg !== jwk.alg) {\n                throw new TypeError('JWK alg and alg option value mismatch');\n            }\n            return jwkToKey({ ...jwk, ext });\n        }\n        case 'EC':\n        case 'OKP':\n            return jwkToKey({ ...jwk, alg, ext });\n        default:\n            throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n    }\n}\n","import { JOSENotSupported, JWEInvalid, JWSInvalid } from '../util/errors.js';\nexport function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n    if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {\n        throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n    }\n    if (!protectedHeader || protectedHeader.crit === undefined) {\n        return new Set();\n    }\n    if (!Array.isArray(protectedHeader.crit) ||\n        protectedHeader.crit.length === 0 ||\n        protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n        throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n    }\n    let recognized;\n    if (recognizedOption !== undefined) {\n        recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n    }\n    else {\n        recognized = recognizedDefault;\n    }\n    for (const parameter of protectedHeader.crit) {\n        if (!recognized.has(parameter)) {\n            throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n        }\n        if (joseHeader[parameter] === undefined) {\n            throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n        }\n        if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n            throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n        }\n    }\n    return new Set(protectedHeader.crit);\n}\n","export function validateAlgorithms(option, algorithms) {\n    if (algorithms !== undefined &&\n        (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n        throw new TypeError(`\"${option}\" option must be an array of strings`);\n    }\n    if (!algorithms) {\n        return undefined;\n    }\n    return new Set(algorithms);\n}\n","import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport { isKeyLike } from './is_key_like.js';\nimport * as jwk from './type_checks.js';\nconst tag = (key) => key?.[Symbol.toStringTag];\nconst jwkMatchesOp = (alg, key, usage) => {\n    if (key.use !== undefined) {\n        let expected;\n        switch (usage) {\n            case 'sign':\n            case 'verify':\n                expected = 'sig';\n                break;\n            case 'encrypt':\n            case 'decrypt':\n                expected = 'enc';\n                break;\n        }\n        if (key.use !== expected) {\n            throw new TypeError(`Invalid key for this operation, its \"use\" must be \"${expected}\" when present`);\n        }\n    }\n    if (key.alg !== undefined && key.alg !== alg) {\n        throw new TypeError(`Invalid key for this operation, its \"alg\" must be \"${alg}\" when present`);\n    }\n    if (Array.isArray(key.key_ops)) {\n        let expectedKeyOp;\n        switch (true) {\n            case usage === 'sign' || usage === 'verify':\n            case alg === 'dir':\n            case alg.includes('CBC-HS'):\n                expectedKeyOp = usage;\n                break;\n            case alg.startsWith('PBES2'):\n                expectedKeyOp = 'deriveBits';\n                break;\n            case /^A\\d{3}(?:GCM)?(?:KW)?$/.test(alg):\n                if (!alg.includes('GCM') && alg.endsWith('KW')) {\n                    expectedKeyOp = usage === 'encrypt' ? 'wrapKey' : 'unwrapKey';\n                }\n                else {\n                    expectedKeyOp = usage;\n                }\n                break;\n            case usage === 'encrypt' && alg.startsWith('RSA'):\n                expectedKeyOp = 'wrapKey';\n                break;\n            case usage === 'decrypt':\n                expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits';\n                break;\n        }\n        if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {\n            throw new TypeError(`Invalid key for this operation, its \"key_ops\" must include \"${expectedKeyOp}\" when present`);\n        }\n    }\n    return true;\n};\nconst symmetricTypeCheck = (alg, key, usage) => {\n    if (key instanceof Uint8Array)\n        return;\n    if (jwk.isJWK(key)) {\n        if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))\n            return;\n        throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present`);\n    }\n    if (!isKeyLike(key)) {\n        throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array'));\n    }\n    if (key.type !== 'secret') {\n        throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type \"secret\"`);\n    }\n};\nconst asymmetricTypeCheck = (alg, key, usage) => {\n    if (jwk.isJWK(key)) {\n        switch (usage) {\n            case 'decrypt':\n            case 'sign':\n                if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))\n                    return;\n                throw new TypeError(`JSON Web Key for this operation must be a private JWK`);\n            case 'encrypt':\n            case 'verify':\n                if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))\n                    return;\n                throw new TypeError(`JSON Web Key for this operation must be a public JWK`);\n        }\n    }\n    if (!isKeyLike(key)) {\n        throw new TypeError(invalidKeyInput(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));\n    }\n    if (key.type === 'secret') {\n        throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type \"secret\"`);\n    }\n    if (key.type === 'public') {\n        switch (usage) {\n            case 'sign':\n                throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type \"private\"`);\n            case 'decrypt':\n                throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type \"private\"`);\n        }\n    }\n    if (key.type === 'private') {\n        switch (usage) {\n            case 'verify':\n                throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type \"public\"`);\n            case 'encrypt':\n                throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type \"public\"`);\n        }\n    }\n};\nexport function checkKeyType(alg, key, usage) {\n    switch (alg.substring(0, 2)) {\n        case 'A1':\n        case 'A2':\n        case 'di':\n        case 'HS':\n        case 'PB':\n            symmetricTypeCheck(alg, key, usage);\n            break;\n        default:\n            asymmetricTypeCheck(alg, key, usage);\n    }\n}\n","import { decode as b64u } from '../../util/base64url.js';\nimport { verify } from '../../lib/signing.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder, encode } from '../../lib/buffer_utils.js';\nimport { decodeBase64url } from '../../lib/helpers.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { isObject } from '../../lib/type_checks.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { validateAlgorithms } from '../../lib/validate_algorithms.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nexport async function flattenedVerify(jws, key, options) {\n    if (!isObject(jws)) {\n        throw new JWSInvalid('Flattened JWS must be an object');\n    }\n    if (jws.protected === undefined && jws.header === undefined) {\n        throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n    }\n    if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n        throw new JWSInvalid('JWS Protected Header incorrect type');\n    }\n    if (jws.payload === undefined) {\n        throw new JWSInvalid('JWS Payload missing');\n    }\n    if (typeof jws.signature !== 'string') {\n        throw new JWSInvalid('JWS Signature missing or incorrect type');\n    }\n    if (jws.header !== undefined && !isObject(jws.header)) {\n        throw new JWSInvalid('JWS Unprotected Header incorrect type');\n    }\n    let parsedProt = {};\n    if (jws.protected) {\n        try {\n            const protectedHeader = b64u(jws.protected);\n            parsedProt = JSON.parse(decoder.decode(protectedHeader));\n        }\n        catch {\n            throw new JWSInvalid('JWS Protected Header is invalid');\n        }\n    }\n    if (!isDisjoint(parsedProt, jws.header)) {\n        throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n    }\n    const joseHeader = {\n        ...parsedProt,\n        ...jws.header,\n    };\n    const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);\n    let b64 = true;\n    if (extensions.has('b64')) {\n        b64 = parsedProt.b64;\n        if (typeof b64 !== 'boolean') {\n            throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n        }\n    }\n    const { alg } = joseHeader;\n    if (typeof alg !== 'string' || !alg) {\n        throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n    }\n    const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n    if (algorithms && !algorithms.has(alg)) {\n        throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n    }\n    if (b64) {\n        if (typeof jws.payload !== 'string') {\n            throw new JWSInvalid('JWS Payload must be a string');\n        }\n    }\n    else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n        throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n    }\n    let resolvedKey = false;\n    if (typeof key === 'function') {\n        key = await key(parsedProt, jws);\n        resolvedKey = true;\n    }\n    checkKeyType(alg, key, 'verify');\n    const data = concat(jws.protected !== undefined ? encode(jws.protected) : new Uint8Array(), encode('.'), typeof jws.payload === 'string'\n        ? b64\n            ? encode(jws.payload)\n            : encoder.encode(jws.payload)\n        : jws.payload);\n    const signature = decodeBase64url(jws.signature, 'signature', JWSInvalid);\n    const k = await normalizeKey(key, alg);\n    const verified = await verify(alg, k, signature, data);\n    if (!verified) {\n        throw new JWSSignatureVerificationFailed();\n    }\n    let payload;\n    if (b64) {\n        payload = decodeBase64url(jws.payload, 'payload', JWSInvalid);\n    }\n    else if (typeof jws.payload === 'string') {\n        payload = encoder.encode(jws.payload);\n    }\n    else {\n        payload = jws.payload;\n    }\n    const result = { payload };\n    if (jws.protected !== undefined) {\n        result.protectedHeader = parsedProt;\n    }\n    if (jws.header !== undefined) {\n        result.unprotectedHeader = jws.header;\n    }\n    if (resolvedKey) {\n        return { ...result, key: k };\n    }\n    return result;\n}\n","import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n    if (jws instanceof Uint8Array) {\n        jws = decoder.decode(jws);\n    }\n    if (typeof jws !== 'string') {\n        throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n    }\n    const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n    if (length !== 3) {\n        throw new JWSInvalid('Invalid Compact JWS');\n    }\n    const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n    const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n    if (typeof key === 'function') {\n        return { ...result, key: verified.key };\n    }\n    return result;\n}\n","import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { encoder, decoder } from './buffer_utils.js';\nimport { isObject } from './type_checks.js';\nconst epoch = (date) => Math.floor(date.getTime() / 1000);\nconst minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;\nexport function secs(str) {\n    const matched = REGEX.exec(str);\n    if (!matched || (matched[4] && matched[1])) {\n        throw new TypeError('Invalid time period format');\n    }\n    const value = parseFloat(matched[2]);\n    const unit = matched[3].toLowerCase();\n    let numericDate;\n    switch (unit) {\n        case 'sec':\n        case 'secs':\n        case 'second':\n        case 'seconds':\n        case 's':\n            numericDate = Math.round(value);\n            break;\n        case 'minute':\n        case 'minutes':\n        case 'min':\n        case 'mins':\n        case 'm':\n            numericDate = Math.round(value * minute);\n            break;\n        case 'hour':\n        case 'hours':\n        case 'hr':\n        case 'hrs':\n        case 'h':\n            numericDate = Math.round(value * hour);\n            break;\n        case 'day':\n        case 'days':\n        case 'd':\n            numericDate = Math.round(value * day);\n            break;\n        case 'week':\n        case 'weeks':\n        case 'w':\n            numericDate = Math.round(value * week);\n            break;\n        default:\n            numericDate = Math.round(value * year);\n            break;\n    }\n    if (matched[1] === '-' || matched[4] === 'ago') {\n        return -numericDate;\n    }\n    return numericDate;\n}\nfunction validateInput(label, input) {\n    if (!Number.isFinite(input)) {\n        throw new TypeError(`Invalid ${label} input`);\n    }\n    return input;\n}\nconst normalizeTyp = (value) => {\n    if (value.includes('/')) {\n        return value.toLowerCase();\n    }\n    return `application/${value.toLowerCase()}`;\n};\nconst checkAudiencePresence = (audPayload, audOption) => {\n    if (typeof audPayload === 'string') {\n        return audOption.includes(audPayload);\n    }\n    if (Array.isArray(audPayload)) {\n        return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n    }\n    return false;\n};\nexport function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {\n    let payload;\n    try {\n        payload = JSON.parse(decoder.decode(encodedPayload));\n    }\n    catch {\n    }\n    if (!isObject(payload)) {\n        throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n    }\n    const { typ } = options;\n    if (typ &&\n        (typeof protectedHeader.typ !== 'string' ||\n            normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n        throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, 'typ', 'check_failed');\n    }\n    const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;\n    const presenceCheck = [...requiredClaims];\n    if (maxTokenAge !== undefined)\n        presenceCheck.push('iat');\n    if (audience !== undefined)\n        presenceCheck.push('aud');\n    if (subject !== undefined)\n        presenceCheck.push('sub');\n    if (issuer !== undefined)\n        presenceCheck.push('iss');\n    for (const claim of new Set(presenceCheck.reverse())) {\n        if (!(claim in payload)) {\n            throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, 'missing');\n        }\n    }\n    if (issuer &&\n        !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n        throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', payload, 'iss', 'check_failed');\n    }\n    if (subject && payload.sub !== subject) {\n        throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', payload, 'sub', 'check_failed');\n    }\n    if (audience &&\n        !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n        throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', payload, 'aud', 'check_failed');\n    }\n    let tolerance;\n    switch (typeof options.clockTolerance) {\n        case 'string':\n            tolerance = secs(options.clockTolerance);\n            break;\n        case 'number':\n            tolerance = options.clockTolerance;\n            break;\n        case 'undefined':\n            tolerance = 0;\n            break;\n        default:\n            throw new TypeError('Invalid clockTolerance option type');\n    }\n    const { currentDate } = options;\n    const now = epoch(currentDate || new Date());\n    if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {\n        throw new JWTClaimValidationFailed('\"iat\" claim must be a number', payload, 'iat', 'invalid');\n    }\n    if (payload.nbf !== undefined) {\n        if (typeof payload.nbf !== 'number') {\n            throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', payload, 'nbf', 'invalid');\n        }\n        if (payload.nbf > now + tolerance) {\n            throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, 'nbf', 'check_failed');\n        }\n    }\n    if (payload.exp !== undefined) {\n        if (typeof payload.exp !== 'number') {\n            throw new JWTClaimValidationFailed('\"exp\" claim must be a number', payload, 'exp', 'invalid');\n        }\n        if (payload.exp <= now - tolerance) {\n            throw new JWTExpired('\"exp\" claim timestamp check failed', payload, 'exp', 'check_failed');\n        }\n    }\n    if (maxTokenAge) {\n        const age = now - payload.iat;\n        const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);\n        if (age - tolerance > max) {\n            throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');\n        }\n        if (age < 0 - tolerance) {\n            throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');\n        }\n    }\n    return payload;\n}\nexport class JWTClaimsBuilder {\n    #payload;\n    constructor(payload) {\n        if (!isObject(payload)) {\n            throw new TypeError('JWT Claims Set MUST be an object');\n        }\n        this.#payload = structuredClone(payload);\n    }\n    data() {\n        return encoder.encode(JSON.stringify(this.#payload));\n    }\n    get iss() {\n        return this.#payload.iss;\n    }\n    set iss(value) {\n        this.#payload.iss = value;\n    }\n    get sub() {\n        return this.#payload.sub;\n    }\n    set sub(value) {\n        this.#payload.sub = value;\n    }\n    get aud() {\n        return this.#payload.aud;\n    }\n    set aud(value) {\n        this.#payload.aud = value;\n    }\n    set jti(value) {\n        this.#payload.jti = value;\n    }\n    set nbf(value) {\n        if (typeof value === 'number') {\n            this.#payload.nbf = validateInput('setNotBefore', value);\n        }\n        else if (value instanceof Date) {\n            this.#payload.nbf = validateInput('setNotBefore', epoch(value));\n        }\n        else {\n            this.#payload.nbf = epoch(new Date()) + secs(value);\n        }\n    }\n    set exp(value) {\n        if (typeof value === 'number') {\n            this.#payload.exp = validateInput('setExpirationTime', value);\n        }\n        else if (value instanceof Date) {\n            this.#payload.exp = validateInput('setExpirationTime', epoch(value));\n        }\n        else {\n            this.#payload.exp = epoch(new Date()) + secs(value);\n        }\n    }\n    set iat(value) {\n        if (value === undefined) {\n            this.#payload.iat = epoch(new Date());\n        }\n        else if (value instanceof Date) {\n            this.#payload.iat = validateInput('setIssuedAt', epoch(value));\n        }\n        else if (typeof value === 'string') {\n            this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value));\n        }\n        else {\n            this.#payload.iat = validateInput('setIssuedAt', value);\n        }\n    }\n}\n","import { compactVerify } from '../jws/compact/verify.js';\nimport { validateClaimsSet } from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n    const verified = await compactVerify(jwt, key, options);\n    if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {\n        throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n    }\n    const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);\n    const result = { payload, protectedHeader: verified.protectedHeader };\n    if (typeof key === 'function') {\n        return { ...result, key: verified.key };\n    }\n    return result;\n}\n","import { encode as b64u } from '../../util/base64url.js';\nimport { sign } from '../../lib/signing.js';\nimport { isDisjoint } from '../../lib/type_checks.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { concat, encode } from '../../lib/buffer_utils.js';\nimport { checkKeyType } from '../../lib/check_key_type.js';\nimport { validateCrit } from '../../lib/validate_crit.js';\nimport { normalizeKey } from '../../lib/normalize_key.js';\nimport { assertNotSet } from '../../lib/helpers.js';\nexport class FlattenedSign {\n    #payload;\n    #protectedHeader;\n    #unprotectedHeader;\n    constructor(payload) {\n        if (!(payload instanceof Uint8Array)) {\n            throw new TypeError('payload must be an instance of Uint8Array');\n        }\n        this.#payload = payload;\n    }\n    setProtectedHeader(protectedHeader) {\n        assertNotSet(this.#protectedHeader, 'setProtectedHeader');\n        this.#protectedHeader = protectedHeader;\n        return this;\n    }\n    setUnprotectedHeader(unprotectedHeader) {\n        assertNotSet(this.#unprotectedHeader, 'setUnprotectedHeader');\n        this.#unprotectedHeader = unprotectedHeader;\n        return this;\n    }\n    async sign(key, options) {\n        if (!this.#protectedHeader && !this.#unprotectedHeader) {\n            throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');\n        }\n        if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) {\n            throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n        }\n        const joseHeader = {\n            ...this.#protectedHeader,\n            ...this.#unprotectedHeader,\n        };\n        const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this.#protectedHeader, joseHeader);\n        let b64 = true;\n        if (extensions.has('b64')) {\n            b64 = this.#protectedHeader.b64;\n            if (typeof b64 !== 'boolean') {\n                throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n            }\n        }\n        const { alg } = joseHeader;\n        if (typeof alg !== 'string' || !alg) {\n            throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n        }\n        checkKeyType(alg, key, 'sign');\n        let payloadS;\n        let payloadB;\n        if (b64) {\n            payloadS = b64u(this.#payload);\n            payloadB = encode(payloadS);\n        }\n        else {\n            payloadB = this.#payload;\n            payloadS = '';\n        }\n        let protectedHeaderString;\n        let protectedHeaderBytes;\n        if (this.#protectedHeader) {\n            protectedHeaderString = b64u(JSON.stringify(this.#protectedHeader));\n            protectedHeaderBytes = encode(protectedHeaderString);\n        }\n        else {\n            protectedHeaderString = '';\n            protectedHeaderBytes = new Uint8Array();\n        }\n        const data = concat(protectedHeaderBytes, encode('.'), payloadB);\n        const k = await normalizeKey(key, alg);\n        const signature = await sign(alg, k, data);\n        const jws = {\n            signature: b64u(signature),\n            payload: payloadS,\n        };\n        if (this.#unprotectedHeader) {\n            jws.header = this.#unprotectedHeader;\n        }\n        if (this.#protectedHeader) {\n            jws.protected = protectedHeaderString;\n        }\n        return jws;\n    }\n}\n","import { FlattenedSign } from '../flattened/sign.js';\nexport class CompactSign {\n    #flattened;\n    constructor(payload) {\n        this.#flattened = new FlattenedSign(payload);\n    }\n    setProtectedHeader(protectedHeader) {\n        this.#flattened.setProtectedHeader(protectedHeader);\n        return this;\n    }\n    async sign(key, options) {\n        const jws = await this.#flattened.sign(key, options);\n        if (jws.payload === undefined) {\n            throw new TypeError('use the flattened module for creating JWS with b64: false');\n        }\n        return `${jws.protected}.${jws.payload}.${jws.signature}`;\n    }\n}\n","import { CompactSign } from '../jws/compact/sign.js';\nimport { JWTInvalid } from '../util/errors.js';\nimport { JWTClaimsBuilder } from '../lib/jwt_claims_set.js';\nexport class SignJWT {\n    #protectedHeader;\n    #jwt;\n    constructor(payload = {}) {\n        this.#jwt = new JWTClaimsBuilder(payload);\n    }\n    setIssuer(issuer) {\n        this.#jwt.iss = issuer;\n        return this;\n    }\n    setSubject(subject) {\n        this.#jwt.sub = subject;\n        return this;\n    }\n    setAudience(audience) {\n        this.#jwt.aud = audience;\n        return this;\n    }\n    setJti(jwtId) {\n        this.#jwt.jti = jwtId;\n        return this;\n    }\n    setNotBefore(input) {\n        this.#jwt.nbf = input;\n        return this;\n    }\n    setExpirationTime(input) {\n        this.#jwt.exp = input;\n        return this;\n    }\n    setIssuedAt(input) {\n        this.#jwt.iat = input;\n        return this;\n    }\n    setProtectedHeader(protectedHeader) {\n        this.#protectedHeader = protectedHeader;\n        return this;\n    }\n    async sign(key, options) {\n        const sig = new CompactSign(this.#jwt.data());\n        sig.setProtectedHeader(this.#protectedHeader);\n        if (Array.isArray(this.#protectedHeader?.crit) &&\n            this.#protectedHeader.crit.includes('b64') &&\n            this.#protectedHeader.b64 === false) {\n            throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n        }\n        return sig.sign(key, options);\n    }\n}\n","import { decodeJwt, importPKCS8, importSPKI, jwtVerify, SignJWT, type JWTPayload } from \"jose\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Predicate from \"effect/Predicate\";\nimport * as Schema from \"effect/Schema\";\n\nexport const RELAY_LINK_PROOF_TYP = \"t3-env-link+jwt\";\nexport const RELAY_MINT_REQUEST_TYP = \"t3-cloud-mint+jwt\";\nexport const RELAY_HEALTH_REQUEST_TYP = \"t3-cloud-health+jwt\";\nexport const RELAY_MINT_RESPONSE_TYP = \"t3-env-mint+jwt\";\nexport const RELAY_HEALTH_RESPONSE_TYP = \"t3-env-health+jwt\";\nexport const RELAY_ACTIVITY_PUBLISH_TYP = \"t3-env-activity+jwt\";\n\nexport class RelayJwtError extends Schema.TaggedErrorClass<RelayJwtError>()(\"RelayJwtError\", {\n  operation: Schema.Literals([\"sign\", \"verify\"]),\n  typ: Schema.String,\n  issuer: Schema.optional(Schema.String),\n  audience: Schema.optional(Schema.String),\n  cause: Schema.Defect(),\n}) {\n  override get message(): string {\n    return `Failed to ${this.operation} relay JWT of type \"${this.typ}\".`;\n  }\n\n  static diagnosticCode(error: RelayJwtError): string {\n    if (\n      Predicate.isObject(error.cause) &&\n      Predicate.hasProperty(error.cause, \"code\") &&\n      Predicate.isString(error.cause.code) &&\n      error.cause.code.length > 0\n    ) {\n      return error.cause.code;\n    }\n\n    return error.cause instanceof Error && error.cause.name ? error.cause.name : \"unknown\";\n  }\n}\n\nexport function normalizeRelayIssuer(value: string): string {\n  return value.trim().replace(/\\/+$/gu, \"\");\n}\n\nexport function decodeRelayJwt(token: string): JWTPayload {\n  return decodeJwt(token);\n}\n\nfunction normalizePem(value: string): string {\n  return value.replace(/\\\\n/gu, \"\\n\").trim();\n}\n\nexport function signRelayJwt(input: {\n  readonly privateKey: string;\n  readonly typ: string;\n  readonly payload: JWTPayload;\n}): Effect.Effect<string, RelayJwtError> {\n  return Effect.tryPromise({\n    try: async () => {\n      const key = await importPKCS8(normalizePem(input.privateKey), \"EdDSA\");\n      return new SignJWT(input.payload)\n        .setProtectedHeader({ alg: \"EdDSA\", typ: input.typ })\n        .sign(key);\n    },\n    catch: (cause) => new RelayJwtError({ operation: \"sign\", typ: input.typ, cause }),\n  });\n}\n\nexport function verifyRelayJwt(input: {\n  readonly publicKey: string;\n  readonly token: string;\n  readonly typ: string;\n  readonly issuer: string;\n  readonly audience: string;\n  readonly nowEpochSeconds: number;\n  readonly maxTokenAge?: string | number;\n}): Effect.Effect<JWTPayload, RelayJwtError> {\n  return Effect.tryPromise({\n    try: async () => {\n      const key = await importSPKI(normalizePem(input.publicKey), \"EdDSA\");\n      const verified = await jwtVerify(input.token, key, {\n        algorithms: [\"EdDSA\"],\n        typ: input.typ,\n        issuer: input.issuer,\n        audience: input.audience,\n        maxTokenAge: input.maxTokenAge ?? \"5 minutes\",\n        clockTolerance: 60,\n        currentDate: DateTime.toDate(DateTime.makeUnsafe(input.nowEpochSeconds * 1_000)),\n      });\n      return verified.payload;\n    },\n    catch: (cause) =>\n      new RelayJwtError({\n        operation: \"verify\",\n        typ: input.typ,\n        issuer: input.issuer,\n        audience: input.audience,\n        cause,\n      }),\n  });\n}\n","import { RelayManagedEndpointRuntimeConfig } from \"@t3tools/contracts/relay\";\nimport * as Schema from \"effect/Schema\";\n\nexport const CLOUD_MINT_PUBLIC_KEY = \"cloud-mint-ed25519-public-key\";\nexport const CLOUD_ENDPOINT_RUNTIME_CONFIG = \"cloud-endpoint-runtime-config\";\nexport const CLOUD_LINKED_USER_ID = \"cloud-linked-user-id\";\nexport const RELAY_URL_SECRET = \"cloud-relay-url\";\nexport const RELAY_ISSUER_SECRET = \"cloud-relay-issuer\";\nexport const RELAY_ENVIRONMENT_CREDENTIAL_SECRET = \"cloud-relay-environment-credential\";\nexport const PUBLISH_AGENT_ACTIVITY_SECRET = \"cloud-publish-agent-activity\";\n\nexport const encodeEndpointRuntimeConfigJson = Schema.encodeEffect(\n  Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),\n);\n\nexport const decodeRuntimeConfig = Schema.decodeUnknownOption(\n  Schema.fromJsonString(RelayManagedEndpointRuntimeConfig),\n);\n","import * as NodeCrypto from \"node:crypto\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ServerSecretStore from \"../auth/ServerSecretStore.ts\";\n\nconst CLOUD_LINK_KEY_PAIR = \"cloud-link-ed25519-key-pair\";\nconst CLOUD_LINK_PRIVATE_KEY = \"cloud-link-ed25519-private-key\";\nconst CLOUD_LINK_PUBLIC_KEY = \"cloud-link-ed25519-public-key\";\n\nconst EnvironmentKeyPair = Schema.Struct({\n  privateKey: Schema.String,\n  publicKey: Schema.String,\n});\ntype EnvironmentKeyPair = typeof EnvironmentKeyPair.Type;\n\nconst EnvironmentKeyPairJson = Schema.fromJsonString(EnvironmentKeyPair);\nconst decodeEnvironmentKeyPair = Schema.decodeUnknownEffect(EnvironmentKeyPairJson);\nconst encodeEnvironmentKeyPair = Schema.encodeEffect(EnvironmentKeyPairJson);\n\nfunction bytesToString(bytes: Uint8Array): string {\n  return new TextDecoder().decode(bytes);\n}\n\nfunction stringToBytes(value: string): Uint8Array {\n  return new TextEncoder().encode(value);\n}\n\nconst KEY_PAIR_RESOURCE = \"environment signing key pair\";\n\nconst keyPairDecodeError = (cause: unknown): ServerSecretStore.SecretStoreDecodeError =>\n  new ServerSecretStore.SecretStoreDecodeError({ resource: KEY_PAIR_RESOURCE, cause });\n\nconst keyPairEncodeError = (cause: unknown): ServerSecretStore.SecretStoreEncodeError =>\n  new ServerSecretStore.SecretStoreEncodeError({ resource: KEY_PAIR_RESOURCE, cause });\n\nconst keyPairConcurrentReadError = (): ServerSecretStore.SecretStoreConcurrentReadError =>\n  new ServerSecretStore.SecretStoreConcurrentReadError({ resource: KEY_PAIR_RESOURCE });\n\nconst readEnvironmentKeyPair = Effect.fn(\"readEnvironmentKeyPair\")(function* (\n  secrets: ServerSecretStore.ServerSecretStore[\"Service\"],\n) {\n  const encoded = yield* secrets.get(CLOUD_LINK_KEY_PAIR);\n  if (Option.isNone(encoded)) {\n    return Option.none<EnvironmentKeyPair>();\n  }\n  const decoded = yield* decodeEnvironmentKeyPair(bytesToString(encoded.value)).pipe(\n    Effect.mapError(keyPairDecodeError),\n  );\n  return Option.some(decoded);\n});\n\nconst persistEnvironmentKeyPair = Effect.fn(\"persistEnvironmentKeyPair\")(function* (\n  secrets: ServerSecretStore.ServerSecretStore[\"Service\"],\n  keyPair: EnvironmentKeyPair,\n) {\n  const encoded = yield* encodeEnvironmentKeyPair(keyPair).pipe(\n    Effect.mapError(keyPairEncodeError),\n  );\n  return yield* secrets.create(CLOUD_LINK_KEY_PAIR, stringToBytes(encoded)).pipe(\n    Effect.as(keyPair),\n    Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>\n      ServerSecretStore.isSecretAlreadyExistsError(error)\n        ? readEnvironmentKeyPair(secrets).pipe(\n            Effect.flatMap(\n              Option.match({\n                onSome: Effect.succeed,\n                onNone: () => Effect.fail(keyPairConcurrentReadError()),\n              }),\n            ),\n          )\n        : Effect.fail(error),\n    ),\n  );\n});\n\nexport const getOrCreateEnvironmentKeyPairFromSecretStore = Effect.fn(function* (\n  secrets: ServerSecretStore.ServerSecretStore[\"Service\"],\n) {\n  const existing = yield* readEnvironmentKeyPair(secrets);\n  if (Option.isSome(existing)) {\n    return existing.value;\n  }\n\n  const existingPrivate = yield* secrets.get(CLOUD_LINK_PRIVATE_KEY);\n  const existingPublic = yield* secrets.get(CLOUD_LINK_PUBLIC_KEY);\n  if (Option.isSome(existingPrivate) && Option.isSome(existingPublic)) {\n    return yield* persistEnvironmentKeyPair(secrets, {\n      privateKey: bytesToString(existingPrivate.value),\n      publicKey: bytesToString(existingPublic.value),\n    });\n  }\n\n  const keyPair = NodeCrypto.generateKeyPairSync(\"ed25519\", {\n    privateKeyEncoding: { format: \"pem\", type: \"pkcs8\" },\n    publicKeyEncoding: { format: \"pem\", type: \"spki\" },\n  });\n  return yield* persistEnvironmentKeyPair(secrets, {\n    privateKey: keyPair.privateKey,\n    publicKey: keyPair.publicKey,\n  });\n});\n","import type {\n  EnvironmentId,\n  OrchestrationEvent,\n  OrchestrationProjectShell,\n  OrchestrationThreadShell,\n  ThreadId,\n} from \"@t3tools/contracts\";\nimport {\n  RelayApi,\n  type RelayAgentActivityPublishProofPayload,\n  type RelayAgentActivityState,\n} from \"@t3tools/contracts/relay\";\nimport { projectThreadAwareness } from \"@t3tools/shared/agentAwareness\";\nimport { makeDrainableWorker } from \"@t3tools/shared/DrainableWorker\";\nimport { withRelayClientTracing } from \"@t3tools/shared/relayTracing\";\nimport {\n  normalizeRelayIssuer,\n  RELAY_ACTIVITY_PUBLISH_TYP,\n  signRelayJwt,\n} from \"@t3tools/shared/relayJwt\";\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport type * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as FetchHttpClient from \"effect/unstable/http/FetchHttpClient\";\nimport * as HttpClient from \"effect/unstable/http/HttpClient\";\nimport * as HttpClientRequest from \"effect/unstable/http/HttpClientRequest\";\nimport * as HttpApiClient from \"effect/unstable/httpapi/HttpApiClient\";\n\nimport * as ServerSecretStore from \"../auth/ServerSecretStore.ts\";\nimport {\n  PUBLISH_AGENT_ACTIVITY_SECRET,\n  RELAY_ENVIRONMENT_CREDENTIAL_SECRET,\n  RELAY_ISSUER_SECRET,\n  RELAY_URL_SECRET,\n} from \"../cloud/config.ts\";\nimport { getOrCreateEnvironmentKeyPairFromSecretStore } from \"../cloud/environmentKeys.ts\";\nimport * as ServerEnvironment from \"../environment/ServerEnvironment.ts\";\nimport * as OrchestrationEngine from \"../orchestration/Services/OrchestrationEngine.ts\";\nimport * as ProjectionSnapshotQuery from \"../orchestration/Services/ProjectionSnapshotQuery.ts\";\nimport { forkParked } from \"../serverActivation.ts\";\n\nexport class AgentAwarenessRelay extends Context.Service<\n  AgentAwarenessRelay,\n  {\n    readonly publishThread: (threadId: ThreadId) => Effect.Effect<void>;\n    readonly start: () => Effect.Effect<void, never, Scope.Scope>;\n  }\n>()(\"t3/relay/AgentAwarenessRelay\") {}\n\nexport function eventThreadId(event: OrchestrationEvent): ThreadId | null {\n  const payload = event.payload as { readonly threadId?: unknown };\n  if (typeof payload.threadId === \"string\") {\n    return payload.threadId as ThreadId;\n  }\n  if (event.aggregateKind === \"thread\" && typeof event.aggregateId === \"string\") {\n    return event.aggregateId as ThreadId;\n  }\n  return null;\n}\n\nexport function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boolean {\n  switch (event.type) {\n    case \"thread.message-sent\":\n    case \"thread.turn-start-requested\":\n      // These events express intent to start work, but the shell still contains\n      // the previous turn's terminal state until the provider acknowledges the\n      // new turn. Publishing that snapshot can queue a fresh \"Done\" alert just\n      // before the real running state arrives. Provider lifecycle events publish\n      // the authoritative starting/running state instead.\n      return false;\n    case \"thread.proposed-plan-upserted\":\n    case \"thread.runtime-mode-set\":\n    case \"thread.interaction-mode-set\":\n      return false;\n    case \"thread.activity-appended\":\n      return (\n        event.payload.activity.kind === \"approval.requested\" ||\n        event.payload.activity.kind === \"approval.resolved\" ||\n        event.payload.activity.kind === \"provider.approval.respond.failed\" ||\n        event.payload.activity.kind === \"user-input.requested\" ||\n        event.payload.activity.kind === \"user-input.resolved\" ||\n        event.payload.activity.kind === \"runtime.error\"\n      );\n    default:\n      return true;\n  }\n}\n\nexport function agentAwarenessPublishIdentity(state: RelayAgentActivityState | null): string {\n  if (state === null) {\n    return \"null\";\n  }\n  const { updatedAt: _updatedAt, ...meaningfulState } = state;\n  return JSON.stringify(meaningfulState);\n}\n\nexport function isAgentActivityPublishingEnabled(value: string | null): boolean {\n  return value === \"true\";\n}\n\nexport function resolveAgentActivityPublishingStartupState(input: {\n  readonly relayConfigured: boolean;\n  readonly publishEnabled: boolean;\n}): \"waiting-for-link\" | \"disabled\" | \"enabled\" {\n  if (!input.relayConfigured) {\n    return \"waiting-for-link\";\n  }\n  return input.publishEnabled ? \"enabled\" : \"disabled\";\n}\n\nconst RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH = 160;\nconst REDACTED_RELAY_AGENT_FAILURE_DETAIL = \"The agent run failed.\";\n\nexport function sanitizeRelayAgentActivityState(\n  state: RelayAgentActivityState | null,\n): RelayAgentActivityState | null {\n  if (state === null) {\n    return null;\n  }\n  const { detail: _detail, ...rest } = state;\n  const detail = (state.phase === \"failed\" ? REDACTED_RELAY_AGENT_FAILURE_DETAIL : state.detail)\n    ?.trim()\n    .slice(0, RELAY_AGENT_ACTIVITY_DETAIL_MAX_LENGTH)\n    .trim();\n  return detail ? { ...rest, detail } : rest;\n}\n\nfunction relayEnvironmentClient(token: string) {\n  return HttpClient.mapRequest(HttpClientRequest.setHeader(\"authorization\", `Bearer ${token}`));\n}\n\nfunction deliveryStats(\n  deliveries: ReadonlyArray<{\n    readonly ok: boolean;\n    readonly queued?: boolean | undefined;\n    readonly kind: string;\n    readonly apnsStatus?: number | null;\n    readonly apnsReason?: string | null;\n  }>,\n) {\n  let queued = 0;\n  let successful = 0;\n  let failed = 0;\n  const failedReasons: string[] = [];\n  const kinds = new Set<string>();\n\n  for (const delivery of deliveries) {\n    kinds.add(delivery.kind);\n    if (delivery.queued) {\n      queued += 1;\n      continue;\n    }\n    if (delivery.ok) {\n      successful += 1;\n      continue;\n    }\n    failed += 1;\n    failedReasons.push(`${delivery.apnsStatus ?? \"transport\"}:${delivery.apnsReason ?? \"unknown\"}`);\n  }\n\n  return {\n    total: deliveries.length,\n    queued,\n    successful,\n    failed,\n    kinds: [...kinds],\n    failedReasons,\n  };\n}\n\nexport function signRelayAgentActivityPublishProof(input: {\n  readonly privateKey: string;\n  readonly payload: RelayAgentActivityPublishProofPayload;\n}) {\n  return signRelayJwt({\n    privateKey: input.privateKey,\n    typ: RELAY_ACTIVITY_PUBLISH_TYP,\n    payload: input.payload,\n  });\n}\n\nconst makePublishProof = Effect.fn(\"makePublishProof\")(function* (input: {\n  readonly privateKey: string;\n  readonly relayIssuer: string;\n  readonly environmentId: string;\n  readonly threadId: ThreadId;\n  readonly state: RelayAgentActivityState | null;\n  readonly jti: string;\n}) {\n  const now = yield* DateTime.now;\n  const expiresAt = DateTime.add(now, { minutes: 5 });\n  const payload = {\n    iss: `t3-env:${input.environmentId}`,\n    aud: normalizeRelayIssuer(input.relayIssuer),\n    sub: input.environmentId,\n    jti: input.jti,\n    iat: Math.floor(now.epochMilliseconds / 1_000),\n    exp: Math.floor(expiresAt.epochMilliseconds / 1_000),\n    environmentId: input.environmentId as RelayAgentActivityPublishProofPayload[\"environmentId\"],\n    threadId: input.threadId,\n    state: input.state,\n  } satisfies RelayAgentActivityPublishProofPayload;\n  return yield* signRelayAgentActivityPublishProof({ privateKey: input.privateKey, payload });\n});\n\n// Compact, log-safe view of the fields the awareness phase ladder reads.\nexport function describeThreadShellForAwareness(\n  thread: Option.Option<OrchestrationThreadShell>,\n): Record<string, unknown> {\n  if (Option.isNone(thread)) {\n    return { found: false };\n  }\n  const shell = thread.value;\n  return {\n    found: true,\n    sessionStatus: shell.session?.status ?? null,\n    sessionActiveTurnId: shell.session?.activeTurnId ?? null,\n    latestTurnId: shell.latestTurn?.turnId ?? null,\n    latestTurnState: shell.latestTurn?.state ?? null,\n    latestTurnCompletedAt: shell.latestTurn?.completedAt ?? null,\n    hasPendingApprovals: shell.hasPendingApprovals,\n    hasPendingUserInput: shell.hasPendingUserInput,\n  };\n}\n\nexport function resolveAgentAwarenessRelayPublishSnapshot(input: {\n  readonly environmentId: EnvironmentId;\n  readonly threadId: ThreadId;\n  readonly thread: Option.Option<OrchestrationThreadShell>;\n  readonly project: Option.Option<OrchestrationProjectShell>;\n}): {\n  readonly projectId: string | null;\n  readonly state: RelayAgentActivityState | null;\n  readonly reason: \"snapshot\" | \"thread-not-found\" | \"project-not-found\";\n} {\n  if (Option.isNone(input.thread)) {\n    return {\n      projectId: null,\n      state: null,\n      reason: \"thread-not-found\",\n    };\n  }\n  if (Option.isNone(input.project)) {\n    return {\n      projectId: input.thread.value.projectId,\n      state: null,\n      reason: \"project-not-found\",\n    };\n  }\n  return {\n    projectId: input.thread.value.projectId,\n    state: sanitizeRelayAgentActivityState(\n      projectThreadAwareness({\n        environmentId: input.environmentId,\n        project: input.project.value,\n        thread: input.thread.value,\n      }),\n    ),\n    reason: \"snapshot\",\n  };\n}\n\nexport function resolveAgentAwarenessRelayActiveThreadIds(input: {\n  readonly environmentId: EnvironmentId;\n  readonly projects: ReadonlyArray<Pick<OrchestrationProjectShell, \"id\" | \"title\">>;\n  readonly threads: ReadonlyArray<OrchestrationThreadShell>;\n}): ReadonlyArray<ThreadId> {\n  const projectById = new Map(input.projects.map((project) => [project.id, project]));\n  return input.threads\n    .filter((thread) => {\n      const project = projectById.get(thread.projectId);\n      if (!project) {\n        return false;\n      }\n      return (\n        projectThreadAwareness({\n          environmentId: input.environmentId,\n          project,\n          thread,\n        }) !== null\n      );\n    })\n    .map((thread) => thread.id);\n}\n\nexport const make = Effect.gen(function* () {\n  const secrets = yield* ServerSecretStore.ServerSecretStore;\n  const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;\n  const snapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;\n  const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;\n  const crypto = yield* Crypto.Crypto;\n  const cloudLinkKeyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(secrets);\n  const activeSnapshotPublishedRef = yield* Ref.make(false);\n  const publishedStateByThreadRef = yield* Ref.make(new Map<ThreadId, string>());\n\n  const readSecretString = (name: string) =>\n    secrets\n      .get(name)\n      .pipe(\n        Effect.map((bytes) =>\n          Option.isSome(bytes) ? new TextDecoder().decode(bytes.value) : null,\n        ),\n      );\n\n  const readRelayConfig = Effect.gen(function* () {\n    const [url, issuer, environmentCredential] = yield* Effect.all([\n      readSecretString(RELAY_URL_SECRET),\n      readSecretString(RELAY_ISSUER_SECRET),\n      readSecretString(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),\n    ]);\n    return url && environmentCredential\n      ? { url, issuer: issuer ?? url, environmentCredential }\n      : null;\n  });\n\n  const readPublishAgentActivityEnabled = readSecretString(PUBLISH_AGENT_ACTIVITY_SECRET).pipe(\n    Effect.map(isAgentActivityPublishingEnabled),\n  );\n\n  const makeRelayClient = (relayConfig: {\n    readonly url: string;\n    readonly environmentCredential: string;\n  }) =>\n    HttpApiClient.make(RelayApi, {\n      baseUrl: relayConfig.url,\n      transformClient: relayEnvironmentClient(relayConfig.environmentCredential),\n    }).pipe(Effect.provide(FetchHttpClient.layer));\n\n  // Deadlines for publishes that need confirmation (tombstones and\n  // first-state completions). The confirming publish is re-enqueued through\n  // the same drainable worker as every other publish, so a confirmed\n  // tombstone can never race an in-flight live update; a recovered state\n  // clears the deadline. Assigned after the worker exists.\n  const publishConfirmDeadlines = new Map<ThreadId, number>();\n  let schedulePublishConfirm: (threadId: ThreadId) => Effect.Effect<void> = () => Effect.void;\n\n  const publishThreadUnsafe = Effect.fn(\"publishThreadUnsafe\")(function* (threadId: ThreadId) {\n    const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(\n      Effect.orElseSucceed(() => false),\n    );\n    if (!publishAgentActivity) {\n      yield* Effect.logDebug(\"agent activity publish skipped; publication disabled\", {\n        threadId,\n      });\n      return;\n    }\n    const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));\n    if (!relayConfig) {\n      yield* Effect.logDebug(\"agent activity publish skipped; relay link credentials unavailable\", {\n        threadId,\n      });\n      return;\n    }\n    const relayClient = yield* makeRelayClient(relayConfig);\n    const environmentId = yield* serverEnvironment.getEnvironmentId;\n\n    const publishState = (input: {\n      readonly projectId: string | null;\n      readonly state: RelayAgentActivityState | null;\n      readonly reason: string;\n    }) =>\n      Effect.gen(function* () {\n        const proof = yield* makePublishProof({\n          privateKey: cloudLinkKeyPair.privateKey,\n          relayIssuer: relayConfig.issuer,\n          environmentId,\n          threadId,\n          state: input.state,\n          jti: yield* crypto.randomUUIDv4,\n        });\n\n        yield* Effect.logInfo(\"publishing agent activity for thread\", {\n          environmentId,\n          threadId,\n          projectId: input.projectId,\n          statePhase: input.state?.phase ?? null,\n          hasState: input.state !== null,\n          reason: input.reason,\n        });\n\n        const response = yield* relayClient.server.publishAgentActivity({\n          params: {\n            environmentId,\n            threadId,\n          },\n          payload: {\n            state: input.state,\n            proof,\n          },\n        });\n\n        yield* Effect.logInfo(\"agent activity publish completed\", {\n          environmentId,\n          threadId,\n          ok: response.ok,\n          deliveries: deliveryStats(response.deliveries),\n        });\n      });\n\n    const thread = yield* snapshotQuery.getThreadShellById(threadId);\n    const project = Option.isSome(thread)\n      ? yield* snapshotQuery.getProjectShellById(thread.value.projectId)\n      : Option.none<OrchestrationProjectShell>();\n    const snapshot = resolveAgentAwarenessRelayPublishSnapshot({\n      environmentId,\n      threadId,\n      thread,\n      project,\n    });\n    const publishIdentity = agentAwarenessPublishIdentity(snapshot.state);\n    const publishedStateByThread = yield* Ref.get(publishedStateByThreadRef);\n    if (publishedStateByThread.get(threadId) === publishIdentity) {\n      // The projection is back at (or never left) the last published state, so\n      // any pending deferred confirmation is moot. Leaving the deadline in\n      // place would let a much later transient null find it already expired\n      // and publish a tombstone immediately, skipping the deferral window.\n      publishConfirmDeadlines.delete(threadId);\n      yield* Effect.logDebug(\"agent activity publish skipped; projected state unchanged\", {\n        environmentId,\n        threadId,\n        reason: snapshot.reason,\n      });\n      return;\n    }\n\n    // Two projections need confirmation before publishing, because both can\n    // appear transiently while the projector is mid-write and publishing them\n    // immediately is destructive or noisy:\n    // - null (tombstone) while the previous published state was live: deletes\n    //   the thread from every armed card mid-conversation.\n    // - completed as the thread's FIRST published state: sessions boot at\n    //   \"ready\" before their first turn, which projects as completed for an\n    //   instant and sends a spurious Done notification at thread birth.\n    // Defer, schedule a re-publish through the ordinary worker queue, and\n    // only publish if the projection still holds when it drains.\n    const requiresConfirmation =\n      (snapshot.state === null &&\n        publishedStateByThread.get(threadId) !== agentAwarenessPublishIdentity(null)) ||\n      (snapshot.state?.phase === \"completed\" && !publishedStateByThread.has(threadId));\n    if (requiresConfirmation) {\n      const nowMs = (yield* DateTime.now).epochMilliseconds;\n      const deadline = publishConfirmDeadlines.get(threadId);\n      if (deadline === undefined) {\n        publishConfirmDeadlines.set(threadId, nowMs + 5_000);\n        yield* Effect.logInfo(\"agent activity publish deferred pending confirmation\", {\n          environmentId,\n          threadId,\n          reason: snapshot.reason,\n          statePhase: snapshot.state?.phase ?? null,\n          shell: describeThreadShellForAwareness(thread),\n        });\n        yield* schedulePublishConfirm(threadId);\n        return;\n      }\n      if (nowMs < deadline) {\n        return;\n      }\n      publishConfirmDeadlines.delete(threadId);\n      yield* Effect.logInfo(\"agent activity deferred publish confirmed\", {\n        environmentId,\n        threadId,\n        reason: snapshot.reason,\n        statePhase: snapshot.state?.phase ?? null,\n        shell: describeThreadShellForAwareness(thread),\n      });\n    } else {\n      publishConfirmDeadlines.delete(threadId);\n    }\n\n    if (snapshot.reason === \"thread-not-found\") {\n      yield* Effect.logDebug(\"publishing agent activity tombstone; thread not found\", {\n        environmentId,\n        threadId,\n      });\n    } else if (snapshot.reason === \"project-not-found\") {\n      yield* Effect.logDebug(\"publishing agent activity tombstone; project not found\", {\n        environmentId,\n        threadId,\n        projectId: snapshot.projectId,\n      });\n    }\n\n    yield* publishState({\n      projectId: snapshot.projectId,\n      state: snapshot.state,\n      reason: snapshot.reason,\n    });\n    yield* Ref.update(publishedStateByThreadRef, (publishedStates) => {\n      const nextPublishedStates = new Map(publishedStates);\n      nextPublishedStates.set(threadId, publishIdentity);\n      return nextPublishedStates;\n    });\n  });\n\n  const publishThread: AgentAwarenessRelay[\"Service\"][\"publishThread\"] = (threadId) =>\n    publishThreadUnsafe(threadId).pipe(\n      Effect.catchCause((cause) => {\n        return Effect.logWarning(\"agent activity publish failed\", {\n          threadId,\n          cause: Cause.pretty(cause),\n        });\n      }),\n      Effect.withSpan(\"AgentAwarenessRelay.publishThread\"),\n      withRelayClientTracing,\n    );\n\n  const publishActiveThreadsUnsafe = Effect.gen(function* () {\n    const publishAgentActivity = yield* readPublishAgentActivityEnabled.pipe(\n      Effect.orElseSucceed(() => false),\n    );\n    if (!publishAgentActivity) {\n      yield* Effect.logDebug(\"agent activity snapshot skipped; publication disabled\");\n      return false;\n    }\n    const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));\n    if (!relayConfig) {\n      yield* Effect.logDebug(\"agent activity snapshot skipped; relay link credentials unavailable\");\n      return false;\n    }\n    const environmentId = yield* serverEnvironment.getEnvironmentId;\n    const snapshot = yield* snapshotQuery.getShellSnapshot();\n    const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({\n      environmentId,\n      projects: snapshot.projects,\n      threads: snapshot.threads,\n    });\n    if (activeThreadIds.length === 0) {\n      yield* Effect.logDebug(\"agent activity snapshot has no publishable threads\");\n      return true;\n    }\n    yield* Effect.logInfo(\"publishing active agent activity snapshot\", {\n      count: activeThreadIds.length,\n    });\n    yield* Effect.forEach(activeThreadIds, publishThread, { concurrency: 4, discard: true });\n    return true;\n  });\n\n  const publishActiveThreadsOnceWhenConfigured = (logEnabledWhenReady: boolean) =>\n    Effect.gen(function* () {\n      while (!(yield* Ref.get(activeSnapshotPublishedRef))) {\n        const published = yield* publishActiveThreadsUnsafe.pipe(Effect.orElseSucceed(() => false));\n        if (published) {\n          yield* Ref.set(activeSnapshotPublishedRef, true);\n          if (logEnabledWhenReady) {\n            const relayConfig = yield* readRelayConfig.pipe(Effect.orElseSucceed(() => null));\n            yield* Effect.logInfo(\"agent activity publishing enabled after link reconciliation\", {\n              relayUrl: relayConfig?.url,\n            });\n          }\n          return;\n        }\n        yield* Effect.sleep(\"5 seconds\");\n      }\n    });\n\n  const worker = yield* makeDrainableWorker(publishThread);\n\n  schedulePublishConfirm = (threadId) =>\n    Effect.forkDetach(\n      Effect.sleep(\"5 seconds\").pipe(\n        Effect.andThen(worker.enqueue(threadId)),\n        Effect.catchCause((cause) =>\n          Effect.logWarning(\"deferred agent activity confirmation failed\", {\n            threadId,\n            cause: Cause.pretty(cause),\n          }),\n        ),\n      ),\n    ).pipe(Effect.asVoid);\n\n  const start: AgentAwarenessRelay[\"Service\"][\"start\"] = Effect.fn(\"AgentAwarenessRelay.start\")(\n    function* () {\n      const [relayConfig, publishEnabled] = yield* Effect.all([\n        readRelayConfig.pipe(Effect.orElseSucceed(() => null)),\n        readPublishAgentActivityEnabled.pipe(Effect.orElseSucceed(() => false)),\n      ]);\n      const startupState = resolveAgentActivityPublishingStartupState({\n        relayConfigured: relayConfig !== null,\n        publishEnabled,\n      });\n      switch (startupState) {\n        case \"waiting-for-link\":\n          yield* Effect.logInfo(\n            \"agent activity publishing standby; waiting for T3 Connect link reconciliation\",\n          );\n          break;\n        case \"disabled\":\n          yield* Effect.logInfo(\"agent activity publishing disabled by T3 Connect configuration\");\n          break;\n        case \"enabled\":\n          yield* Effect.logInfo(\"agent activity publishing enabled\", {\n            relayUrl: relayConfig?.url,\n          });\n          break;\n      }\n      yield* forkParked(\n        Effect.sleep(\"1 second\").pipe(\n          Effect.andThen(publishActiveThreadsOnceWhenConfigured(startupState !== \"enabled\")),\n        ),\n      );\n      yield* forkParked(\n        Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {\n          const threadId = eventThreadId(event);\n          if (threadId === null) {\n            return Effect.logDebug(\"agent activity publishing ignored event without thread id\", {\n              eventType: event.type,\n            });\n          }\n          if (!shouldPublishAgentAwarenessEvent(event)) {\n            return Effect.logDebug(\n              \"agent activity publishing ignored event without activity changes\",\n              {\n                eventType: event.type,\n                threadId,\n              },\n            );\n          }\n          return Effect.logDebug(\"agent activity publishing queued thread publish\", {\n            eventType: event.type,\n            threadId,\n          }).pipe(Effect.andThen(worker.enqueue(threadId)));\n        }),\n      );\n    },\n  );\n\n  return AgentAwarenessRelay.of({\n    publishThread,\n    start,\n  });\n});\n\nexport const layer = Layer.effect(AgentAwarenessRelay, make);\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\n\nimport {\n  OrchestrationReactor,\n  type OrchestrationReactorShape,\n} from \"../Services/OrchestrationReactor.ts\";\nimport { CheckpointReactor } from \"../Services/CheckpointReactor.ts\";\nimport { ProviderCommandReactor } from \"../Services/ProviderCommandReactor.ts\";\nimport { ProviderRuntimeIngestionService } from \"../Services/ProviderRuntimeIngestion.ts\";\nimport { ThreadDeletionReactor } from \"../Services/ThreadDeletionReactor.ts\";\nimport * as AgentAwarenessRelay from \"../../relay/AgentAwarenessRelay.ts\";\n\nexport const makeOrchestrationReactor = Effect.gen(function* () {\n  const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;\n  const providerCommandReactor = yield* ProviderCommandReactor;\n  const checkpointReactor = yield* CheckpointReactor;\n  const threadDeletionReactor = yield* ThreadDeletionReactor;\n  const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;\n\n  const start: OrchestrationReactorShape[\"start\"] = Effect.fn(\"start\")(function* () {\n    yield* providerRuntimeIngestion.start();\n    yield* providerCommandReactor.start();\n    yield* checkpointReactor.start();\n    yield* threadDeletionReactor.start();\n    yield* agentAwarenessRelay.start();\n  });\n\n  return {\n    start,\n  } satisfies OrchestrationReactorShape;\n});\n\nexport const OrchestrationReactorLive = Layer.effect(\n  OrchestrationReactor,\n  makeOrchestrationReactor,\n);\n","/**\n * RuntimeReceiptBus - Internal checkpoint-reactor synchronization receipts.\n *\n * This service exists to expose short-lived orchestration milestones that are\n * useful in tests and harnesses but are not part of the production runtime\n * event model. `CheckpointReactor` publishes receipts such as baseline capture,\n * diff finalization, and turn-processing quiescence so integration tests can\n * wait for those exact points without inferring them indirectly from persisted\n * state.\n *\n * Production code should only call `publish`. Test code may subscribe via\n * `streamEventsForTest`, which is intentionally named to make the intended\n * usage explicit.\n *\n * @module RuntimeReceiptBus\n */\nimport { CheckpointRef, IsoDateTime, NonNegativeInt, ThreadId, TurnId } from \"@t3tools/contracts\";\nimport * as Schema from \"effect/Schema\";\nimport * as Context from \"effect/Context\";\nimport type * as Effect from \"effect/Effect\";\nimport type * as Stream from \"effect/Stream\";\n\nexport const CheckpointBaselineCapturedReceipt = Schema.Struct({\n  type: Schema.Literal(\"checkpoint.baseline.captured\"),\n  threadId: ThreadId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  createdAt: IsoDateTime,\n});\nexport type CheckpointBaselineCapturedReceipt = typeof CheckpointBaselineCapturedReceipt.Type;\n\nexport const CheckpointDiffFinalizedReceipt = Schema.Struct({\n  type: Schema.Literal(\"checkpoint.diff.finalized\"),\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  checkpointRef: CheckpointRef,\n  status: Schema.Literals([\"ready\", \"missing\", \"error\"]),\n  createdAt: IsoDateTime,\n});\nexport type CheckpointDiffFinalizedReceipt = typeof CheckpointDiffFinalizedReceipt.Type;\n\nexport const TurnProcessingQuiescedReceipt = Schema.Struct({\n  type: Schema.Literal(\"turn.processing.quiesced\"),\n  threadId: ThreadId,\n  turnId: TurnId,\n  checkpointTurnCount: NonNegativeInt,\n  createdAt: IsoDateTime,\n});\nexport type TurnProcessingQuiescedReceipt = typeof TurnProcessingQuiescedReceipt.Type;\n\nexport const OrchestrationRuntimeReceipt = Schema.Union([\n  CheckpointBaselineCapturedReceipt,\n  CheckpointDiffFinalizedReceipt,\n  TurnProcessingQuiescedReceipt,\n]);\nexport type OrchestrationRuntimeReceipt = typeof OrchestrationRuntimeReceipt.Type;\n\nexport interface RuntimeReceiptBusShape {\n  readonly publish: (receipt: OrchestrationRuntimeReceipt) => Effect.Effect<void>;\n  readonly streamEventsForTest: Stream.Stream<OrchestrationRuntimeReceipt>;\n}\n\nexport class RuntimeReceiptBus extends Context.Service<RuntimeReceiptBus, RuntimeReceiptBusShape>()(\n  \"t3/orchestration/Services/RuntimeReceiptBus\",\n) {}\n","/**\n * RuntimeReceiptBus layers.\n *\n * `RuntimeReceiptBusLive` is the production default and intentionally does not\n * retain or broadcast receipts. `RuntimeReceiptBusTest` installs the in-memory\n * PubSub-backed implementation used by integration tests that need to await\n * checkpoint-reactor milestones precisely.\n *\n * @module RuntimeReceiptBus\n */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Stream from \"effect/Stream\";\n\nimport {\n  RuntimeReceiptBus,\n  type RuntimeReceiptBusShape,\n  type OrchestrationRuntimeReceipt,\n} from \"../Services/RuntimeReceiptBus.ts\";\n\nconst makeRuntimeReceiptBus = Effect.succeed({\n  publish: () => Effect.void,\n  streamEventsForTest: Stream.empty,\n} satisfies RuntimeReceiptBusShape);\n\nconst makeRuntimeReceiptBusTest = Effect.gen(function* () {\n  const pubSub = yield* PubSub.unbounded<OrchestrationRuntimeReceipt>();\n\n  return {\n    publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),\n    get streamEventsForTest() {\n      return Stream.fromPubSub(pubSub);\n    },\n  } satisfies RuntimeReceiptBusShape;\n});\n\nexport const RuntimeReceiptBusLive = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBus);\nexport const RuntimeReceiptBusTest = Layer.effect(RuntimeReceiptBus, makeRuntimeReceiptBusTest);\n","// @effect-diagnostics nodeBuiltinImport:off\nimport * as NodeFS from \"node:fs\";\nimport * as NodePath from \"node:path\";\n\nexport function isGitRepository(cwd: string): boolean {\n  return NodeFS.existsSync(NodePath.join(cwd, \".git\"));\n}\n","import {\n  ApprovalRequestId,\n  type AssistantDeliveryMode,\n  CommandId,\n  MessageId,\n  type OrchestrationEvent,\n  type OrchestrationMessage,\n  type OrchestrationProposedPlanId,\n  CheckpointRef,\n  classifyTaskAgentKind,\n  EventId,\n  isToolLifecycleItemType,\n  ThreadId,\n  type ThreadTokenUsageSnapshot,\n  TurnId,\n  type OrchestrationCheckpointSummary,\n  type OrchestrationProposedPlan,\n  type OrchestrationThread,\n  type OrchestrationThreadActivity,\n  type ProviderRuntimeEvent,\n} from \"@t3tools/contracts\";\nimport * as Cache from \"effect/Cache\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Stream from \"effect/Stream\";\nimport { makeDrainableWorker } from \"@t3tools/shared/DrainableWorker\";\n\nimport { ProviderService } from \"../../provider/Services/ProviderService.ts\";\nimport { ProjectionTurnRepository } from \"../../persistence/Services/ProjectionTurns.ts\";\nimport { ProjectionTurnRepositoryLive } from \"../../persistence/Layers/ProjectionTurns.ts\";\nimport { isGitRepository } from \"../../git/Utils.ts\";\nimport { OrchestrationEngineService } from \"../Services/OrchestrationEngine.ts\";\nimport { ThreadBackgroundLivenessService } from \"../ThreadBackgroundLiveness.ts\";\nimport { ThreadPlanProgressService } from \"../ThreadPlanProgress.ts\";\nimport { ProjectionSnapshotQuery } from \"../Services/ProjectionSnapshotQuery.ts\";\nimport {\n  ProviderRuntimeIngestionService,\n  type ProviderRuntimeIngestionShape,\n} from \"../Services/ProviderRuntimeIngestion.ts\";\nimport { forkParked } from \"../../serverActivation.ts\";\nimport { ServerSettingsService } from \"../../serverSettings.ts\";\n\nconst providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;\nconst providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;\n\n// Fallback when the in-memory description cache no longer has the task name\n// (server restart, session-exit sweep, TTL/capacity eviction): earlier\n// task.started/task.progress activities for the task are persisted with it.\nfunction findTaskTitleInActivities(\n  activities: ReadonlyArray<OrchestrationThreadActivity> | undefined,\n  taskId: string,\n): string | undefined {\n  if (!activities) {\n    return undefined;\n  }\n  for (let index = activities.length - 1; index >= 0; index -= 1) {\n    const activity = activities[index];\n    if (!activity || (activity.kind !== \"task.started\" && activity.kind !== \"task.progress\")) {\n      continue;\n    }\n    const payload =\n      activity.payload && typeof activity.payload === \"object\"\n        ? (activity.payload as { taskId?: unknown; title?: unknown; detail?: unknown })\n        : undefined;\n    if (payload?.taskId !== taskId) {\n      continue;\n    }\n    const title =\n      typeof payload.title === \"string\"\n        ? payload.title\n        : activity.kind === \"task.started\" && typeof payload.detail === \"string\"\n          ? payload.detail\n          : undefined;\n    if (title && title.trim().length > 0) {\n      return title;\n    }\n  }\n  return undefined;\n}\n\ninterface AssistantSegmentState {\n  baseKey: string;\n  nextSegmentIndex: number;\n  activeMessageId: MessageId | null;\n}\n\nconst TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;\nconst TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);\nconst BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;\nconst BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);\nconst BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY = 10_000;\nconst BUFFERED_PROPOSED_PLAN_BY_ID_TTL = Duration.minutes(120);\nconst TASK_DESCRIPTION_BY_TASK_CACHE_CAPACITY = 10_000;\nconst TASK_DESCRIPTION_BY_TASK_TTL = Duration.minutes(120);\nconst MAX_BUFFERED_ASSISTANT_CHARS = 24_000;\nconst STRICT_PROVIDER_LIFECYCLE_GUARD =\n  process.env.SYNAPTIC_STRICT_PROVIDER_LIFECYCLE_GUARD !== \"0\";\n\ntype TurnStartRequestedDomainEvent = Extract<\n  OrchestrationEvent,\n  { type: \"thread.turn-start-requested\" }\n>;\n\ntype RuntimeIngestionInput =\n  | {\n      source: \"runtime\";\n      event: ProviderRuntimeEvent;\n    }\n  | {\n      source: \"domain\";\n      event: TurnStartRequestedDomainEvent;\n    };\n\nfunction toTurnId(value: TurnId | string | undefined): TurnId | undefined {\n  return value === undefined ? undefined : TurnId.make(String(value));\n}\n\nfunction toApprovalRequestId(value: string | undefined): ApprovalRequestId | undefined {\n  return value === undefined ? undefined : ApprovalRequestId.make(value);\n}\n\nfunction sameId(left: string | null | undefined, right: string | null | undefined): boolean {\n  if (left === null || left === undefined || right === null || right === undefined) {\n    return false;\n  }\n  return left === right;\n}\n\nfunction hasAssistantMessageForTurn(\n  messages: ReadonlyArray<OrchestrationMessage>,\n  turnId: TurnId,\n  options?: { readonly streamingOnly?: boolean },\n): boolean {\n  for (let index = 0; index < messages.length; index += 1) {\n    const message = messages[index];\n    if (!message) {\n      continue;\n    }\n    if (message.role !== \"assistant\" || message.turnId !== turnId) {\n      continue;\n    }\n    if (options?.streamingOnly === true && !message.streaming) {\n      continue;\n    }\n    return true;\n  }\n  return false;\n}\n\nfunction findMessageById(\n  messages: ReadonlyArray<OrchestrationMessage>,\n  messageId: MessageId,\n): OrchestrationMessage | undefined {\n  for (let index = 0; index < messages.length; index += 1) {\n    const message = messages[index];\n    if (message?.id === messageId) {\n      return message;\n    }\n  }\n  return undefined;\n}\n\nfunction findProposedPlanById(\n  proposedPlans: ReadonlyArray<\n    Pick<OrchestrationProposedPlan, \"id\" | \"createdAt\" | \"implementedAt\" | \"implementationThreadId\">\n  >,\n  planId: string,\n):\n  | Pick<OrchestrationProposedPlan, \"id\" | \"createdAt\" | \"implementedAt\" | \"implementationThreadId\">\n  | undefined {\n  for (let index = 0; index < proposedPlans.length; index += 1) {\n    const proposedPlan = proposedPlans[index];\n    if (proposedPlan?.id === planId) {\n      return proposedPlan;\n    }\n  }\n  return undefined;\n}\n\nfunction hasCheckpointForTurn(\n  checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,\n  turnId: TurnId,\n): boolean {\n  for (let index = 0; index < checkpoints.length; index += 1) {\n    if (checkpoints[index]?.turnId === turnId) {\n      return true;\n    }\n  }\n  return false;\n}\n\nfunction maxCheckpointTurnCount(\n  checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,\n): number {\n  let maxTurnCount = 0;\n  for (let index = 0; index < checkpoints.length; index += 1) {\n    const checkpoint = checkpoints[index];\n    if (checkpoint && checkpoint.checkpointTurnCount > maxTurnCount) {\n      maxTurnCount = checkpoint.checkpointTurnCount;\n    }\n  }\n  return maxTurnCount;\n}\n\nfunction truncateDetail(value: string, limit = 180): string {\n  return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;\n}\n\nfunction normalizeProposedPlanMarkdown(planMarkdown: string | undefined): string | undefined {\n  const trimmed = planMarkdown?.trim();\n  if (!trimmed) {\n    return undefined;\n  }\n  return trimmed;\n}\n\nfunction hasRenderableAssistantText(text: string | undefined): boolean {\n  return (text?.trim().length ?? 0) > 0;\n}\n\nfunction proposedPlanIdForTurn(threadId: ThreadId, turnId: TurnId): string {\n  return `plan:${threadId}:turn:${turnId}`;\n}\n\nfunction proposedPlanIdFromEvent(event: ProviderRuntimeEvent, threadId: ThreadId): string {\n  const turnId = toTurnId(event.turnId);\n  if (turnId) {\n    return proposedPlanIdForTurn(threadId, turnId);\n  }\n  if (event.itemId) {\n    return `plan:${threadId}:item:${event.itemId}`;\n  }\n  return `plan:${threadId}:event:${event.eventId}`;\n}\n\nfunction assistantSegmentBaseKeyFromEvent(event: ProviderRuntimeEvent): string {\n  return String(event.itemId ?? event.turnId ?? event.eventId);\n}\n\nfunction assistantSegmentMessageId(baseKey: string, segmentIndex: number): MessageId {\n  return MessageId.make(\n    segmentIndex === 0 ? `assistant:${baseKey}` : `assistant:${baseKey}:segment:${segmentIndex}`,\n  );\n}\nfunction buildContextWindowActivityPayload(\n  event: ProviderRuntimeEvent,\n): ThreadTokenUsageSnapshot | undefined {\n  if (event.type !== \"thread.token-usage.updated\" || event.payload.usage.usedTokens <= 0) {\n    return undefined;\n  }\n  return event.payload.usage;\n}\n\nfunction normalizeRuntimeTurnState(\n  value: string | undefined,\n): \"completed\" | \"failed\" | \"interrupted\" | \"cancelled\" {\n  switch (value) {\n    case \"failed\":\n    case \"interrupted\":\n    case \"cancelled\":\n    case \"completed\":\n      return value;\n    default:\n      return \"completed\";\n  }\n}\n\nfunction orchestrationSessionStatusFromRuntimeState(\n  state: \"starting\" | \"running\" | \"waiting\" | \"ready\" | \"interrupted\" | \"stopped\" | \"error\",\n): \"starting\" | \"running\" | \"ready\" | \"interrupted\" | \"stopped\" | \"error\" {\n  switch (state) {\n    case \"starting\":\n      return \"starting\";\n    case \"running\":\n    case \"waiting\":\n      return \"running\";\n    case \"ready\":\n      return \"ready\";\n    case \"interrupted\":\n      return \"interrupted\";\n    case \"stopped\":\n      return \"stopped\";\n    case \"error\":\n      return \"error\";\n  }\n}\n\nfunction sessionStatusAllowsActiveTurn(\n  status: ReturnType<typeof orchestrationSessionStatusFromRuntimeState>,\n): boolean {\n  return status === \"starting\" || status === \"running\";\n}\n\nfunction requestKindFromCanonicalRequestType(\n  requestType: string | undefined,\n): \"command\" | \"file-read\" | \"file-change\" | undefined {\n  switch (requestType) {\n    case \"command_execution_approval\":\n    case \"exec_command_approval\":\n      return \"command\";\n    case \"file_read_approval\":\n      return \"file-read\";\n    case \"file_change_approval\":\n    case \"apply_patch_approval\":\n      return \"file-change\";\n    default:\n      return undefined;\n  }\n}\n\n/**\n * Copies the optional TaskAgentLinkage bundle from a task.* runtime payload\n * into the persisted activity payload. Identity fields ride on every row so\n * client folds survive activity retention; absent fields stay absent.\n */\nfunction taskLinkageActivityFields(payload: Record<string, unknown>): Record<string, unknown> {\n  const fields: Record<string, unknown> = {\n    // Server-stamped classification: persisted rows are self-describing, so\n    // clients trust the stamp instead of re-deriving agent-vs-background\n    // from taskType denylists and marker heuristics (legacy rows without a\n    // stamp keep the client fallback).\n    agentKind: classifyTaskAgentKind({\n      taskType: typeof payload.taskType === \"string\" ? payload.taskType : undefined,\n      agentId: typeof payload.agentId === \"string\" ? payload.agentId : undefined,\n    }),\n  };\n  for (const key of [\n    \"taskType\",\n    \"agentId\",\n    \"title\",\n    \"role\",\n    \"model\",\n    \"effort\",\n    \"toolUseId\",\n    \"parentAgentId\",\n    \"workflowName\",\n    \"agentIndex\",\n    \"phaseIndex\",\n    \"phaseTitle\",\n    \"phases\",\n    \"attempt\",\n    \"runHandles\",\n    \"outputFile\",\n    \"agentPath\",\n    \"timelineBypass\",\n    \"typedUsage\",\n    \"status\",\n    \"error\",\n  ] as const) {\n    if (payload[key] !== undefined) {\n      fields[key] = payload[key];\n    }\n  }\n  return fields;\n}\n\nexport function runtimeEventToActivities(\n  event: ProviderRuntimeEvent,\n  taskTitle?: string,\n): ReadonlyArray<OrchestrationThreadActivity> {\n  const maybeSequence = (() => {\n    const eventWithSequence = event as ProviderRuntimeEvent & { sessionSequence?: number };\n    return eventWithSequence.sessionSequence !== undefined\n      ? { sequence: eventWithSequence.sessionSequence }\n      : {};\n  })();\n  switch (event.type) {\n    case \"request.opened\": {\n      if (event.payload.requestType === \"tool_user_input\") {\n        return [];\n      }\n      const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType);\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"approval\",\n          kind: \"approval.requested\",\n          summary:\n            requestKind === \"command\"\n              ? \"Command approval requested\"\n              : requestKind === \"file-read\"\n                ? \"File-read approval requested\"\n                : requestKind === \"file-change\"\n                  ? \"File-change approval requested\"\n                  : \"Approval requested\",\n          payload: {\n            requestId: toApprovalRequestId(event.requestId),\n            ...(requestKind ? { requestKind } : {}),\n            requestType: event.payload.requestType,\n            ...(event.payload.detail ? { detail: event.payload.detail } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"request.resolved\": {\n      if (event.payload.requestType === \"tool_user_input\") {\n        return [];\n      }\n      const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType);\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"approval\",\n          kind: \"approval.resolved\",\n          summary: \"Approval resolved\",\n          payload: {\n            requestId: toApprovalRequestId(event.requestId),\n            ...(requestKind ? { requestKind } : {}),\n            requestType: event.payload.requestType,\n            ...(event.payload.decision ? { decision: event.payload.decision } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"runtime.error\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"error\",\n          kind: \"runtime.error\",\n          summary: \"Runtime error\",\n          payload: {\n            message: truncateDetail(event.payload.message),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"tool.denied\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"error\",\n          kind: \"tool.denied\",\n          summary: `Tool denied: ${event.payload.toolName}`,\n          payload: {\n            toolName: event.payload.toolName,\n            ...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),\n            ...(event.payload.reason ? { detail: truncateDetail(event.payload.reason) } : {}),\n            ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"runtime.warning\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"runtime.warning\",\n          // Use the adapter-supplied message as the row label so the work log\n          // shows what the warning was about, not a generic \"Runtime warning\".\n          summary: truncateDetail(event.payload.message, 120),\n          payload: {\n            message: truncateDetail(event.payload.message),\n            ...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"turn.plan.updated\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"turn.plan.updated\",\n          summary: \"Plan updated\",\n          payload: {\n            plan: event.payload.plan,\n            ...(event.payload.explanation !== undefined\n              ? { explanation: event.payload.explanation }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"user-input.requested\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"user-input.requested\",\n          summary: \"User input requested\",\n          payload: {\n            ...(event.requestId ? { requestId: event.requestId } : {}),\n            questions: event.payload.questions,\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"user-input.resolved\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"user-input.resolved\",\n          summary: \"User input submitted\",\n          payload: {\n            ...(event.requestId ? { requestId: event.requestId } : {}),\n            answers: event.payload.answers,\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"task.started\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"task.started\",\n          summary:\n            event.payload.taskType === \"plan\"\n              ? \"Plan task started\"\n              : event.payload.taskType\n                ? `${event.payload.taskType} task started`\n                : \"Task started\",\n          payload: {\n            taskId: event.payload.taskId,\n            ...(event.payload.taskType ? { taskType: event.payload.taskType } : {}),\n            ...(event.payload.description\n              ? { detail: truncateDetail(event.payload.description) }\n              : {}),\n            ...taskLinkageActivityFields(event.payload as Record<string, unknown>),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"task.progress\": {\n      const linkage = taskLinkageActivityFields(event.payload as Record<string, unknown>);\n      // Usage and activity are independent latest-state streams. Keeping them\n      // under separate stable ids prevents a command/reasoning update from\n      // replacing the last known token count (and prevents a usage-only tick\n      // from blanking the last meaningful activity).\n      const identityLinkage = { ...linkage };\n      delete identityLinkage.typedUsage;\n      delete identityLinkage.status;\n      delete identityLinkage.error;\n      const title =\n        event.payload.description.trim().length > 0\n          ? { title: truncateDetail(event.payload.description, 120) }\n          : {};\n      const hasProgressState =\n        event.payload.typedUsage === undefined ||\n        event.payload.summary !== undefined ||\n        event.payload.lastToolName !== undefined ||\n        event.payload.status !== undefined ||\n        event.payload.error !== undefined;\n      return [\n        ...(hasProgressState\n          ? [\n              {\n                // Stable per-task id: activity is \"latest state\", not\n                // history, so each meaningful tick replaces the last. This\n                // bounds a large fleet to one activity row per task.\n                id: EventId.make(`task-progress:${event.threadId}:${event.payload.taskId}`),\n                createdAt: event.createdAt,\n                tone: \"info\" as const,\n                kind: \"task.progress\" as const,\n                summary:\n                  event.payload.description.trim().length > 0\n                    ? truncateDetail(event.payload.description, 120)\n                    : \"Reasoning update\",\n                payload: {\n                  taskId: event.payload.taskId,\n                  ...title,\n                  detail: truncateDetail(event.payload.summary ?? event.payload.description),\n                  ...(event.payload.summary\n                    ? { summary: truncateDetail(event.payload.summary) }\n                    : {}),\n                  ...(event.payload.lastToolName\n                    ? { lastToolName: event.payload.lastToolName }\n                    : {}),\n                  ...(event.payload.status ? { status: event.payload.status } : {}),\n                  ...(event.payload.error ? { error: event.payload.error } : {}),\n                  ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),\n                  ...identityLinkage,\n                },\n                turnId: toTurnId(event.turnId) ?? null,\n                ...maybeSequence,\n              },\n            ]\n          : []),\n        ...(event.payload.typedUsage !== undefined\n          ? [\n              {\n                id: EventId.make(`task-usage:${event.threadId}:${event.payload.taskId}`),\n                createdAt: event.createdAt,\n                tone: \"info\" as const,\n                kind: \"task.progress\" as const,\n                summary: \"Task usage updated\",\n                payload: {\n                  taskId: event.payload.taskId,\n                  ...title,\n                  ...identityLinkage,\n                  usageSnapshot: true,\n                  typedUsage: event.payload.typedUsage,\n                },\n                turnId: toTurnId(event.turnId) ?? null,\n                ...maybeSequence,\n              },\n            ]\n          : []),\n      ];\n    }\n\n    case \"task.updated\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: event.payload.status === \"failed\" ? \"error\" : \"info\",\n          kind: \"task.updated\",\n          summary:\n            event.payload.status === \"failed\"\n              ? \"Task failed\"\n              : event.payload.status\n                ? `Task ${event.payload.status}`\n                : \"Task updated\",\n          payload: {\n            taskId: event.payload.taskId,\n            ...(event.payload.description\n              ? { detail: truncateDetail(event.payload.description) }\n              : {}),\n            ...(event.payload.endedAt ? { endedAt: event.payload.endedAt } : {}),\n            ...(event.payload.isBackgrounded !== undefined\n              ? { isBackgrounded: event.payload.isBackgrounded }\n              : {}),\n            ...taskLinkageActivityFields(event.payload as Record<string, unknown>),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"tool.progress\": {\n      // Only agent-owned heartbeats are persisted: they feed the owning\n      // agent's activity line. Parent-conversation tool progress stays\n      // ephemeral (item lifecycle already covers it).\n      if (event.payload.taskId === undefined) {\n        return [];\n      }\n      return [\n        {\n          // Same stable-id treatment as task.progress: a heartbeat is\n          // \"what is this agent doing right now\", so one row per task\n          // (thread-scoped for the same global-PK collision reason).\n          id: EventId.make(`tool-progress:${event.threadId}:${event.payload.taskId}`),\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"tool.progress\",\n          summary: event.payload.toolName ?? \"Tool progress\",\n          payload: {\n            taskId: event.payload.taskId,\n            ...(event.payload.toolName ? { toolName: event.payload.toolName } : {}),\n            ...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),\n            ...(event.payload.elapsedSeconds !== undefined\n              ? { elapsedSeconds: event.payload.elapsedSeconds }\n              : {}),\n            ...(event.payload.parentToolUseId\n              ? { parentToolUseId: event.payload.parentToolUseId }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"task.completed\": {\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: event.payload.status === \"failed\" ? \"error\" : \"info\",\n          kind: \"task.completed\",\n          summary:\n            event.payload.status === \"failed\"\n              ? \"Task failed\"\n              : event.payload.status === \"stopped\"\n                ? \"Task stopped\"\n                : \"Task completed\",\n          payload: {\n            taskId: event.payload.taskId,\n            status: event.payload.status,\n            ...(taskTitle ? { title: truncateDetail(taskTitle, 120) } : {}),\n            // summary + detail mirror task.progress: clients label the row from\n            // summary and keep detail for the preview/expanded body.\n            ...(event.payload.summary\n              ? {\n                  summary: truncateDetail(event.payload.summary),\n                  detail: truncateDetail(event.payload.summary),\n                }\n              : {}),\n            ...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),\n            ...taskLinkageActivityFields(event.payload as Record<string, unknown>),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"thread.state.changed\": {\n      if (event.payload.state !== \"compacted\") {\n        return [];\n      }\n\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"context-compaction\",\n          summary: \"Context compacted\",\n          payload: {\n            state: event.payload.state,\n            ...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"thread.token-usage.updated\": {\n      const payload = buildContextWindowActivityPayload(event);\n      if (!payload) {\n        return [];\n      }\n\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"info\",\n          kind: \"context-window.updated\",\n          summary: \"Context window updated\",\n          payload,\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"item.updated\": {\n      if (!isToolLifecycleItemType(event.payload.itemType)) {\n        return [];\n      }\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"tool\",\n          kind: \"tool.updated\",\n          summary: event.payload.title ?? \"Tool updated\",\n          payload: {\n            itemType: event.payload.itemType,\n            ...(event.payload.status ? { status: event.payload.status } : {}),\n            ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),\n            ...(event.payload.data !== undefined ? { data: event.payload.data } : {}),\n            ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),\n            ...(event.payload.parentToolUseId\n              ? { parentToolUseId: event.payload.parentToolUseId }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"item.completed\": {\n      if (!isToolLifecycleItemType(event.payload.itemType)) {\n        return [];\n      }\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"tool\",\n          kind: \"tool.completed\",\n          summary: event.payload.title ?? \"Tool\",\n          payload: {\n            itemType: event.payload.itemType,\n            ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),\n            ...(event.payload.data !== undefined ? { data: event.payload.data } : {}),\n            ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),\n            ...(event.payload.parentToolUseId\n              ? { parentToolUseId: event.payload.parentToolUseId }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    case \"item.started\": {\n      if (!isToolLifecycleItemType(event.payload.itemType)) {\n        return [];\n      }\n      return [\n        {\n          id: event.eventId,\n          createdAt: event.createdAt,\n          tone: \"tool\",\n          kind: \"tool.started\",\n          summary: `${event.payload.title ?? \"Tool\"} started`,\n          payload: {\n            itemType: event.payload.itemType,\n            ...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),\n            ...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),\n            ...(event.payload.parentToolUseId\n              ? { parentToolUseId: event.payload.parentToolUseId }\n              : {}),\n          },\n          turnId: toTurnId(event.turnId) ?? null,\n          ...maybeSequence,\n        },\n      ];\n    }\n\n    default:\n      break;\n  }\n\n  return [];\n}\n\nconst make = Effect.gen(function* () {\n  const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;\n  const threadPlanProgress = yield* ThreadPlanProgressService;\n  const crypto = yield* Crypto.Crypto;\n  const orchestrationEngine = yield* OrchestrationEngineService;\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n  const providerService = yield* ProviderService;\n  const projectionTurnRepository = yield* ProjectionTurnRepository;\n  const serverSettingsService = yield* ServerSettingsService;\n  const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>\n    crypto.randomUUIDv4.pipe(\n      Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),\n    );\n\n  const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({\n    capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,\n    timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,\n    lookup: () => Effect.succeed(new Set<MessageId>()),\n  });\n\n  const bufferedAssistantTextByMessageId = yield* Cache.make<MessageId, string>({\n    capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,\n    timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,\n    lookup: () => Effect.succeed(\"\"),\n  });\n\n  const assistantSegmentStateByTurnKey = yield* Cache.make<string, AssistantSegmentState>({\n    capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,\n    timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,\n    lookup: () =>\n      Effect.die(\n        new Error(\"assistant segment state should be read through getOption before initialization\"),\n      ),\n  });\n\n  const bufferedProposedPlanById = yield* Cache.make<string, { text: string; createdAt: string }>({\n    capacity: BUFFERED_PROPOSED_PLAN_BY_ID_CACHE_CAPACITY,\n    timeToLive: BUFFERED_PROPOSED_PLAN_BY_ID_TTL,\n    lookup: () => Effect.succeed({ text: \"\", createdAt: \"\" }),\n  });\n\n  // Task names arrive on task.started/task.progress but not on task.completed,\n  // so remember them per task to title the completion activity.\n  const taskDescriptionByTaskKey = yield* Cache.make<string, string>({\n    capacity: TASK_DESCRIPTION_BY_TASK_CACHE_CAPACITY,\n    timeToLive: TASK_DESCRIPTION_BY_TASK_TTL,\n    lookup: () => Effect.succeed(\"\"),\n  });\n\n  const rememberTaskDescription = (threadId: ThreadId, taskId: string, description: string) =>\n    Cache.set(taskDescriptionByTaskKey, providerTaskKey(threadId, taskId), description);\n\n  // Entries are left in place after completion so replayed or duplicate\n  // terminal events stay titled; TTL, capacity, and the session-exit sweep\n  // bound the cache.\n  const lookupTaskDescription = (threadId: ThreadId, taskId: string) =>\n    Cache.getOption(taskDescriptionByTaskKey, providerTaskKey(threadId, taskId)).pipe(\n      Effect.map((description) =>\n        Option.filter(description, (value) => value.length > 0).pipe(Option.getOrUndefined),\n      ),\n    );\n\n  const resolveThreadDetail = Effect.fn(\"resolveThreadDetail\")(function* (threadId: ThreadId) {\n    return yield* projectionSnapshotQuery\n      .getThreadDetailById(threadId)\n      .pipe(Effect.map(Option.getOrUndefined));\n  });\n\n  const resolveThreadShell = Effect.fn(\"resolveThreadShell\")(function* (threadId: ThreadId) {\n    return yield* projectionSnapshotQuery\n      .getThreadShellById(threadId)\n      .pipe(Effect.map(Option.getOrUndefined));\n  });\n\n  const rememberAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>\n    Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(\n      Effect.flatMap((existingIds) =>\n        Cache.set(\n          turnMessageIdsByTurnKey,\n          providerTurnKey(threadId, turnId),\n          Option.match(existingIds, {\n            onNone: () => new Set([messageId]),\n            onSome: (ids) => {\n              const nextIds = new Set(ids);\n              nextIds.add(messageId);\n              return nextIds;\n            },\n          }),\n        ),\n      ),\n    );\n\n  const forgetAssistantMessageId = (threadId: ThreadId, turnId: TurnId, messageId: MessageId) =>\n    Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(\n      Effect.flatMap((existingIds) =>\n        Option.match(existingIds, {\n          onNone: () => Effect.void,\n          onSome: (ids) => {\n            const nextIds = new Set(ids);\n            nextIds.delete(messageId);\n            if (nextIds.size === 0) {\n              return Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));\n            }\n            return Cache.set(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId), nextIds);\n          },\n        }),\n      ),\n    );\n\n  const getAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    Cache.getOption(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId)).pipe(\n      Effect.map((existingIds) =>\n        Option.getOrElse(existingIds, (): Set<MessageId> => new Set<MessageId>()),\n      ),\n    );\n\n  const clearAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));\n\n  const getAssistantSegmentStateForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    Cache.getOption(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId));\n\n  const setAssistantSegmentStateForTurn = (\n    threadId: ThreadId,\n    turnId: TurnId,\n    state: AssistantSegmentState,\n  ) => Cache.set(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId), state);\n\n  const clearAssistantSegmentStateForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    Cache.invalidate(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId));\n\n  const getActiveAssistantMessageIdForTurn = (threadId: ThreadId, turnId: TurnId) =>\n    getAssistantSegmentStateForTurn(threadId, turnId).pipe(\n      Effect.map((state) =>\n        Option.flatMap(state, (entry) =>\n          entry.activeMessageId ? Option.some(entry.activeMessageId) : Option.none(),\n        ),\n      ),\n    );\n\n  const startAssistantSegmentForTurn = (input: {\n    threadId: ThreadId;\n    turnId: TurnId;\n    baseKey: string;\n  }) =>\n    getAssistantSegmentStateForTurn(input.threadId, input.turnId).pipe(\n      Effect.flatMap((existingState) =>\n        Effect.gen(function* () {\n          const nextState = Option.match(existingState, {\n            onNone: () => ({\n              baseKey: input.baseKey,\n              nextSegmentIndex: 1,\n              activeMessageId: assistantSegmentMessageId(input.baseKey, 0),\n            }),\n            onSome: (state) => {\n              const segmentIndex = state.baseKey === input.baseKey ? state.nextSegmentIndex : 0;\n              const messageId = assistantSegmentMessageId(input.baseKey, segmentIndex);\n              return {\n                baseKey: input.baseKey,\n                nextSegmentIndex: state.baseKey === input.baseKey ? state.nextSegmentIndex + 1 : 1,\n                activeMessageId: messageId,\n              } satisfies AssistantSegmentState;\n            },\n          });\n          yield* setAssistantSegmentStateForTurn(input.threadId, input.turnId, nextState);\n          return nextState.activeMessageId!;\n        }),\n      ),\n    );\n\n  const getOrCreateAssistantMessageId = (input: {\n    threadId: ThreadId;\n    event: ProviderRuntimeEvent;\n    turnId?: TurnId;\n  }) =>\n    Effect.gen(function* () {\n      if (!input.turnId) {\n        return assistantSegmentMessageId(assistantSegmentBaseKeyFromEvent(input.event), 0);\n      }\n\n      const activeMessageId = yield* getActiveAssistantMessageIdForTurn(\n        input.threadId,\n        input.turnId,\n      );\n      if (Option.isSome(activeMessageId)) {\n        return activeMessageId.value;\n      }\n\n      return yield* startAssistantSegmentForTurn({\n        threadId: input.threadId,\n        turnId: input.turnId,\n        baseKey: assistantSegmentBaseKeyFromEvent(input.event),\n      });\n    });\n\n  const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>\n    Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(\n      Effect.flatMap((existingText) =>\n        Effect.gen(function* () {\n          const nextText = Option.match(existingText, {\n            onNone: () => delta,\n            onSome: (text) => `${text}${delta}`,\n          });\n          if (nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS) {\n            yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText);\n            return \"\";\n          }\n\n          // Safety valve: flush full buffered text as an assistant delta to cap memory.\n          yield* Cache.invalidate(bufferedAssistantTextByMessageId, messageId);\n          return nextText;\n        }),\n      ),\n    );\n\n  const takeBufferedAssistantText = (messageId: MessageId) =>\n    Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(\n      Effect.flatMap((existingText) =>\n        Cache.invalidate(bufferedAssistantTextByMessageId, messageId).pipe(\n          Effect.as(Option.getOrElse(existingText, () => \"\")),\n        ),\n      ),\n    );\n\n  const clearBufferedAssistantText = (messageId: MessageId) =>\n    Cache.invalidate(bufferedAssistantTextByMessageId, messageId);\n\n  const appendBufferedProposedPlan = (planId: string, delta: string, createdAt: string) =>\n    Cache.getOption(bufferedProposedPlanById, planId).pipe(\n      Effect.flatMap((existingEntry) => {\n        const existing = Option.getOrUndefined(existingEntry);\n        return Cache.set(bufferedProposedPlanById, planId, {\n          text: `${existing?.text ?? \"\"}${delta}`,\n          createdAt:\n            existing?.createdAt && existing.createdAt.length > 0 ? existing.createdAt : createdAt,\n        });\n      }),\n    );\n\n  const takeBufferedProposedPlan = (planId: string) =>\n    Cache.getOption(bufferedProposedPlanById, planId).pipe(\n      Effect.flatMap((existingEntry) =>\n        Cache.invalidate(bufferedProposedPlanById, planId).pipe(\n          Effect.as(Option.getOrUndefined(existingEntry)),\n        ),\n      ),\n    );\n\n  const clearBufferedProposedPlan = (planId: string) =>\n    Cache.invalidate(bufferedProposedPlanById, planId);\n\n  const clearAssistantMessageState = (messageId: MessageId) =>\n    clearBufferedAssistantText(messageId);\n\n  const flushBufferedAssistantMessage = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    messageId: MessageId;\n    turnId?: TurnId;\n    createdAt: string;\n    commandTag: string;\n  }) =>\n    Effect.gen(function* () {\n      const bufferedText = yield* takeBufferedAssistantText(input.messageId);\n      if (!hasRenderableAssistantText(bufferedText)) {\n        return false;\n      }\n\n      yield* orchestrationEngine.dispatch({\n        type: \"thread.message.assistant.delta\",\n        commandId: yield* providerCommandId(input.event, input.commandTag),\n        threadId: input.threadId,\n        messageId: input.messageId,\n        delta: bufferedText,\n        ...(input.turnId ? { turnId: input.turnId } : {}),\n        createdAt: input.createdAt,\n      });\n      return true;\n    });\n\n  const flushBufferedAssistantMessagesForTurn = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    turnId: TurnId;\n    createdAt: string;\n    commandTag: string;\n  }) =>\n    Effect.gen(function* () {\n      const assistantMessageIds = yield* getAssistantMessageIdsForTurn(\n        input.threadId,\n        input.turnId,\n      );\n      const flushedMessageIds = new Set<MessageId>();\n      yield* Effect.forEach(\n        assistantMessageIds,\n        (messageId) =>\n          flushBufferedAssistantMessage({\n            event: input.event,\n            threadId: input.threadId,\n            messageId,\n            turnId: input.turnId,\n            createdAt: input.createdAt,\n            commandTag: input.commandTag,\n          }).pipe(\n            Effect.tap((flushed) =>\n              flushed ? Effect.sync(() => flushedMessageIds.add(messageId)) : Effect.void,\n            ),\n          ),\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n      return flushedMessageIds;\n    });\n\n  const finalizeAssistantMessage = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    messageId: MessageId;\n    turnId?: TurnId;\n    createdAt: string;\n    commandTag: string;\n    finalDeltaCommandTag: string;\n    fallbackText?: string;\n    hasProjectedMessage?: boolean;\n  }) =>\n    Effect.gen(function* () {\n      const bufferedText = yield* takeBufferedAssistantText(input.messageId);\n      const text =\n        bufferedText.length > 0\n          ? bufferedText\n          : (input.fallbackText?.trim().length ?? 0) > 0\n            ? input.fallbackText!\n            : \"\";\n      const hasRenderableText = hasRenderableAssistantText(text);\n\n      if (hasRenderableText) {\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.message.assistant.delta\",\n          commandId: yield* providerCommandId(input.event, input.finalDeltaCommandTag),\n          threadId: input.threadId,\n          messageId: input.messageId,\n          delta: text,\n          ...(input.turnId ? { turnId: input.turnId } : {}),\n          createdAt: input.createdAt,\n        });\n      }\n\n      if (input.hasProjectedMessage || hasRenderableText) {\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.message.assistant.complete\",\n          commandId: yield* providerCommandId(input.event, input.commandTag),\n          threadId: input.threadId,\n          messageId: input.messageId,\n          ...(input.turnId ? { turnId: input.turnId } : {}),\n          createdAt: input.createdAt,\n        });\n      }\n      yield* clearAssistantMessageState(input.messageId);\n    });\n\n  const finalizeActiveAssistantSegmentForTurn = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    turnId: TurnId;\n    createdAt: string;\n    commandTag: string;\n    finalDeltaCommandTag: string;\n    hasProjectedMessage: boolean;\n    flushedMessageIds?: ReadonlySet<MessageId>;\n  }) =>\n    Effect.gen(function* () {\n      const activeMessageId = yield* getActiveAssistantMessageIdForTurn(\n        input.threadId,\n        input.turnId,\n      );\n      if (Option.isNone(activeMessageId)) {\n        return;\n      }\n\n      yield* finalizeAssistantMessage({\n        event: input.event,\n        threadId: input.threadId,\n        messageId: activeMessageId.value,\n        turnId: input.turnId,\n        createdAt: input.createdAt,\n        commandTag: input.commandTag,\n        finalDeltaCommandTag: input.finalDeltaCommandTag,\n        hasProjectedMessage:\n          input.hasProjectedMessage ||\n          (input.flushedMessageIds?.has(activeMessageId.value) ?? false),\n      });\n      yield* forgetAssistantMessageId(input.threadId, input.turnId, activeMessageId.value);\n\n      const state = yield* getAssistantSegmentStateForTurn(input.threadId, input.turnId);\n      if (Option.isSome(state)) {\n        yield* setAssistantSegmentStateForTurn(input.threadId, input.turnId, {\n          ...state.value,\n          activeMessageId: null,\n        });\n      }\n    });\n\n  const upsertProposedPlan = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    threadProposedPlans: ReadonlyArray<{\n      id: string;\n      createdAt: string;\n      implementedAt: string | null;\n      implementationThreadId: ThreadId | null;\n    }>;\n    planId: string;\n    turnId?: TurnId;\n    planMarkdown: string | undefined;\n    createdAt: string;\n    updatedAt: string;\n  }) =>\n    Effect.gen(function* () {\n      const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown);\n      if (!planMarkdown) {\n        return;\n      }\n\n      const existingPlan = findProposedPlanById(input.threadProposedPlans, input.planId);\n      yield* orchestrationEngine.dispatch({\n        type: \"thread.proposed-plan.upsert\",\n        commandId: yield* providerCommandId(input.event, \"proposed-plan-upsert\"),\n        threadId: input.threadId,\n        proposedPlan: {\n          id: input.planId,\n          turnId: input.turnId ?? null,\n          planMarkdown,\n          implementedAt: existingPlan?.implementedAt ?? null,\n          implementationThreadId: existingPlan?.implementationThreadId ?? null,\n          createdAt: existingPlan?.createdAt ?? input.createdAt,\n          updatedAt: input.updatedAt,\n        },\n        createdAt: input.updatedAt,\n      });\n    });\n\n  const finalizeBufferedProposedPlan = (input: {\n    event: ProviderRuntimeEvent;\n    threadId: ThreadId;\n    threadProposedPlans: ReadonlyArray<{\n      id: string;\n      createdAt: string;\n      implementedAt: string | null;\n      implementationThreadId: ThreadId | null;\n    }>;\n    planId: string;\n    turnId?: TurnId;\n    fallbackMarkdown?: string;\n    updatedAt: string;\n  }) =>\n    Effect.gen(function* () {\n      const bufferedPlan = yield* takeBufferedProposedPlan(input.planId);\n      const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text);\n      const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown);\n      const planMarkdown = bufferedMarkdown ?? fallbackMarkdown;\n      if (!planMarkdown) {\n        return;\n      }\n\n      yield* upsertProposedPlan({\n        event: input.event,\n        threadId: input.threadId,\n        threadProposedPlans: input.threadProposedPlans,\n        planId: input.planId,\n        ...(input.turnId ? { turnId: input.turnId } : {}),\n        planMarkdown,\n        createdAt:\n          bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0\n            ? bufferedPlan.createdAt\n            : input.updatedAt,\n        updatedAt: input.updatedAt,\n      });\n      yield* clearBufferedProposedPlan(input.planId);\n    });\n\n  const clearTurnStateForSession = (threadId: ThreadId) =>\n    Effect.gen(function* () {\n      const prefix = `${threadId}:`;\n      const proposedPlanPrefix = `plan:${threadId}:`;\n      const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey));\n      const assistantSegmentKeys = Array.from(yield* Cache.keys(assistantSegmentStateByTurnKey));\n      const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById));\n      const taskDescriptionKeys = Array.from(yield* Cache.keys(taskDescriptionByTaskKey));\n      yield* Effect.forEach(\n        turnKeys,\n        (key) =>\n          Effect.gen(function* () {\n            if (!key.startsWith(prefix)) {\n              return;\n            }\n\n            const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key);\n            if (Option.isSome(messageIds)) {\n              yield* Effect.forEach(messageIds.value, clearAssistantMessageState, {\n                concurrency: 1,\n              }).pipe(Effect.asVoid);\n            }\n\n            yield* Cache.invalidate(turnMessageIdsByTurnKey, key);\n          }),\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n      yield* Effect.forEach(\n        assistantSegmentKeys,\n        (key) =>\n          key.startsWith(prefix)\n            ? Cache.invalidate(assistantSegmentStateByTurnKey, key)\n            : Effect.void,\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n      yield* Effect.forEach(\n        proposedPlanKeys,\n        (key) =>\n          key.startsWith(proposedPlanPrefix)\n            ? Cache.invalidate(bufferedProposedPlanById, key)\n            : Effect.void,\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n      yield* Effect.forEach(\n        taskDescriptionKeys,\n        (key) =>\n          key.startsWith(prefix) ? Cache.invalidate(taskDescriptionByTaskKey, key) : Effect.void,\n        { concurrency: 1 },\n      ).pipe(Effect.asVoid);\n    });\n\n  const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn(\n    \"getSourceProposedPlanReferenceForPendingTurnStart\",\n  )(function* (threadId: ThreadId) {\n    const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({\n      threadId,\n    });\n    if (Option.isNone(pendingTurnStart)) {\n      return null;\n    }\n\n    const sourceThreadId = pendingTurnStart.value.sourceProposedPlanThreadId;\n    const sourcePlanId = pendingTurnStart.value.sourceProposedPlanId;\n    if (sourceThreadId === null || sourcePlanId === null) {\n      return null;\n    }\n\n    return {\n      sourceThreadId,\n      sourcePlanId,\n    } as const;\n  });\n\n  const getExpectedProviderTurnIdForThread = Effect.fn(\"getExpectedProviderTurnIdForThread\")(\n    function* (threadId: ThreadId) {\n      const sessions = yield* providerService.listSessions();\n      const session = sessions.find((entry) => entry.threadId === threadId);\n      return session?.activeTurnId;\n    },\n  );\n\n  const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn(\n    \"getSourceProposedPlanReferenceForAcceptedTurnStart\",\n  )(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) {\n    if (eventTurnId === undefined) {\n      return null;\n    }\n\n    const expectedTurnId = yield* getExpectedProviderTurnIdForThread(threadId);\n    if (!sameId(expectedTurnId, eventTurnId)) {\n      return null;\n    }\n\n    return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);\n  });\n\n  const markSourceProposedPlanImplemented = Effect.fn(\"markSourceProposedPlanImplemented\")(\n    function* (\n      sourceThreadId: ThreadId,\n      sourcePlanId: OrchestrationProposedPlanId,\n      implementationThreadId: ThreadId,\n      implementedAt: string,\n    ) {\n      const sourceThread = yield* resolveThreadDetail(sourceThreadId);\n      const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);\n      if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {\n        return;\n      }\n\n      const commandUuid = yield* crypto.randomUUIDv4;\n      yield* orchestrationEngine.dispatch({\n        type: \"thread.proposed-plan.upsert\",\n        commandId: CommandId.make(\n          `provider:source-proposed-plan-implemented:${implementationThreadId}:${commandUuid}`,\n        ),\n        threadId: sourceThread.id,\n        proposedPlan: {\n          ...sourcePlan,\n          implementedAt,\n          implementationThreadId,\n          updatedAt: implementedAt,\n        },\n        createdAt: implementedAt,\n      });\n    },\n  );\n\n  const processRuntimeEvent = (event: ProviderRuntimeEvent) =>\n    Effect.gen(function* () {\n      const thread = yield* resolveThreadShell(event.threadId);\n      if (!thread) return;\n\n      let loadedThreadDetail: OrchestrationThread | null | undefined;\n      const getLoadedThreadDetail = () =>\n        Effect.gen(function* () {\n          if (loadedThreadDetail !== undefined) {\n            return loadedThreadDetail;\n          }\n          loadedThreadDetail = (yield* resolveThreadDetail(thread.id)) ?? null;\n          return loadedThreadDetail;\n        });\n\n      const now = event.createdAt;\n      const eventTurnId = toTurnId(event.turnId);\n      const activeTurnId = thread.session?.activeTurnId ?? null;\n      const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({\n        threadId: thread.id,\n      });\n      const hasPendingTurnStart =\n        Option.isSome(pendingTurnStart) && thread.session?.status === \"starting\";\n\n      const conflictsWithActiveTurn =\n        activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);\n      const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;\n\n      // A turn.started that conflicts with the active turn is legitimate when\n      // the server itself has a turn start pending for this thread AND the\n      // provider session already tracks the event's turn as its active turn:\n      // steering a running turn makes some providers (e.g. opencode) open a\n      // new turn without ever completing the superseded one. A stale\n      // turn.started for some other turn id still gets rejected.\n      const conflictingTurnStartIsPendingTurnStart =\n        event.type === \"turn.started\" && conflictsWithActiveTurn\n          ? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&\n            Option.isSome(pendingTurnStart)\n          : false;\n\n      const shouldApplyThreadLifecycle = (() => {\n        if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {\n          return true;\n        }\n        switch (event.type) {\n          case \"session.exited\":\n            return true;\n          case \"session.started\":\n          case \"thread.started\":\n            return true;\n          case \"turn.started\":\n            return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;\n          case \"turn.completed\":\n            if (conflictsWithActiveTurn || missingTurnForActiveTurn) {\n              return false;\n            }\n            // Only the active turn may close the lifecycle state.\n            if (activeTurnId !== null && eventTurnId !== undefined) {\n              return sameId(activeTurnId, eventTurnId);\n            }\n            // If no active turn is tracked, accept completion scoped to this thread.\n            return true;\n          default:\n            return true;\n        }\n      })();\n      const acceptedTurnStartedSourcePlan =\n        event.type === \"turn.started\" && shouldApplyThreadLifecycle\n          ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)\n          : null;\n\n      if (\n        event.type === \"session.started\" ||\n        event.type === \"session.state.changed\" ||\n        event.type === \"session.exited\" ||\n        event.type === \"thread.started\" ||\n        event.type === \"turn.started\" ||\n        event.type === \"turn.completed\"\n      ) {\n        const status = (() => {\n          switch (event.type) {\n            case \"session.state.changed\": {\n              const runtimeStatus = orchestrationSessionStatusFromRuntimeState(event.payload.state);\n              return hasPendingTurnStart && runtimeStatus === \"ready\" ? \"starting\" : runtimeStatus;\n            }\n            case \"turn.started\":\n              return \"running\";\n            case \"session.exited\":\n              return \"stopped\";\n            case \"turn.completed\":\n              return normalizeRuntimeTurnState(event.payload.state) === \"failed\"\n                ? \"error\"\n                : \"ready\";\n            case \"session.started\":\n            case \"thread.started\":\n              // Provider thread/session start notifications can arrive during an\n              // active or pending turn; preserve that lifecycle state.\n              return activeTurnId !== null ? \"running\" : hasPendingTurnStart ? \"starting\" : \"ready\";\n          }\n        })();\n        const nextActiveTurnId =\n          event.type === \"turn.started\"\n            ? (eventTurnId ?? null)\n            : event.type === \"turn.completed\" || event.type === \"session.exited\"\n              ? null\n              : event.type === \"session.state.changed\" &&\n                  !sessionStatusAllowsActiveTurn(\n                    orchestrationSessionStatusFromRuntimeState(event.payload.state),\n                  )\n                ? null\n                : activeTurnId;\n        const lastError =\n          event.type === \"session.state.changed\" && event.payload.state === \"error\"\n            ? (event.payload.reason ?? thread.session?.lastError ?? \"Provider session error\")\n            : event.type === \"turn.completed\" &&\n                normalizeRuntimeTurnState(event.payload.state) === \"failed\"\n              ? (event.payload.errorMessage ?? thread.session?.lastError ?? \"Turn failed\")\n              : status === \"ready\"\n                ? null\n                : (thread.session?.lastError ?? null);\n\n        if (shouldApplyThreadLifecycle) {\n          if (event.type === \"turn.started\" && acceptedTurnStartedSourcePlan !== null) {\n            yield* markSourceProposedPlanImplemented(\n              acceptedTurnStartedSourcePlan.sourceThreadId,\n              acceptedTurnStartedSourcePlan.sourcePlanId,\n              thread.id,\n              now,\n            ).pipe(\n              Effect.catchCause((cause) =>\n                Effect.logWarning(\n                  \"provider runtime ingestion failed to mark source proposed plan\",\n                  {\n                    eventId: event.eventId,\n                    eventType: event.type,\n                    cause: Cause.pretty(cause),\n                  },\n                ),\n              ),\n            );\n          }\n\n          yield* orchestrationEngine.dispatch({\n            type: \"thread.session.set\",\n            commandId: yield* providerCommandId(event, \"thread-session-set\"),\n            threadId: thread.id,\n            session: {\n              threadId: thread.id,\n              status,\n              providerName: event.provider,\n              ...(event.providerInstanceId !== undefined\n                ? { providerInstanceId: event.providerInstanceId }\n                : {}),\n              runtimeMode: thread.session?.runtimeMode ?? \"full-access\",\n              activeTurnId: nextActiveTurnId,\n              lastError,\n              updatedAt: now,\n            },\n            createdAt: now,\n          });\n        }\n      }\n\n      const assistantDelta =\n        event.type === \"content.delta\" && event.payload.streamKind === \"assistant_text\"\n          ? event.payload.delta\n          : undefined;\n      const proposedPlanDelta =\n        event.type === \"turn.proposed.delta\" ? event.payload.delta : undefined;\n\n      if (assistantDelta && assistantDelta.length > 0) {\n        const turnId = toTurnId(event.turnId);\n        const assistantMessageId = yield* getOrCreateAssistantMessageId({\n          threadId: thread.id,\n          event,\n          ...(turnId ? { turnId } : {}),\n        });\n        if (turnId) {\n          yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);\n        }\n\n        const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(\n          serverSettingsService.getSettings,\n          (settings) => (settings.enableLegacyTokenStreaming ? \"streaming\" : \"buffered\"),\n        );\n        if (assistantDeliveryMode === \"buffered\") {\n          const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);\n          if (spillChunk.length > 0) {\n            yield* orchestrationEngine.dispatch({\n              type: \"thread.message.assistant.delta\",\n              commandId: yield* providerCommandId(event, \"assistant-delta-buffer-spill\"),\n              threadId: thread.id,\n              messageId: assistantMessageId,\n              delta: spillChunk,\n              ...(turnId ? { turnId } : {}),\n              createdAt: now,\n            });\n          }\n        } else {\n          yield* orchestrationEngine.dispatch({\n            type: \"thread.message.assistant.delta\",\n            commandId: yield* providerCommandId(event, \"assistant-delta\"),\n            threadId: thread.id,\n            messageId: assistantMessageId,\n            delta: assistantDelta,\n            ...(turnId ? { turnId } : {}),\n            createdAt: now,\n          });\n        }\n      }\n\n      const pauseForUserTurnId =\n        event.type === \"request.opened\" || event.type === \"user-input.requested\"\n          ? toTurnId(event.turnId)\n          : undefined;\n      if (pauseForUserTurnId) {\n        const detailedThread = yield* getLoadedThreadDetail();\n        const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(\n          serverSettingsService.getSettings,\n          (settings) => (settings.enableLegacyTokenStreaming ? \"streaming\" : \"buffered\"),\n        );\n        const flushedMessageIds =\n          assistantDeliveryMode === \"buffered\"\n            ? yield* flushBufferedAssistantMessagesForTurn({\n                event,\n                threadId: thread.id,\n                turnId: pauseForUserTurnId,\n                createdAt: now,\n                commandTag:\n                  event.type === \"request.opened\"\n                    ? \"assistant-delta-flush-on-request-opened\"\n                    : \"assistant-delta-flush-on-user-input-requested\",\n              })\n            : new Set<MessageId>();\n        yield* finalizeActiveAssistantSegmentForTurn({\n          event,\n          threadId: thread.id,\n          turnId: pauseForUserTurnId,\n          createdAt: now,\n          commandTag:\n            event.type === \"request.opened\"\n              ? \"assistant-complete-on-request-opened\"\n              : \"assistant-complete-on-user-input-requested\",\n          finalDeltaCommandTag:\n            event.type === \"request.opened\"\n              ? \"assistant-delta-finalize-on-request-opened\"\n              : \"assistant-delta-finalize-on-user-input-requested\",\n          hasProjectedMessage:\n            detailedThread !== null &&\n            hasAssistantMessageForTurn(detailedThread.messages, pauseForUserTurnId, {\n              streamingOnly: true,\n            }),\n          flushedMessageIds,\n        });\n      }\n\n      if (proposedPlanDelta && proposedPlanDelta.length > 0) {\n        const planId = proposedPlanIdFromEvent(event, thread.id);\n        yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now);\n      }\n\n      const assistantCompletion =\n        event.type === \"item.completed\" && event.payload.itemType === \"assistant_message\"\n          ? {\n              messageId: MessageId.make(\n                `assistant:${event.itemId ?? event.turnId ?? event.eventId}`,\n              ),\n              fallbackText: event.payload.detail,\n            }\n          : undefined;\n      const proposedPlanCompletion =\n        event.type === \"turn.proposed.completed\"\n          ? {\n              planId: proposedPlanIdFromEvent(event, thread.id),\n              turnId: toTurnId(event.turnId),\n              planMarkdown: event.payload.planMarkdown,\n            }\n          : undefined;\n\n      if (assistantCompletion) {\n        const detailedThread = yield* getLoadedThreadDetail();\n        const messages = detailedThread?.messages ?? [];\n        const turnId = toTurnId(event.turnId);\n        const activeAssistantMessageId = turnId\n          ? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)\n          : Option.none<MessageId>();\n        const hasAssistantMessagesForTurn =\n          turnId !== undefined ? hasAssistantMessageForTurn(messages, turnId) : false;\n        const assistantMessageId = Option.getOrElse(\n          activeAssistantMessageId,\n          () => assistantCompletion.messageId,\n        );\n        const existingAssistantMessage = findMessageById(messages, assistantMessageId);\n        const shouldApplyFallbackCompletionText =\n          !existingAssistantMessage || existingAssistantMessage.text.length === 0;\n\n        const shouldSkipRedundantCompletion =\n          Option.isNone(activeAssistantMessageId) &&\n          turnId !== undefined &&\n          hasAssistantMessagesForTurn &&\n          (assistantCompletion.fallbackText?.trim().length ?? 0) === 0;\n\n        if (!shouldSkipRedundantCompletion) {\n          if (turnId && Option.isNone(activeAssistantMessageId)) {\n            yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);\n          }\n\n          yield* finalizeAssistantMessage({\n            event,\n            threadId: thread.id,\n            messageId: assistantMessageId,\n            ...(turnId ? { turnId } : {}),\n            createdAt: now,\n            commandTag: \"assistant-complete\",\n            finalDeltaCommandTag: \"assistant-delta-finalize\",\n            hasProjectedMessage: existingAssistantMessage !== undefined,\n            ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText\n              ? { fallbackText: assistantCompletion.fallbackText }\n              : {}),\n          });\n\n          if (turnId) {\n            yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId);\n          }\n        }\n\n        if (turnId) {\n          yield* clearAssistantSegmentStateForTurn(thread.id, turnId);\n        }\n      }\n\n      if (proposedPlanCompletion) {\n        const detailedThread = yield* getLoadedThreadDetail();\n        yield* finalizeBufferedProposedPlan({\n          event,\n          threadId: thread.id,\n          threadProposedPlans: detailedThread?.proposedPlans ?? [],\n          planId: proposedPlanCompletion.planId,\n          ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}),\n          fallbackMarkdown: proposedPlanCompletion.planMarkdown,\n          updatedAt: now,\n        });\n      }\n\n      if (event.type === \"turn.completed\") {\n        const detailedThread = yield* getLoadedThreadDetail();\n        const messages = detailedThread?.messages ?? [];\n        const proposedPlans = detailedThread?.proposedPlans ?? [];\n        const turnId = toTurnId(event.turnId);\n        if (turnId) {\n          const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId);\n          yield* Effect.forEach(\n            assistantMessageIds,\n            (assistantMessageId) =>\n              finalizeAssistantMessage({\n                event,\n                threadId: thread.id,\n                messageId: assistantMessageId,\n                turnId,\n                createdAt: now,\n                commandTag: \"assistant-complete-finalize\",\n                finalDeltaCommandTag: \"assistant-delta-finalize-fallback\",\n                hasProjectedMessage: findMessageById(messages, assistantMessageId) !== undefined,\n              }),\n            { concurrency: 1 },\n          ).pipe(Effect.asVoid);\n          yield* clearAssistantMessageIdsForTurn(thread.id, turnId);\n          yield* clearAssistantSegmentStateForTurn(thread.id, turnId);\n\n          yield* finalizeBufferedProposedPlan({\n            event,\n            threadId: thread.id,\n            threadProposedPlans: proposedPlans,\n            planId: proposedPlanIdForTurn(thread.id, turnId),\n            turnId,\n            updatedAt: now,\n          });\n        }\n      }\n\n      if (event.type === \"session.exited\") {\n        yield* clearTurnStateForSession(thread.id);\n      }\n\n      if (event.type === \"runtime.error\") {\n        const runtimeErrorMessage = event.payload.message;\n\n        const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD\n          ? true\n          : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId);\n\n        if (shouldApplyRuntimeError) {\n          yield* orchestrationEngine.dispatch({\n            type: \"thread.session.set\",\n            commandId: yield* providerCommandId(event, \"runtime-error-session-set\"),\n            threadId: thread.id,\n            session: {\n              threadId: thread.id,\n              status: \"error\",\n              providerName: event.provider,\n              ...(event.providerInstanceId !== undefined\n                ? { providerInstanceId: event.providerInstanceId }\n                : {}),\n              runtimeMode: thread.session?.runtimeMode ?? \"full-access\",\n              activeTurnId: eventTurnId ?? null,\n              lastError: runtimeErrorMessage,\n              updatedAt: now,\n            },\n            createdAt: now,\n          });\n        }\n      }\n\n      if (event.type === \"thread.metadata.updated\" && event.payload.name) {\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.meta.update\",\n          commandId: yield* providerCommandId(event, \"thread-meta-update\"),\n          threadId: thread.id,\n          title: event.payload.name,\n        });\n      }\n\n      if (event.type === \"turn.diff.updated\") {\n        const turnId = toTurnId(event.turnId);\n        const checkpointContext = turnId\n          ? yield* projectionSnapshotQuery\n              .getThreadCheckpointContext(thread.id)\n              .pipe(Effect.map(Option.getOrUndefined))\n          : undefined;\n        const workspaceCwd =\n          checkpointContext?.worktreePath ?? checkpointContext?.workspaceRoot ?? undefined;\n        if (turnId && checkpointContext && workspaceCwd && isGitRepository(workspaceCwd)) {\n          // Skip if a checkpoint already exists for this turn. A real\n          // (non-placeholder) capture from CheckpointReactor should not\n          // be clobbered, and dispatching a duplicate placeholder for the\n          // same turnId would produce an unstable checkpointTurnCount.\n          if (hasCheckpointForTurn(checkpointContext.checkpoints, turnId)) {\n            // Already tracked; no-op.\n          } else {\n            const assistantMessageId = MessageId.make(\n              `assistant:${event.itemId ?? event.turnId ?? event.eventId}`,\n            );\n            yield* orchestrationEngine.dispatch({\n              type: \"thread.turn.diff.complete\",\n              commandId: yield* providerCommandId(event, \"thread-turn-diff-complete\"),\n              threadId: thread.id,\n              turnId,\n              completedAt: now,\n              checkpointRef: CheckpointRef.make(`provider-diff:${event.eventId}`),\n              status: \"missing\",\n              files: [],\n              assistantMessageId,\n              checkpointTurnCount: maxCheckpointTurnCount(checkpointContext.checkpoints) + 1,\n              createdAt: now,\n            });\n          }\n        }\n      }\n\n      if (event.type === \"task.started\" || event.type === \"task.progress\") {\n        const description = event.payload.description?.trim();\n        if (description) {\n          yield* rememberTaskDescription(thread.id, event.payload.taskId, description);\n        }\n      }\n      // Working-indicator plan progress: current step while the turn runs,\n      // cleared on settle so a finished plan never lingers as stale UI.\n      // Events carrying a turn id that conflicts with the active turn are\n      // stale (superseded turn) and must neither overwrite nor clear the\n      // active turn's progress; session.exited always clears.\n      if (event.type === \"session.exited\") {\n        threadPlanProgress.clearThreadPlanProgress(thread.id);\n      } else if (!conflictsWithActiveTurn) {\n        if (event.type === \"turn.plan.updated\") {\n          threadPlanProgress.recordPlanProgress(thread.id, event.payload.plan);\n        } else if (event.type === \"turn.completed\" || event.type === \"turn.aborted\") {\n          threadPlanProgress.clearThreadPlanProgress(thread.id);\n        }\n      }\n\n      // Sidebar background liveness: fed from the same lifecycle stream,\n      // read by the shell query at mapping time (no persistence).\n      switch (event.type) {\n        case \"task.started\":\n        case \"task.progress\":\n        case \"task.updated\":\n        case \"task.completed\": {\n          const payload = event.payload as {\n            taskId: string;\n            taskType?: string;\n            status?: string;\n            agentId?: string;\n          };\n          threadBackgroundLiveness.recordTaskLiveness({\n            threadId: thread.id,\n            taskId: payload.taskId,\n            taskType: payload.taskType,\n            status: payload.status,\n            agentId: payload.agentId,\n            kind:\n              event.type === \"task.started\"\n                ? \"started\"\n                : event.type === \"task.progress\"\n                  ? \"progress\"\n                  : event.type === \"task.updated\"\n                    ? \"updated\"\n                    : \"completed\",\n          });\n          break;\n        }\n        case \"session.exited\":\n          threadBackgroundLiveness.clearThreadLiveness(thread.id);\n          break;\n        default:\n          break;\n      }\n\n      let taskTitle: string | undefined;\n      if (event.type === \"task.completed\") {\n        taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId);\n        if (!taskTitle) {\n          const threadDetail = yield* getLoadedThreadDetail();\n          taskTitle = findTaskTitleInActivities(threadDetail?.activities, event.payload.taskId);\n        }\n      }\n\n      const activities = runtimeEventToActivities(event, taskTitle);\n      yield* Effect.forEach(activities, (activity) =>\n        providerCommandId(event, \"thread-activity-append\").pipe(\n          Effect.flatMap((commandId) =>\n            orchestrationEngine.dispatch({\n              type: \"thread.activity.append\",\n              commandId,\n              threadId: thread.id,\n              activity,\n              createdAt: activity.createdAt,\n            }),\n          ),\n        ),\n      ).pipe(Effect.asVoid);\n    });\n\n  const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;\n\n  const processInput = (input: RuntimeIngestionInput) =>\n    input.source === \"runtime\" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);\n\n  const processInputSafely = (input: RuntimeIngestionInput) =>\n    processInput(input).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.failCause(cause);\n        }\n        return Effect.logWarning(\"provider runtime ingestion failed to process event\", {\n          source: input.source,\n          eventId: input.event.eventId,\n          eventType: input.event.type,\n          cause: Cause.pretty(cause),\n        });\n      }),\n    );\n\n  const worker = yield* makeDrainableWorker(processInputSafely);\n\n  const start: ProviderRuntimeIngestionShape[\"start\"] = () =>\n    Effect.gen(function* () {\n      yield* forkParked(\n        Stream.runForEach(providerService.streamEvents, (event) =>\n          worker.enqueue({ source: \"runtime\", event }),\n        ),\n      );\n      yield* forkParked(\n        Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {\n          if (event.type !== \"thread.turn-start-requested\") {\n            return Effect.void;\n          }\n          return worker.enqueue({ source: \"domain\", event });\n        }),\n      );\n    });\n\n  return {\n    start,\n    drain: worker.drain,\n  } satisfies ProviderRuntimeIngestionShape;\n});\n\nexport const ProviderRuntimeIngestionLive = Layer.effect(\n  ProviderRuntimeIngestionService,\n  make,\n).pipe(Layer.provide(ProjectionTurnRepositoryLive));\n","import {\n  type ChatAttachment,\n  CommandId,\n  EventId,\n  type ModelSelection,\n  type OrchestrationEvent,\n  ProviderDriverKind,\n  type ProjectId,\n  type OrchestrationSession,\n  ThreadId,\n  type ProviderSession,\n  type RuntimeMode,\n  type TurnId,\n} from \"@t3tools/contracts\";\nimport { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from \"@t3tools/shared/git\";\nimport * as Cache from \"effect/Cache\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport { makeDrainableWorker } from \"@t3tools/shared/DrainableWorker\";\n\nimport { resolveThreadWorkspaceCwd } from \"../../checkpointing/Utils.ts\";\nimport { increment, orchestrationEventsProcessedTotal } from \"../../observability/Metrics.ts\";\nimport { ProviderAdapterRequestError } from \"../../provider/Errors.ts\";\nimport type { ProviderServiceError } from \"../../provider/Errors.ts\";\nimport { TextGeneration } from \"../../textGeneration/TextGeneration.ts\";\nimport { ProviderService } from \"../../provider/Services/ProviderService.ts\";\nimport { ProviderRegistry } from \"../../provider/Services/ProviderRegistry.ts\";\nimport { OrchestrationEngineService } from \"../Services/OrchestrationEngine.ts\";\nimport { ProjectionSnapshotQuery } from \"../Services/ProjectionSnapshotQuery.ts\";\nimport {\n  ProviderCommandReactor,\n  type ProviderCommandReactorShape,\n} from \"../Services/ProviderCommandReactor.ts\";\nimport { forkParked, ServerActivation } from \"../../serverActivation.ts\";\nimport {\n  resolveSourceControlWriterModelSelection,\n  ServerSettingsService,\n} from \"../../serverSettings.ts\";\nimport { VcsStatusBroadcaster } from \"../../vcs/VcsStatusBroadcaster.ts\";\nimport { GitWorkflowService } from \"../../git/GitWorkflowService.ts\";\nconst isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);\nconst isProviderDriverKind = Schema.is(ProviderDriverKind);\n\ntype ProviderIntentEvent = Extract<\n  OrchestrationEvent,\n  {\n    type:\n      | \"thread.meta-updated\"\n      | \"thread.runtime-mode-set\"\n      | \"thread.turn-start-requested\"\n      | \"thread.turn-interrupt-requested\"\n      | \"thread.approval-response-requested\"\n      | \"thread.user-input-response-requested\"\n      | \"thread.session-stop-requested\";\n  }\n>;\n\nfunction toNonEmptyProviderInput(value: string | undefined): string | undefined {\n  const normalized = value?.trim();\n  return normalized && normalized.length > 0 ? normalized : undefined;\n}\n\nfunction mapProviderSessionStatusToOrchestrationStatus(\n  status: \"connecting\" | \"ready\" | \"running\" | \"error\" | \"closed\",\n): OrchestrationSession[\"status\"] {\n  switch (status) {\n    case \"connecting\":\n      return \"starting\";\n    case \"running\":\n      return \"running\";\n    case \"error\":\n      return \"error\";\n    case \"closed\":\n      return \"stopped\";\n    case \"ready\":\n    default:\n      return \"ready\";\n  }\n}\n\nconst turnStartKeyForEvent = (event: ProviderIntentEvent): string =>\n  event.commandId !== null ? `command:${event.commandId}` : `event:${event.eventId}`;\n\nconst HANDLED_TURN_START_KEY_MAX = 10_000;\nconst HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);\nconst DEFAULT_RUNTIME_MODE: RuntimeMode = \"full-access\";\nconst DEFAULT_THREAD_TITLE = \"New thread\";\nconst MAX_REGENERATION_ATTACHMENTS = 4;\nconst MAX_THREAD_TITLE_CONTEXT_CHARS = 8_000;\nconst MAX_FIRST_USER_TITLE_CONTEXT_CHARS = 2_000;\nconst THREAD_TITLE_CONTEXT_TRUNCATION_MARKER = \"[Earlier content truncated]\\n\\n\";\nconst FIRST_USER_CONTEXT_TRUNCATION_MARKER = \"\\n[First user message truncated]\";\n\ntype ThreadTitleMessage = {\n  readonly role: \"user\" | \"assistant\" | \"system\";\n  readonly text: string;\n  readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;\n};\n\nfunction formatThreadTitleSection(message: ThreadTitleMessage): string | undefined {\n  if (message.role === \"system\") {\n    return undefined;\n  }\n  const text = message.text.trim();\n  const attachmentSummary = (message.attachments ?? [])\n    .map((attachment) => attachment.name)\n    .join(\", \");\n  const contents = [\n    ...(text.length > 0 ? [text] : []),\n    ...(attachmentSummary.length > 0 ? [`[Attachments: ${attachmentSummary}]`] : []),\n  ].join(\"\\n\");\n  return contents.length > 0 ? `${message.role.toUpperCase()}:\\n${contents}` : undefined;\n}\n\nfunction limitFirstUserSection(section: string): string {\n  if (section.length <= MAX_FIRST_USER_TITLE_CONTEXT_CHARS) {\n    return section;\n  }\n  return `${section.slice(\n    0,\n    MAX_FIRST_USER_TITLE_CONTEXT_CHARS - FIRST_USER_CONTEXT_TRUNCATION_MARKER.length,\n  )}${FIRST_USER_CONTEXT_TRUNCATION_MARKER}`;\n}\n\nfunction collectRecentThreadTitleContext(\n  messages: ReadonlyArray<ThreadTitleMessage>,\n  maxChars: number,\n): {\n  readonly context: string;\n  readonly attachments: ReadonlyArray<ChatAttachment>;\n  readonly truncated: boolean;\n} {\n  let context = \"\";\n  let truncated = false;\n  const retainedAttachments: Array<ChatAttachment> = [];\n\n  for (const message of messages.toReversed()) {\n    const section = formatThreadTitleSection(message);\n    if (section === undefined) {\n      continue;\n    }\n\n    const separator = context.length > 0 ? \"\\n\\n\" : \"\";\n    const available = maxChars - context.length - separator.length;\n    if (section.length > available) {\n      if (available > 0) {\n        context = `${section.slice(-available)}${separator}${context}`;\n        retainedAttachments.unshift(...(message.attachments ?? []));\n      }\n      truncated = true;\n      break;\n    }\n    context = `${section}${separator}${context}`;\n    retainedAttachments.unshift(...(message.attachments ?? []));\n  }\n\n  return { context, attachments: retainedAttachments, truncated };\n}\n\nfunction formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>): {\n  readonly message: string;\n  readonly attachments: ReadonlyArray<ChatAttachment>;\n} {\n  const recent = collectRecentThreadTitleContext(messages, MAX_THREAD_TITLE_CONTEXT_CHARS);\n  if (!recent.truncated) {\n    return {\n      message: recent.context,\n      attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),\n    };\n  }\n\n  const firstUserMessage = messages.find(\n    (message) => message.role === \"user\" && formatThreadTitleSection(message),\n  );\n  const firstUserSection = firstUserMessage\n    ? formatThreadTitleSection(firstUserMessage)\n    : undefined;\n  if (!firstUserMessage || !firstUserSection) {\n    return {\n      message: `${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${recent.context}`,\n      attachments: recent.attachments.slice(-MAX_REGENERATION_ATTACHMENTS),\n    };\n  }\n\n  const pinnedSection = limitFirstUserSection(firstUserSection);\n  const recentContextBudget =\n    MAX_THREAD_TITLE_CONTEXT_CHARS -\n    pinnedSection.length -\n    \"\\n\\n\".length -\n    THREAD_TITLE_CONTEXT_TRUNCATION_MARKER.length;\n  const retainedRecent = collectRecentThreadTitleContext(messages, recentContextBudget);\n  const pinnedAttachment = firstUserMessage.attachments?.[0];\n  const recentAttachments = retainedRecent.attachments.filter(\n    (attachment) => attachment.id !== pinnedAttachment?.id,\n  );\n\n  return {\n    message: `${pinnedSection}\\n\\n${THREAD_TITLE_CONTEXT_TRUNCATION_MARKER}${retainedRecent.context}`,\n    attachments: [\n      ...(pinnedAttachment ? [pinnedAttachment] : []),\n      ...recentAttachments.slice(\n        -(MAX_REGENERATION_ATTACHMENTS - (pinnedAttachment === undefined ? 0 : 1)),\n      ),\n    ],\n  };\n}\n\nexport function providerErrorLabel(value: string | undefined): string {\n  const normalized = value?.trim();\n  return normalized && normalized.length > 0 ? normalized : \"unknown\";\n}\n\nexport function providerErrorLabelFromInstanceHint(input: {\n  readonly instanceId?: string | undefined;\n  readonly modelSelectionInstanceId?: string | undefined;\n  readonly sessionProvider?: string | undefined;\n}): string {\n  return providerErrorLabel(\n    input.instanceId ?? input.modelSelectionInstanceId ?? input.sessionProvider,\n  );\n}\n\nfunction canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean {\n  const trimmedCurrentTitle = currentTitle.trim();\n  if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) {\n    return true;\n  }\n\n  const trimmedTitleSeed = titleSeed?.trim();\n  return trimmedTitleSeed !== undefined && trimmedTitleSeed.length > 0\n    ? trimmedCurrentTitle === trimmedTitleSeed\n    : false;\n}\n\nfunction findProviderAdapterRequestError(\n  cause: Cause.Cause<ProviderServiceError>,\n): ProviderAdapterRequestError | undefined {\n  const failReason = cause.reasons.find(Cause.isFailReason);\n  return isProviderAdapterRequestError(failReason?.error) ? failReason.error : undefined;\n}\n\nfunction isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {\n  const error = findProviderAdapterRequestError(cause);\n  if (error) {\n    const detail = error.detail.toLowerCase();\n    return (\n      detail.includes(\"unknown pending approval request\") ||\n      detail.includes(\"unknown pending permission request\")\n    );\n  }\n  const message = Cause.pretty(cause);\n  return (\n    message.includes(\"unknown pending approval request\") ||\n    message.includes(\"unknown pending permission request\")\n  );\n}\n\nfunction isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {\n  const error = findProviderAdapterRequestError(cause);\n  if (error) {\n    const detail = error.detail.toLowerCase();\n    return (\n      detail.includes(\"unknown pending user-input request\") ||\n      detail.includes(\"unknown pending user input request\") ||\n      detail.includes(\"unknown pending codex user input request\")\n    );\n  }\n  const message = Cause.pretty(cause).toLowerCase();\n  return (\n    message.includes(\"unknown pending user-input request\") ||\n    message.includes(\"unknown pending user input request\") ||\n    message.includes(\"unknown pending codex user input request\")\n  );\n}\n\nfunction stalePendingRequestDetail(\n  requestKind: \"approval\" | \"user-input\",\n  requestId: string,\n): string {\n  return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;\n}\n\nfunction buildGeneratedWorktreeBranchName(raw: string): string {\n  const normalized = raw\n    .trim()\n    .toLowerCase()\n    .replace(/^refs\\/heads\\//, \"\")\n    .replace(/['\"`]/g, \"\");\n\n  const withoutPrefix = normalized.startsWith(`${WORKTREE_BRANCH_PREFIX}/`)\n    ? normalized.slice(`${WORKTREE_BRANCH_PREFIX}/`.length)\n    : normalized;\n\n  const branchFragment = withoutPrefix\n    .replace(/[^a-z0-9/_-]+/g, \"-\")\n    .replace(/\\/+/g, \"/\")\n    .replace(/-+/g, \"-\")\n    .replace(/^[./_-]+|[./_-]+$/g, \"\")\n    .slice(0, 64)\n    .replace(/[./_-]+$/g, \"\");\n\n  const safeFragment = branchFragment.length > 0 ? branchFragment : \"update\";\n  return `${WORKTREE_BRANCH_PREFIX}/${safeFragment}`;\n}\n\nconst make = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const orchestrationEngine = yield* OrchestrationEngineService;\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n  const providerService = yield* ProviderService;\n  const providerRegistry = yield* ProviderRegistry;\n  const gitWorkflow = yield* GitWorkflowService;\n  const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;\n  const textGeneration = yield* TextGeneration;\n  const serverSettingsService = yield* ServerSettingsService;\n  const serverCommandId = (tag: string) =>\n    crypto.randomUUIDv4.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));\n  const serverEventId = () => crypto.randomUUIDv4.pipe(Effect.map(EventId.make));\n  const handledTurnStartKeys = yield* Cache.make<string, true>({\n    capacity: HANDLED_TURN_START_KEY_MAX,\n    timeToLive: HANDLED_TURN_START_KEY_TTL,\n    lookup: () => Effect.succeed(true),\n  });\n\n  const hasHandledTurnStartRecently = (key: string) =>\n    Cache.getOption(handledTurnStartKeys, key).pipe(\n      Effect.flatMap((cached) =>\n        Cache.set(handledTurnStartKeys, key, true).pipe(Effect.as(Option.isSome(cached))),\n      ),\n    );\n\n  const threadModelSelections = new Map<string, ModelSelection>();\n\n  const appendProviderFailureActivity = (input: {\n    readonly threadId: ThreadId;\n    readonly kind:\n      | \"provider.turn.start.failed\"\n      | \"provider.turn.interrupt.failed\"\n      | \"provider.approval.respond.failed\"\n      | \"provider.user-input.respond.failed\"\n      | \"provider.session.stop.failed\";\n    readonly summary: string;\n    readonly detail: string;\n    readonly turnId: TurnId | null;\n    readonly createdAt: string;\n    readonly requestId?: string;\n  }) =>\n    Effect.all({\n      commandId: serverCommandId(\"provider-failure-activity\"),\n      eventId: serverEventId(),\n    }).pipe(\n      Effect.flatMap(({ commandId, eventId }) =>\n        orchestrationEngine.dispatch({\n          type: \"thread.activity.append\",\n          commandId,\n          threadId: input.threadId,\n          activity: {\n            id: eventId,\n            tone: \"error\",\n            kind: input.kind,\n            summary: input.summary,\n            payload: {\n              detail: input.detail,\n              ...(input.requestId ? { requestId: input.requestId } : {}),\n            },\n            turnId: input.turnId,\n            createdAt: input.createdAt,\n          },\n          createdAt: input.createdAt,\n        }),\n      ),\n    );\n\n  const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {\n    const failReason = cause.reasons.find(Cause.isFailReason);\n    const providerError = isProviderAdapterRequestError(failReason?.error)\n      ? failReason.error\n      : undefined;\n    if (providerError) {\n      return providerError.detail;\n    }\n    return Cause.pretty(cause);\n  };\n\n  const setThreadSession = (input: {\n    readonly threadId: ThreadId;\n    readonly session: OrchestrationSession;\n    readonly createdAt: string;\n  }) =>\n    serverCommandId(\"provider-session-set\").pipe(\n      Effect.flatMap((commandId) =>\n        orchestrationEngine.dispatch({\n          type: \"thread.session.set\",\n          commandId,\n          threadId: input.threadId,\n          session: input.session,\n          createdAt: input.createdAt,\n        }),\n      ),\n    );\n\n  const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {\n    readonly threadId: ThreadId;\n    readonly detail: string;\n    readonly createdAt: string;\n  }) {\n    const thread = yield* resolveThread(input.threadId);\n    if (!thread) {\n      return;\n    }\n    const session = thread.session;\n    yield* setThreadSession({\n      threadId: input.threadId,\n      session: {\n        ...(session ?? {\n          threadId: input.threadId,\n          providerName: null,\n          providerInstanceId: thread.modelSelection.instanceId,\n          runtimeMode: thread.runtimeMode,\n        }),\n        status: session?.status === \"stopped\" ? \"stopped\" : \"error\",\n        activeTurnId: null,\n        lastError: input.detail,\n        updatedAt: input.createdAt,\n      },\n      createdAt: input.createdAt,\n    });\n  });\n\n  const resolveProject = Effect.fnUntraced(function* (projectId: ProjectId) {\n    return yield* projectionSnapshotQuery\n      .getProjectShellById(projectId)\n      .pipe(Effect.map(Option.getOrUndefined));\n  });\n\n  const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {\n    return yield* projectionSnapshotQuery\n      .getThreadDetailById(threadId)\n      .pipe(Effect.map(Option.getOrUndefined));\n  });\n\n  const rejectStartedThreadModelChangeIfRequired = Effect.fnUntraced(function* (input: {\n    readonly threadId: ThreadId;\n    readonly currentModelSelection: ModelSelection;\n    readonly requestedModelSelection: ModelSelection | undefined;\n  }) {\n    const requestedModelSelection = input.requestedModelSelection;\n    if (\n      requestedModelSelection === undefined ||\n      (input.currentModelSelection.instanceId === requestedModelSelection.instanceId &&\n        input.currentModelSelection.model === requestedModelSelection.model)\n    ) {\n      return;\n    }\n    const providers = yield* providerRegistry.getProviders;\n    const requiresNewThread =\n      providers.find((snapshot) => snapshot.instanceId === input.currentModelSelection.instanceId)\n        ?.requiresNewThreadForModelChange === true ||\n      providers.find((snapshot) => snapshot.instanceId === requestedModelSelection.instanceId)\n        ?.requiresNewThreadForModelChange === true;\n    if (!requiresNewThread) {\n      return;\n    }\n    return yield* new ProviderAdapterRequestError({\n      provider: providerErrorLabelFromInstanceHint({\n        instanceId: String(requestedModelSelection.instanceId),\n        modelSelectionInstanceId: String(input.currentModelSelection.instanceId),\n      }),\n      method: \"thread.turn.start\",\n      detail: `Thread '${input.threadId}' cannot switch models after the conversation has started. Start a new thread to use '${requestedModelSelection.model}'.`,\n    });\n  });\n\n  const ensureSessionForThread = Effect.fn(\"ensureSessionForThread\")(function* (\n    threadId: ThreadId,\n    createdAt: string,\n    options?: {\n      readonly modelSelection?: ModelSelection;\n      readonly pendingTurnStart?: boolean;\n    },\n  ) {\n    const thread = yield* resolveThread(threadId);\n    if (!thread) {\n      return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));\n    }\n\n    const desiredRuntimeMode = thread.runtimeMode;\n    const requestedModelSelection = options?.modelSelection;\n    const resolveActiveSession = (threadId: ThreadId) =>\n      providerService\n        .listSessions()\n        .pipe(Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)));\n\n    const activeSession = yield* resolveActiveSession(threadId);\n    const activeThreadSession =\n      thread.session !== null && thread.session.status !== \"stopped\" && activeSession\n        ? thread.session\n        : null;\n    if (\n      activeThreadSession !== null &&\n      activeSession !== undefined &&\n      (activeThreadSession.providerInstanceId === undefined ||\n        activeSession.providerInstanceId === undefined)\n    ) {\n      return yield* new ProviderAdapterRequestError({\n        provider: providerErrorLabel(activeThreadSession.providerName ?? undefined),\n        method: \"thread.turn.start\",\n        detail: `Thread '${threadId}' has an active provider session without a provider instance id.`,\n      });\n    }\n    const currentInstanceId =\n      activeThreadSession !== null &&\n      activeSession !== undefined &&\n      activeSession.providerInstanceId !== undefined\n        ? activeSession.providerInstanceId\n        : thread.modelSelection.instanceId;\n    const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;\n    const desiredInstanceId = desiredModelSelection.instanceId;\n    const currentInfo = yield* providerService.getInstanceInfo(currentInstanceId).pipe(\n      Effect.mapError(\n        () =>\n          new ProviderAdapterRequestError({\n            provider: providerErrorLabelFromInstanceHint({\n              instanceId: String(currentInstanceId),\n              modelSelectionInstanceId: String(thread.modelSelection.instanceId),\n              sessionProvider: thread.session?.providerName ?? undefined,\n            }),\n            method: \"thread.turn.start\",\n            detail: `Thread '${threadId}' references unknown provider instance '${currentInstanceId}'. The instance is not configured in this build.`,\n          }),\n      ),\n    );\n    const desiredInfo = yield* providerService.getInstanceInfo(desiredInstanceId).pipe(\n      Effect.mapError(\n        () =>\n          new ProviderAdapterRequestError({\n            provider: providerErrorLabelFromInstanceHint({\n              instanceId: String(desiredModelSelection.instanceId),\n            }),\n            method: \"thread.turn.start\",\n            detail: `Requested provider instance '${desiredInstanceId}' is not configured in this build.`,\n          }),\n      ),\n    );\n    const desiredDriverKind = desiredInfo.driverKind;\n    if (!isProviderDriverKind(desiredDriverKind)) {\n      return yield* new ProviderAdapterRequestError({\n        provider: providerErrorLabel(String(desiredDriverKind)),\n        method: \"thread.turn.start\",\n        detail: `Requested provider instance '${desiredInstanceId}' uses unknown provider driver '${desiredDriverKind}'. The driver is not installed in this build.`,\n      });\n    }\n    const preferredProvider: ProviderDriverKind = desiredDriverKind;\n    if (options?.pendingTurnStart === true && thread.session?.status !== \"running\") {\n      yield* setThreadSession({\n        threadId,\n        session: {\n          threadId,\n          status: \"starting\",\n          providerName: activeSession?.provider ?? preferredProvider,\n          providerInstanceId: activeSession?.providerInstanceId ?? desiredInstanceId,\n          runtimeMode: desiredRuntimeMode,\n          activeTurnId: null,\n          lastError: null,\n          updatedAt: createdAt,\n        },\n        createdAt,\n      });\n    }\n    if (thread.session !== null) {\n      yield* rejectStartedThreadModelChangeIfRequired({\n        threadId,\n        currentModelSelection:\n          activeSession?.model !== undefined\n            ? {\n                ...thread.modelSelection,\n                instanceId: currentInstanceId,\n                model: activeSession.model,\n              }\n            : thread.modelSelection,\n        requestedModelSelection,\n      });\n    }\n    if (\n      thread.session !== null &&\n      requestedModelSelection !== undefined &&\n      requestedModelSelection.instanceId !== currentInstanceId\n    ) {\n      if (currentInfo.driverKind !== desiredInfo.driverKind) {\n        return yield* new ProviderAdapterRequestError({\n          provider: preferredProvider,\n          method: \"thread.turn.start\",\n          detail: `Thread '${threadId}' is bound to driver '${currentInfo.driverKind}' and cannot switch to '${desiredInfo.driverKind}'.`,\n        });\n      }\n      if (\n        currentInfo.continuationIdentity.continuationKey !==\n        desiredInfo.continuationIdentity.continuationKey\n      ) {\n        return yield* new ProviderAdapterRequestError({\n          provider: preferredProvider,\n          method: \"thread.turn.start\",\n          detail: `Thread '${threadId}' cannot switch from instance '${currentInstanceId}' to '${desiredInstanceId}' because their provider resume state is incompatible.`,\n        });\n      }\n    }\n    const project = yield* resolveProject(thread.projectId);\n    const effectiveCwd = resolveThreadWorkspaceCwd({\n      thread,\n      projects: project ? [project] : [],\n    });\n\n    const startProviderSession = (input?: {\n      readonly resumeCursor?: unknown;\n      readonly provider?: ProviderDriverKind;\n    }) =>\n      providerService.startSession(threadId, {\n        threadId,\n        ...(preferredProvider ? { provider: preferredProvider } : {}),\n        providerInstanceId: desiredInstanceId,\n        ...(effectiveCwd ? { cwd: effectiveCwd } : {}),\n        modelSelection: desiredModelSelection,\n        ...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),\n        runtimeMode: desiredRuntimeMode,\n      });\n\n    const bindSessionToThread = (session: ProviderSession) =>\n      Effect.gen(function* () {\n        if (session.providerInstanceId === undefined) {\n          return yield* new ProviderAdapterRequestError({\n            provider: providerErrorLabel(session.provider),\n            method: \"thread.turn.start\",\n            detail: `Provider session '${session.threadId}' started without a provider instance id.`,\n          });\n        }\n        yield* setThreadSession({\n          threadId,\n          session: {\n            threadId,\n            status:\n              options?.pendingTurnStart === true && session.status === \"ready\"\n                ? \"starting\"\n                : mapProviderSessionStatusToOrchestrationStatus(session.status),\n            providerName: session.provider,\n            providerInstanceId: session.providerInstanceId,\n            runtimeMode: desiredRuntimeMode,\n            // Provider turn ids are not orchestration turn ids.\n            activeTurnId: null,\n            lastError: session.lastError ?? null,\n            updatedAt: session.updatedAt,\n          },\n          createdAt,\n        });\n      });\n\n    const existingSessionThreadId =\n      thread.session && thread.session.status !== \"stopped\" && activeSession ? thread.id : null;\n    if (existingSessionThreadId) {\n      const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;\n      const cwdChanged = effectiveCwd !== activeSession?.cwd;\n      const sessionModelSwitch = (yield* providerService.getCapabilities(desiredInstanceId))\n        .sessionModelSwitch;\n      const modelChanged =\n        requestedModelSelection !== undefined &&\n        requestedModelSelection.model !== activeSession?.model;\n      const instanceChanged =\n        requestedModelSelection !== undefined &&\n        activeSession?.providerInstanceId !== requestedModelSelection.instanceId;\n      const shouldRestartForModelChange = modelChanged && sessionModelSwitch === \"unsupported\";\n      const previousModelSelection = threadModelSelections.get(threadId);\n      const shouldRestartForModelSelectionChange =\n        preferredProvider === \"claudeAgent\" &&\n        requestedModelSelection !== undefined &&\n        !Equal.equals(previousModelSelection, requestedModelSelection);\n\n      if (\n        !runtimeModeChanged &&\n        !cwdChanged &&\n        !instanceChanged &&\n        !shouldRestartForModelChange &&\n        !shouldRestartForModelSelectionChange\n      ) {\n        return existingSessionThreadId;\n      }\n\n      const resumeCursor = shouldRestartForModelChange\n        ? undefined\n        : (activeSession?.resumeCursor ?? undefined);\n      yield* Effect.logInfo(\"provider command reactor restarting provider session\", {\n        threadId,\n        existingSessionThreadId,\n        currentProvider: activeSession?.provider,\n        currentInstanceId,\n        desiredInstanceId,\n        desiredProvider: desiredModelSelection.instanceId,\n        currentRuntimeMode: thread.session?.runtimeMode,\n        desiredRuntimeMode: thread.runtimeMode,\n        runtimeModeChanged,\n        previousCwd: activeSession?.cwd,\n        desiredCwd: effectiveCwd,\n        cwdChanged,\n        modelChanged,\n        instanceChanged,\n        shouldRestartForModelChange,\n        shouldRestartForModelSelectionChange,\n        hasResumeCursor: resumeCursor !== undefined,\n      });\n      const restartedSession = yield* startProviderSession(\n        resumeCursor !== undefined ? { resumeCursor } : undefined,\n      );\n      yield* Effect.logInfo(\"provider command reactor restarted provider session\", {\n        threadId,\n        previousSessionId: existingSessionThreadId,\n        restartedSessionThreadId: restartedSession.threadId,\n        provider: restartedSession.provider,\n        runtimeMode: restartedSession.runtimeMode,\n        cwd: restartedSession.cwd,\n      });\n      yield* bindSessionToThread(restartedSession);\n      return restartedSession.threadId;\n    }\n\n    const startedSession = yield* startProviderSession(undefined);\n    yield* bindSessionToThread(startedSession);\n    return startedSession.threadId;\n  });\n\n  const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {\n    readonly threadId: ThreadId;\n    readonly messageText: string;\n    readonly attachments?: ReadonlyArray<ChatAttachment>;\n    readonly modelSelection?: ModelSelection;\n    readonly interactionMode?: \"default\" | \"plan\";\n    readonly createdAt: string;\n  }) {\n    const thread = yield* resolveThread(input.threadId);\n    if (!thread) {\n      return yield* Effect.die(\n        new Error(`Thread '${input.threadId}' was not found in read model.`),\n      );\n    }\n    yield* ensureSessionForThread(input.threadId, input.createdAt, {\n      ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),\n      pendingTurnStart: true,\n    });\n    if (input.modelSelection !== undefined) {\n      threadModelSelections.set(input.threadId, input.modelSelection);\n    }\n    const normalizedInput = toNonEmptyProviderInput(input.messageText);\n    const normalizedAttachments = input.attachments ?? [];\n    const activeSession = yield* providerService\n      .listSessions()\n      .pipe(\n        Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),\n      );\n    const sessionModelSwitch =\n      activeSession === undefined\n        ? \"in-session\"\n        : activeSession.providerInstanceId === undefined\n          ? yield* new ProviderAdapterRequestError({\n              provider: providerErrorLabel(activeSession.provider),\n              method: \"thread.turn.start\",\n              detail: `Active provider session '${activeSession.threadId}' is missing a provider instance id.`,\n            })\n          : (yield* providerService.getCapabilities(activeSession.providerInstanceId))\n              .sessionModelSwitch;\n    const requestedModelSelection =\n      input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;\n    const modelForTurn =\n      sessionModelSwitch === \"unsupported\" && input.modelSelection === undefined\n        ? activeSession?.model !== undefined\n          ? {\n              ...requestedModelSelection,\n              model: activeSession.model,\n            }\n          : requestedModelSelection\n        : input.modelSelection;\n\n    return {\n      threadId: input.threadId,\n      ...(normalizedInput ? { input: normalizedInput } : {}),\n      ...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),\n      ...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),\n      ...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),\n    };\n  });\n\n  const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(\n    \"maybeGenerateAndRenameWorktreeBranchForFirstTurn\",\n  )(function* (input: {\n    readonly threadId: ThreadId;\n    readonly branch: string | null;\n    readonly worktreePath: string | null;\n    readonly messageText: string;\n    readonly attachments?: ReadonlyArray<ChatAttachment>;\n  }) {\n    if (!input.branch || !input.worktreePath) {\n      return;\n    }\n    if (!isTemporaryWorktreeBranch(input.branch)) {\n      return;\n    }\n\n    const oldBranch = input.branch;\n    const cwd = input.worktreePath;\n    const attachments = input.attachments ?? [];\n    yield* Effect.gen(function* () {\n      const settings = yield* serverSettingsService.getSettings;\n      const modelSelection =\n        settings.sourceControlWriterModelSelection === null\n          ? settings.textGenerationModelSelection\n          : resolveSourceControlWriterModelSelection(\n              settings,\n              yield* providerRegistry.getProviders,\n            );\n\n      const generated = yield* textGeneration.generateBranchName({\n        cwd,\n        message: input.messageText,\n        ...(attachments.length > 0 ? { attachments } : {}),\n        modelSelection,\n      });\n      if (!generated) return;\n\n      const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);\n      if (targetBranch === oldBranch) return;\n\n      const renamed = yield* gitWorkflow.renameBranch({ cwd, oldBranch, newBranch: targetBranch });\n      yield* orchestrationEngine.dispatch({\n        type: \"thread.meta.update\",\n        commandId: yield* serverCommandId(\"worktree-branch-rename\"),\n        threadId: input.threadId,\n        branch: renamed.branch,\n        worktreePath: cwd,\n      });\n      yield* vcsStatusBroadcaster.refreshStatus(cwd).pipe(Effect.ignoreCause({ log: true }));\n    }).pipe(\n      Effect.catchCause((cause) =>\n        Effect.logWarning(\"provider command reactor failed to generate or rename worktree branch\", {\n          threadId: input.threadId,\n          cwd,\n          oldBranch,\n          cause: Cause.pretty(cause),\n        }),\n      ),\n    );\n  });\n\n  const maybeGenerateThreadTitleForFirstTurn = Effect.fn(\"maybeGenerateThreadTitleForFirstTurn\")(\n    function* (input: {\n      readonly threadId: ThreadId;\n      readonly cwd: string;\n      readonly messageText: string;\n      readonly attachments?: ReadonlyArray<ChatAttachment>;\n      readonly titleSeed?: string;\n    }) {\n      const attachments = input.attachments ?? [];\n      yield* Effect.gen(function* () {\n        const { textGenerationModelSelection: modelSelection } =\n          yield* serverSettingsService.getSettings;\n\n        const generated = yield* textGeneration.generateThreadTitle({\n          cwd: input.cwd,\n          message: input.messageText,\n          ...(attachments.length > 0 ? { attachments } : {}),\n          modelSelection,\n        });\n        if (!generated) return;\n\n        const thread = yield* resolveThread(input.threadId);\n        if (!thread) return;\n        if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {\n          return;\n        }\n\n        yield* orchestrationEngine.dispatch({\n          type: \"thread.meta.update\",\n          commandId: yield* serverCommandId(\"thread-title-rename\"),\n          threadId: input.threadId,\n          title: generated.title,\n        });\n      }).pipe(\n        Effect.catchCause((cause) =>\n          Effect.logWarning(\"provider command reactor failed to generate or rename thread title\", {\n            threadId: input.threadId,\n            cwd: input.cwd,\n            cause: Cause.pretty(cause),\n          }),\n        ),\n      );\n    },\n  );\n\n  const regenerateThreadTitle = Effect.fn(\"regenerateThreadTitle\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.meta-updated\" }>,\n    requestId: CommandId,\n  ) {\n    if (event.payload.regenerateTitle !== true) {\n      return { _tag: \"Superseded\" } as const;\n    }\n\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread || thread.titleRegeneration?.requestId !== requestId) {\n      return { _tag: \"Superseded\" } as const;\n    }\n\n    const { message, attachments } = formatThreadTitleContext(thread.messages);\n    if (message.length === 0) {\n      return { _tag: \"Completed\", title: undefined } as const;\n    }\n\n    const previousTitle = event.payload.previousTitle ?? thread.title;\n    if (thread.title !== previousTitle) {\n      return { _tag: \"Superseded\" } as const;\n    }\n    const project = yield* resolveProject(thread.projectId);\n    const cwd =\n      resolveThreadWorkspaceCwd({\n        thread,\n        projects: project ? [project] : [],\n      }) ?? process.cwd();\n    const { textGenerationModelSelection: modelSelection } =\n      yield* serverSettingsService.getSettings;\n    const generated = yield* textGeneration.generateThreadTitle({\n      cwd,\n      message,\n      previousTitle,\n      ...(attachments.length > 0 ? { attachments } : {}),\n      modelSelection,\n    });\n    if (generated.title === DEFAULT_THREAD_TITLE || generated.title === previousTitle) {\n      return { _tag: \"Completed\", title: undefined } as const;\n    }\n\n    const latestThread = yield* resolveThread(event.payload.threadId);\n    if (\n      !latestThread ||\n      latestThread.titleRegeneration?.requestId !== requestId ||\n      latestThread.title !== previousTitle\n    ) {\n      return { _tag: \"Superseded\" } as const;\n    }\n\n    return { _tag: \"Completed\", title: generated.title } as const;\n  });\n  const dispatchThreadTitleRegenerationCompletion = Effect.fn(\n    \"dispatchThreadTitleRegenerationCompletion\",\n  )(function* (input: {\n    readonly threadId: ThreadId;\n    readonly requestId: CommandId;\n    readonly title?: string;\n  }) {\n    yield* orchestrationEngine.dispatch({\n      type: \"thread.title.regeneration.complete\",\n      commandId: yield* serverCommandId(\"thread-title-regeneration-complete\"),\n      threadId: input.threadId,\n      requestId: input.requestId,\n      ...(input.title !== undefined ? { title: input.title } : {}),\n    });\n  });\n  const findInterruptedThreadTitleRegenerations = Effect.fn(\n    \"findInterruptedThreadTitleRegenerations\",\n  )(function* () {\n    const readModel = yield* projectionSnapshotQuery.getCommandReadModel();\n    return readModel.threads.flatMap((thread) => {\n      const requestId = thread.titleRegeneration?.requestId;\n      return requestId === undefined ? [] : [{ threadId: thread.id, requestId }];\n    });\n  });\n  const clearInterruptedThreadTitleRegenerations = Effect.fn(\n    \"clearInterruptedThreadTitleRegenerations\",\n  )(function* (\n    interrupted: ReadonlyArray<{ readonly threadId: ThreadId; readonly requestId: CommandId }>,\n  ) {\n    yield* Effect.forEach(\n      interrupted,\n      ({ threadId, requestId }) => {\n        return dispatchThreadTitleRegenerationCompletion({\n          threadId,\n          requestId,\n        }).pipe(\n          Effect.catchCause((cause) => {\n            if (Cause.hasInterruptsOnly(cause)) {\n              return Effect.interrupt;\n            }\n            return Effect.logWarning(\n              \"provider command reactor failed to clear interrupted title regeneration\",\n              {\n                threadId,\n                cause: Cause.pretty(cause),\n              },\n            );\n          }),\n        );\n      },\n      { discard: true },\n    );\n  });\n  const processThreadTitleRegenerationSafely = Effect.fn(\"processThreadTitleRegenerationSafely\")(\n    function* (event: Extract<ProviderIntentEvent, { type: \"thread.meta-updated\" }>) {\n      if (event.payload.regenerateTitle !== true) {\n        return;\n      }\n\n      const requestId = event.payload.titleRegeneration?.requestId ?? event.commandId;\n      if (requestId === null) {\n        return;\n      }\n      const result = yield* regenerateThreadTitle(event, requestId).pipe(\n        Effect.catchCause((cause) => {\n          if (Cause.hasInterruptsOnly(cause)) {\n            return Effect.failCause(cause);\n          }\n          return Effect.logWarning(\"provider command reactor failed to regenerate thread title\", {\n            threadId: event.payload.threadId,\n            cause: Cause.pretty(cause),\n          }).pipe(Effect.as({ _tag: \"Completed\", title: undefined } as const));\n        }),\n      );\n      if (result._tag === \"Superseded\") {\n        return;\n      }\n\n      const completion = {\n        threadId: event.payload.threadId,\n        requestId,\n        ...(result.title !== undefined ? { title: result.title } : {}),\n      };\n      yield* dispatchThreadTitleRegenerationCompletion(completion).pipe(\n        Effect.catchCause((cause) => {\n          if (Cause.hasInterruptsOnly(cause)) {\n            return Effect.failCause(cause);\n          }\n          return Effect.logWarning(\n            \"provider command reactor retrying title regeneration completion\",\n            {\n              threadId: event.payload.threadId,\n              cause: Cause.pretty(cause),\n            },\n          ).pipe(Effect.andThen(dispatchThreadTitleRegenerationCompletion(completion)));\n        }),\n      );\n    },\n    (effect, event) =>\n      effect.pipe(\n        Effect.catchCause((cause) => {\n          if (Cause.hasInterruptsOnly(cause)) {\n            return Effect.failCause(cause);\n          }\n          return Effect.logWarning(\n            \"provider command reactor failed to complete title regeneration\",\n            {\n              threadId: event.payload.threadId,\n              cause: Cause.pretty(cause),\n            },\n          );\n        }),\n      ),\n  );\n  const threadTitleRegenerationWorker = yield* makeDrainableWorker(\n    processThreadTitleRegenerationSafely,\n  );\n\n  const processTurnStartRequested = Effect.fn(\"processTurnStartRequested\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.turn-start-requested\" }>,\n  ) {\n    const key = turnStartKeyForEvent(event);\n    if (yield* hasHandledTurnStartRecently(key)) {\n      return;\n    }\n\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread) {\n      return;\n    }\n\n    const message = thread.messages.find((entry) => entry.id === event.payload.messageId);\n    if (!message || message.role !== \"user\") {\n      yield* appendProviderFailureActivity({\n        threadId: event.payload.threadId,\n        kind: \"provider.turn.start.failed\",\n        summary: \"Provider turn start failed\",\n        detail: `User message '${event.payload.messageId}' was not found for turn start request.`,\n        turnId: null,\n        createdAt: event.payload.createdAt,\n      });\n      return;\n    }\n\n    const isFirstUserMessageTurn =\n      thread.messages.filter((entry) => entry.role === \"user\").length === 1;\n    if (isFirstUserMessageTurn) {\n      const project = yield* resolveProject(thread.projectId);\n      const generationCwd =\n        resolveThreadWorkspaceCwd({\n          thread,\n          projects: project ? [project] : [],\n        }) ?? process.cwd();\n      const generationInput = {\n        messageText: message.text,\n        ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),\n        ...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}),\n      };\n\n      yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({\n        threadId: event.payload.threadId,\n        branch: thread.branch,\n        worktreePath: thread.worktreePath,\n        ...generationInput,\n      }).pipe(Effect.forkScoped);\n\n      if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) {\n        yield* maybeGenerateThreadTitleForFirstTurn({\n          threadId: event.payload.threadId,\n          cwd: generationCwd,\n          ...generationInput,\n        }).pipe(Effect.forkScoped);\n      }\n    }\n\n    const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {\n      if (Cause.hasInterruptsOnly(cause)) {\n        return Effect.void;\n      }\n      const detail = formatFailureDetail(cause);\n      return setThreadSessionErrorOnTurnStartFailure({\n        threadId: event.payload.threadId,\n        detail,\n        createdAt: event.payload.createdAt,\n      }).pipe(\n        Effect.flatMap(() =>\n          appendProviderFailureActivity({\n            threadId: event.payload.threadId,\n            kind: \"provider.turn.start.failed\",\n            summary: \"Provider turn start failed\",\n            detail,\n            turnId: null,\n            createdAt: event.payload.createdAt,\n          }),\n        ),\n        Effect.asVoid,\n      );\n    };\n\n    const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>\n      handleTurnStartFailure(cause).pipe(\n        Effect.catchCause((recoveryCause) =>\n          Effect.logWarning(\"provider command reactor failed to recover turn start failure\", {\n            eventType: event.type,\n            threadId: event.payload.threadId,\n            cause: Cause.pretty(recoveryCause),\n            originalCause: Cause.pretty(cause),\n          }),\n        ),\n      );\n\n    const sendTurnRequest = yield* buildSendTurnRequestForThread({\n      threadId: event.payload.threadId,\n      messageText: message.text,\n      ...(message.attachments !== undefined ? { attachments: message.attachments } : {}),\n      ...(event.payload.modelSelection !== undefined\n        ? { modelSelection: event.payload.modelSelection }\n        : {}),\n      interactionMode: event.payload.interactionMode,\n      createdAt: event.payload.createdAt,\n    }).pipe(\n      Effect.map(Option.some),\n      Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),\n    );\n\n    if (Option.isNone(sendTurnRequest)) {\n      return;\n    }\n\n    yield* providerService\n      .sendTurn(sendTurnRequest.value)\n      .pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);\n  });\n\n  const processTurnInterruptRequested = Effect.fn(\"processTurnInterruptRequested\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.turn-interrupt-requested\" }>,\n  ) {\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread) {\n      return;\n    }\n    const hasSession = thread.session && thread.session.status !== \"stopped\";\n    if (!hasSession) {\n      return yield* appendProviderFailureActivity({\n        threadId: event.payload.threadId,\n        kind: \"provider.turn.interrupt.failed\",\n        summary: \"Provider turn interrupt failed\",\n        detail: \"No active provider session is bound to this thread.\",\n        turnId: event.payload.turnId ?? null,\n        createdAt: event.payload.createdAt,\n      });\n    }\n\n    // Orchestration turn ids are not provider turn ids, so interrupt by session.\n    yield* providerService.interruptTurn({ threadId: event.payload.threadId });\n  });\n\n  const processApprovalResponseRequested = Effect.fn(\"processApprovalResponseRequested\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.approval-response-requested\" }>,\n  ) {\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread) {\n      return;\n    }\n    const hasSession = thread.session && thread.session.status !== \"stopped\";\n    if (!hasSession) {\n      return yield* appendProviderFailureActivity({\n        threadId: event.payload.threadId,\n        kind: \"provider.approval.respond.failed\",\n        summary: \"Provider approval response failed\",\n        detail: \"No active provider session is bound to this thread.\",\n        turnId: null,\n        createdAt: event.payload.createdAt,\n        requestId: event.payload.requestId,\n      });\n    }\n\n    yield* providerService\n      .respondToRequest({\n        threadId: event.payload.threadId,\n        requestId: event.payload.requestId,\n        decision: event.payload.decision,\n      })\n      .pipe(\n        Effect.catchCause((cause) =>\n          appendProviderFailureActivity({\n            threadId: event.payload.threadId,\n            kind: \"provider.approval.respond.failed\",\n            summary: \"Provider approval response failed\",\n            detail: isUnknownPendingApprovalRequestError(cause)\n              ? stalePendingRequestDetail(\"approval\", event.payload.requestId)\n              : Cause.pretty(cause),\n            turnId: null,\n            createdAt: event.payload.createdAt,\n            requestId: event.payload.requestId,\n          }),\n        ),\n      );\n  });\n\n  const processUserInputResponseRequested = Effect.fn(\"processUserInputResponseRequested\")(\n    function* (\n      event: Extract<ProviderIntentEvent, { type: \"thread.user-input-response-requested\" }>,\n    ) {\n      const thread = yield* resolveThread(event.payload.threadId);\n      if (!thread) {\n        return;\n      }\n      const hasSession = thread.session && thread.session.status !== \"stopped\";\n      if (!hasSession) {\n        return yield* appendProviderFailureActivity({\n          threadId: event.payload.threadId,\n          kind: \"provider.user-input.respond.failed\",\n          summary: \"Provider user input response failed\",\n          detail: \"No active provider session is bound to this thread.\",\n          turnId: null,\n          createdAt: event.payload.createdAt,\n          requestId: event.payload.requestId,\n        });\n      }\n\n      yield* providerService\n        .respondToUserInput({\n          threadId: event.payload.threadId,\n          requestId: event.payload.requestId,\n          answers: event.payload.answers,\n        })\n        .pipe(\n          Effect.catchCause((cause) =>\n            appendProviderFailureActivity({\n              threadId: event.payload.threadId,\n              kind: \"provider.user-input.respond.failed\",\n              summary: \"Provider user input response failed\",\n              detail: isUnknownPendingUserInputRequestError(cause)\n                ? stalePendingRequestDetail(\"user-input\", event.payload.requestId)\n                : Cause.pretty(cause),\n              turnId: null,\n              createdAt: event.payload.createdAt,\n              requestId: event.payload.requestId,\n            }),\n          ),\n        );\n    },\n  );\n\n  const processSessionStopRequested = Effect.fn(\"processSessionStopRequested\")(function* (\n    event: Extract<ProviderIntentEvent, { type: \"thread.session-stop-requested\" }>,\n  ) {\n    const thread = yield* resolveThread(event.payload.threadId);\n    if (!thread) {\n      return;\n    }\n\n    const now = event.payload.createdAt;\n    if (thread.session && thread.session.status !== \"stopped\") {\n      yield* providerService.stopSession({ threadId: thread.id });\n    }\n\n    yield* setThreadSession({\n      threadId: thread.id,\n      session: {\n        threadId: thread.id,\n        status: \"stopped\",\n        providerName: thread.session?.providerName ?? null,\n        ...(thread.session?.providerInstanceId !== undefined\n          ? { providerInstanceId: thread.session.providerInstanceId }\n          : {}),\n        runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,\n        activeTurnId: null,\n        lastError: thread.session?.lastError ?? null,\n        updatedAt: now,\n      },\n      createdAt: now,\n    });\n  });\n\n  const processDomainEvent = Effect.fn(\"processDomainEvent\")(function* (\n    event: ProviderIntentEvent,\n  ) {\n    yield* Effect.annotateCurrentSpan({\n      \"orchestration.event_type\": event.type,\n      \"orchestration.thread_id\": event.payload.threadId,\n      ...(event.commandId ? { \"orchestration.command_id\": event.commandId } : {}),\n    });\n    yield* increment(orchestrationEventsProcessedTotal, {\n      eventType: event.type,\n    });\n    switch (event.type) {\n      case \"thread.meta-updated\":\n        yield* threadTitleRegenerationWorker.enqueue(event);\n        return;\n      case \"thread.runtime-mode-set\": {\n        const thread = yield* resolveThread(event.payload.threadId);\n        if (!thread?.session || thread.session.status === \"stopped\") {\n          return;\n        }\n        const cachedModelSelection = threadModelSelections.get(event.payload.threadId);\n        yield* ensureSessionForThread(\n          event.payload.threadId,\n          event.occurredAt,\n          cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},\n        );\n        return;\n      }\n      case \"thread.turn-start-requested\":\n        yield* processTurnStartRequested(event);\n        return;\n      case \"thread.turn-interrupt-requested\":\n        yield* processTurnInterruptRequested(event);\n        return;\n      case \"thread.approval-response-requested\":\n        yield* processApprovalResponseRequested(event);\n        return;\n      case \"thread.user-input-response-requested\":\n        yield* processUserInputResponseRequested(event);\n        return;\n      case \"thread.session-stop-requested\":\n        yield* processSessionStopRequested(event);\n        return;\n    }\n  });\n\n  const processDomainEventSafely = (event: ProviderIntentEvent) =>\n    processDomainEvent(event).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.interrupt;\n        }\n        return Effect.logWarning(\"provider command reactor failed to process event\", {\n          eventType: event.type,\n          cause: Cause.pretty(cause),\n        });\n      }),\n    );\n\n  const worker = yield* makeDrainableWorker(processDomainEventSafely);\n\n  const start: ProviderCommandReactorShape[\"start\"] = Effect.fn(\"start\")(function* () {\n    const interruptedTitleRegenerations = yield* findInterruptedThreadTitleRegenerations().pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.interrupt;\n        }\n        return Effect.logWarning(\n          \"provider command reactor failed to find interrupted title regenerations\",\n          { cause: Cause.pretty(cause) },\n        ).pipe(Effect.as([]));\n      }),\n    );\n    const processEvent = Effect.fn(\"processEvent\")(function* (event: OrchestrationEvent) {\n      if (\n        (event.type === \"thread.meta-updated\" && event.payload.regenerateTitle === true) ||\n        event.type === \"thread.runtime-mode-set\" ||\n        event.type === \"thread.turn-start-requested\" ||\n        event.type === \"thread.turn-interrupt-requested\" ||\n        event.type === \"thread.approval-response-requested\" ||\n        event.type === \"thread.user-input-response-requested\" ||\n        event.type === \"thread.session-stop-requested\"\n      ) {\n        return yield* worker.enqueue(event);\n      }\n    });\n\n    yield* forkParked(Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent));\n\n    // The domain event stream is hot, so work pending before this reactor\n    // starts cannot be resumed. Correlated completions only clear the request\n    // captured here, leaving any newer request untouched.\n    const clearInterrupted = clearInterruptedThreadTitleRegenerations(\n      interruptedTitleRegenerations,\n    ).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.interrupt;\n        }\n        return Effect.logWarning(\n          \"provider command reactor failed to clear interrupted title regenerations\",\n          {\n            cause: Cause.pretty(cause),\n          },\n        );\n      }),\n    );\n    const activation = yield* ServerActivation;\n    if (activation === undefined) {\n      yield* clearInterrupted;\n    } else {\n      yield* forkParked(clearInterrupted);\n    }\n  });\n\n  return {\n    start,\n    drain: Effect.gen(function* () {\n      yield* worker.drain;\n      yield* threadTitleRegenerationWorker.drain;\n    }),\n  } satisfies ProviderCommandReactorShape;\n});\n\nexport const ProviderCommandReactorLive = Layer.effect(ProviderCommandReactor, make);\n","//#region src/constants.ts\nconst DIFFS_TAG_NAME = \"diffs-container\";\nconst DIFFS_DEVELOPMENT_BUILD = (() => {\n\ttry {\n\t\treturn process.env.NODE_ENV === \"development\";\n\t} catch {\n\t\treturn false;\n\t}\n})();\nconst COMMIT_METADATA_SPLIT = /(?=^From [a-f0-9]+ .+$)/m;\nconst GIT_DIFF_FILE_BREAK_REGEX = /(?=^diff --git)/gm;\nconst UNIFIED_DIFF_FILE_BREAK_REGEX = /(?=^---\\s+\\S)/gm;\nconst FILE_CONTEXT_BLOB = /(?=^@@ )/gm;\nconst HUNK_HEADER = /^@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@(?: (.*))?/m;\nconst SPLIT_WITH_NEWLINES = /(?<=\\n)/;\nconst FILENAME_HEADER_REGEX = /^(---|\\+\\+\\+)\\s+([^\\t\\r\\n]+)/;\nconst FILENAME_HEADER_REGEX_GIT = /^(---|\\+\\+\\+)\\s+[ab]\\/([^\\t\\r\\n]+)/;\nconst ALTERNATE_FILE_NAMES_GIT = /^diff --git (?:\"a\\/(.+?)\"|a\\/(.+?)) (?:\"b\\/(.+?)\"|b\\/(.+?))$/;\nconst INDEX_LINE_METADATA = /^index ([0-9a-f]+)\\.\\.([0-9a-f]+)(?: (\\d+))?$/i;\nconst MERGE_CONFLICT_START_MARKER_REGEX = /^<{7,}(?:\\s.*)?$/;\nconst MERGE_CONFLICT_BASE_MARKER_REGEX = /^\\|{7,}(?:\\s.*)?$/;\nconst MERGE_CONFLICT_SEPARATOR_MARKER_REGEX = /^={7,}$/;\nconst MERGE_CONFLICT_END_MARKER_REGEX = /^>{7,}(?:\\s.*)?$/;\nconst HEADER_PREFIX_SLOT_ID = \"header-prefix\";\nconst HEADER_FILENAME_SUFFIX_SLOT_ID = \"header-filename-suffix\";\nconst HEADER_METADATA_SLOT_ID = \"header-metadata\";\nconst CUSTOM_HEADER_SLOT_ID = \"header-custom\";\nconst DEFAULT_THEMES = {\n\tdark: \"pierre-dark\",\n\tlight: \"pierre-light\"\n};\nconst THEME_CSS_ATTRIBUTE = \"data-theme-css\";\nconst UNSAFE_CSS_ATTRIBUTE = \"data-unsafe-css\";\nconst CORE_CSS_ATTRIBUTE = \"data-core-css\";\nconst DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE = \"data-diffs-scrollbar-measure\";\nconst CODE_VIEW_HEADER_ATTRIBUTE = \"data-diffs-code-view-header\";\nconst CODE_VIEW_FOOTER_ATTRIBUTE = \"data-diffs-code-view-footer\";\nconst DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY = \"--diffs-scrollbar-gutter-measured\";\nconst DEFAULT_COLLAPSED_CONTEXT_THRESHOLD = 1;\nconst DEFAULT_TOKENIZE_MAX_LENGTH = 1e5;\nconst DEFAULT_VIRTUAL_FILE_METRICS = {\n\thunkLineCount: 50,\n\tlineHeight: 20,\n\tdiffHeaderHeight: 44,\n\tspacing: 8\n};\nconst DEFAULT_CODE_VIEW_FILE_METRICS = {\n\t...DEFAULT_VIRTUAL_FILE_METRICS,\n\thunkLineCount: 1\n};\nconst DEFAULT_CODE_VIEW_LAYOUT = {\n\tpaddingTop: 8,\n\tpaddingBottom: 8,\n\tgap: 8\n};\nconst DEFAULT_SMOOTH_SCROLL_SETTINGS = {\n\tomega: .015,\n\tpositionEpsilon: .5,\n\tvelocityEpsilon: .05\n};\nconst DEFAULT_EXPANDED_REGION = Object.freeze({\n\tfromStart: 0,\n\tfromEnd: 0\n});\nconst DEFAULT_RENDER_RANGE = {\n\tstartingLine: 0,\n\ttotalLines: Infinity,\n\tbufferBefore: 0,\n\tbufferAfter: 0\n};\nconst EMPTY_RENDER_RANGE = {\n\tstartingLine: 0,\n\ttotalLines: 0,\n\tbufferBefore: 0,\n\tbufferAfter: 0\n};\n//#endregion\nexport { ALTERNATE_FILE_NAMES_GIT, CODE_VIEW_FOOTER_ATTRIBUTE, CODE_VIEW_HEADER_ATTRIBUTE, COMMIT_METADATA_SPLIT, CORE_CSS_ATTRIBUTE, CUSTOM_HEADER_SLOT_ID, DEFAULT_CODE_VIEW_FILE_METRICS, DEFAULT_CODE_VIEW_LAYOUT, DEFAULT_COLLAPSED_CONTEXT_THRESHOLD, DEFAULT_EXPANDED_REGION, DEFAULT_RENDER_RANGE, DEFAULT_SMOOTH_SCROLL_SETTINGS, DEFAULT_THEMES, DEFAULT_TOKENIZE_MAX_LENGTH, DEFAULT_VIRTUAL_FILE_METRICS, DIFFS_DEVELOPMENT_BUILD, DIFFS_SCROLLBAR_GUTTER_MEASURED_PROPERTY, DIFFS_SCROLLBAR_MEASURE_ATTRIBUTE, DIFFS_TAG_NAME, EMPTY_RENDER_RANGE, FILENAME_HEADER_REGEX, FILENAME_HEADER_REGEX_GIT, FILE_CONTEXT_BLOB, GIT_DIFF_FILE_BREAK_REGEX, HEADER_FILENAME_SUFFIX_SLOT_ID, HEADER_METADATA_SLOT_ID, HEADER_PREFIX_SLOT_ID, HUNK_HEADER, INDEX_LINE_METADATA, MERGE_CONFLICT_BASE_MARKER_REGEX, MERGE_CONFLICT_END_MARKER_REGEX, MERGE_CONFLICT_SEPARATOR_MARKER_REGEX, MERGE_CONFLICT_START_MARKER_REGEX, SPLIT_WITH_NEWLINES, THEME_CSS_ATTRIBUTE, UNIFIED_DIFF_FILE_BREAK_REGEX, UNSAFE_CSS_ATTRIBUTE };\n\n//# sourceMappingURL=constants.js.map","//#region src/utils/cleanLastNewline.ts\nfunction cleanLastNewline(contents) {\n\tlet end = contents.length;\n\tif (contents.charCodeAt(end - 1) === 10) {\n\t\tend--;\n\t\tif (contents.charCodeAt(end - 1) === 13) end--;\n\t}\n\treturn contents.slice(0, end);\n}\n//#endregion\nexport { cleanLastNewline };\n\n//# sourceMappingURL=cleanLastNewline.js.map","//#region src/utils/detachString.ts\nconst stringDetachEncoder = new TextEncoder();\nconst stringDetachDecoder = new TextDecoder(\"utf-8\", { ignoreBOM: true });\nconst SURROGATE_CODE_UNIT_PATTERN = /[\\uD800-\\uDFFF]/;\nconst STRING_DETACH_INITIAL_BUFFER_SIZE = 1024;\nlet stringDetachBuffer = new Uint8Array(STRING_DETACH_INITIAL_BUFFER_SIZE);\nfunction releaseStringDetachBuffer() {\n\tif (stringDetachBuffer.length !== STRING_DETACH_INITIAL_BUFFER_SIZE) stringDetachBuffer = new Uint8Array(STRING_DETACH_INITIAL_BUFFER_SIZE);\n}\nfunction detachString(value) {\n\tif (value.length === 0) return value;\n\tif (SURROGATE_CODE_UNIT_PATTERN.test(value)) return JSON.parse(JSON.stringify(value));\n\tconst requiredByteLength = value.length * 3;\n\tif (stringDetachBuffer.length < requiredByteLength) stringDetachBuffer = new Uint8Array(requiredByteLength);\n\tconst { written } = stringDetachEncoder.encodeInto(value, stringDetachBuffer);\n\treturn stringDetachDecoder.decode(stringDetachBuffer.subarray(0, written));\n}\n//#endregion\nexport { detachString, releaseStringDetachBuffer };\n\n//# sourceMappingURL=detachString.js.map","//#region src/utils/realignChangeContent.ts\nconst MAX_ALIGNMENT_COMPARISONS = 4096;\nconst MIN_IMPROVEMENT_PER_PAIR = .5;\n/**\n* Re-split count-mismatched change blocks in every hunk so paired lines are\n* chosen by content similarity instead of position, then slide blank-line\n* insert/delete blocks to the top of their blank run. Mutates `hunks` in\n* place; rendered row counts are unchanged (a split block covers the same\n* split/unified rows as the original).\n*/\nfunction realignChangeContentBySimilarity(diff) {\n\tfor (const hunk of diff.hunks) {\n\t\tfor (let index = 0; index < hunk.hunkContent.length; index++) {\n\t\t\tconst content = hunk.hunkContent[index];\n\t\t\tif (content.type !== \"change\") continue;\n\t\t\tconst replacement = realignChangeBlock(diff, content);\n\t\t\tif (replacement != null) {\n\t\t\t\thunk.hunkContent.splice(index, 1, ...replacement);\n\t\t\t\tindex += replacement.length - 1;\n\t\t\t}\n\t\t}\n\t\tslideBlankBoundaryBlocksUp(hunk, diff);\n\t}\n}\n/**\n* Slide pure insert/delete blocks made entirely of blank lines to the top of\n* the blank run they sit in. Adding or removing a blank line next to\n* existing blanks is ambiguous, and the diff library reports the change at\n* the run's bottom — so pressing Enter at the end of a line marks a blank\n* *below* the caret as inserted while the caret's own new line renders as\n* context. Sliding up anchors the change to the content above it (the caret\n* line after an Enter) instead. Non-blank blocks never slide, so code that\n* merely ends like its neighbor (an added function before an identical `}`)\n* keeps the library's canonical position. Runs on final assembled\n* hunkContent: from the parse post-pass above and from the edit session's\n* region re-diff, so mid-session and exit renderings agree.\n*/\nfunction slideBlankBoundaryBlocksUp(hunk, diff) {\n\tconst { hunkContent } = hunk;\n\tfor (let index = 1; index < hunkContent.length; index++) {\n\t\tconst block = hunkContent[index];\n\t\tconst previous = hunkContent[index - 1];\n\t\tif (block.type !== \"change\" || block.additions > 0 && block.deletions > 0 || previous.type !== \"context\") continue;\n\t\tconst isInsert = block.additions > 0;\n\t\tconst lines = isInsert ? diff.additionLines : diff.deletionLines;\n\t\tconst blockStart = isInsert ? block.additionLineIndex : block.deletionLineIndex;\n\t\tconst blockLength = isInsert ? block.additions : block.deletions;\n\t\tconst unit = lines[blockStart] ?? \"\";\n\t\tif (unit.trim() !== \"\") continue;\n\t\tlet uniform = true;\n\t\tfor (let offset = 1; offset < blockLength; offset++) if (lines[blockStart + offset] !== unit) {\n\t\t\tuniform = false;\n\t\t\tbreak;\n\t\t}\n\t\tif (!uniform) continue;\n\t\tlet slide = 0;\n\t\twhile (slide < previous.lines && diff.additionLines[previous.additionLineIndex + previous.lines - 1 - slide] === unit) slide++;\n\t\tif (slide === 0) continue;\n\t\tblock.additionLineIndex -= slide;\n\t\tblock.deletionLineIndex -= slide;\n\t\tconst blockAdditionEnd = block.additionLineIndex + block.additions;\n\t\tconst blockDeletionEnd = block.deletionLineIndex + block.deletions;\n\t\tconst next = hunkContent[index + 1];\n\t\tif (next?.type === \"context\") {\n\t\t\tnext.lines += slide;\n\t\t\tnext.additionLineIndex = blockAdditionEnd;\n\t\t\tnext.deletionLineIndex = blockDeletionEnd;\n\t\t} else hunkContent.splice(index + 1, 0, {\n\t\t\ttype: \"context\",\n\t\t\tlines: slide,\n\t\t\tadditionLineIndex: blockAdditionEnd,\n\t\t\tdeletionLineIndex: blockDeletionEnd\n\t\t});\n\t\tprevious.lines -= slide;\n\t\tif (previous.lines === 0) {\n\t\t\thunkContent.splice(index - 1, 1);\n\t\t\tindex--;\n\t\t}\n\t}\n}\nfunction realignChangeBlock(diff, content) {\n\tconst { deletions, additions, deletionLineIndex, additionLineIndex } = content;\n\tconst pairCount = Math.min(deletions, additions);\n\tconst surplus = Math.abs(additions - deletions);\n\tif (pairCount === 0 || surplus === 0 || pairCount * (surplus + 1) > MAX_ALIGNMENT_COMPARISONS) return null;\n\tconst strippedDeletions = [];\n\tfor (let line = 0; line < deletions; line++) strippedDeletions.push(stripWhitespace(diff.deletionLines[deletionLineIndex + line] ?? \"\"));\n\tconst strippedAdditions = [];\n\tfor (let line = 0; line < additions; line++) strippedAdditions.push(stripWhitespace(diff.additionLines[additionLineIndex + line] ?? \"\"));\n\tconst additionsAreLonger = additions > deletions;\n\tlet bestOffset = 0;\n\tlet bestScore = -1;\n\tfor (let offset = 0; offset <= surplus; offset++) {\n\t\tlet score = 0;\n\t\tfor (let pair = 0; pair < pairCount; pair++) score += lineSimilarity(strippedDeletions[pair + (additionsAreLonger ? 0 : offset)], strippedAdditions[pair + (additionsAreLonger ? offset : 0)]);\n\t\tif (offset === 0) bestScore = score + pairCount * MIN_IMPROVEMENT_PER_PAIR;\n\t\telse if (score > bestScore) {\n\t\t\tbestScore = score;\n\t\t\tbestOffset = offset;\n\t\t}\n\t}\n\tif (bestOffset === 0) return null;\n\tconst blocks = [];\n\tconst pushBlock = (blockDeletions, blockAdditions, blockDeletionIndex, blockAdditionIndex) => {\n\t\tif (blockDeletions > 0 || blockAdditions > 0) blocks.push({\n\t\t\ttype: \"change\",\n\t\t\tdeletions: blockDeletions,\n\t\t\tadditions: blockAdditions,\n\t\t\tdeletionLineIndex: blockDeletionIndex,\n\t\t\tadditionLineIndex: blockAdditionIndex\n\t\t});\n\t};\n\tif (additionsAreLonger) {\n\t\tpushBlock(0, bestOffset, deletionLineIndex, additionLineIndex);\n\t\tpushBlock(pairCount, pairCount, deletionLineIndex, additionLineIndex + bestOffset);\n\t\tpushBlock(0, additions - pairCount - bestOffset, deletionLineIndex + pairCount, additionLineIndex + bestOffset + pairCount);\n\t} else {\n\t\tpushBlock(bestOffset, 0, deletionLineIndex, additionLineIndex);\n\t\tpushBlock(pairCount, pairCount, deletionLineIndex + bestOffset, additionLineIndex);\n\t\tpushBlock(deletions - pairCount - bestOffset, 0, deletionLineIndex + bestOffset + pairCount, additionLineIndex + pairCount);\n\t}\n\treturn blocks;\n}\nconst WHITESPACE = /\\s+/g;\nfunction stripWhitespace(line) {\n\treturn line.replace(WHITESPACE, \"\");\n}\nfunction lineSimilarity(a, b) {\n\tif (a === b) return 1;\n\tconst maxLength = Math.max(a.length, b.length);\n\tconst minLength = Math.min(a.length, b.length);\n\tif (minLength === 0) return 0;\n\tlet prefix = 0;\n\twhile (prefix < minLength && a[prefix] === b[prefix]) prefix++;\n\tlet suffix = 0;\n\twhile (suffix < minLength - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++;\n\treturn (prefix + suffix) / maxLength;\n}\n//#endregion\nexport { realignChangeContentBySimilarity, slideBlankBoundaryBlocksUp };\n\n//# sourceMappingURL=realignChangeContent.js.map","import { ALTERNATE_FILE_NAMES_GIT, COMMIT_METADATA_SPLIT, FILENAME_HEADER_REGEX, FILENAME_HEADER_REGEX_GIT, GIT_DIFF_FILE_BREAK_REGEX, INDEX_LINE_METADATA } from \"../constants.js\";\nimport { cleanLastNewline } from \"./cleanLastNewline.js\";\nimport { detachString, releaseStringDetachBuffer } from \"./detachString.js\";\nimport { realignChangeContentBySimilarity } from \"./realignChangeContent.js\";\n//#region src/utils/parsePatchFiles.ts\nfunction processPatch(data, cacheKeyPrefix, throwOnError) {\n\ttry {\n\t\treturn _processPatch(data, cacheKeyPrefix, throwOnError);\n\t} finally {\n\t\treleaseStringDetachBuffer();\n\t}\n}\nfunction _processPatch(data, cacheKeyPrefix, throwOnError = false) {\n\tconst isGitDiff = isGitDiffPatch(data);\n\tconst rawFiles = isGitDiff ? splitGitDiffFiles(data) : splitUnifiedDiffFiles(data);\n\tlet patchMetadata;\n\tconst files = [];\n\tfor (const fileOrPatchMetadata of rawFiles) {\n\t\tif (isGitDiff && !GIT_DIFF_FILE_BREAK_REGEX.test(fileOrPatchMetadata)) {\n\t\t\tif (patchMetadata == null) patchMetadata = detachString(fileOrPatchMetadata);\n\t\t\telse if (throwOnError) throw Error(\"parsePatchContent: unknown file blob\");\n\t\t\telse console.error(\"parsePatchContent: unknown file blob:\", fileOrPatchMetadata);\n\t\t\tcontinue;\n\t\t} else if (!isGitDiff && !startsWithUnifiedDiffFileHeader(fileOrPatchMetadata)) {\n\t\t\tif (patchMetadata == null) patchMetadata = detachString(fileOrPatchMetadata);\n\t\t\telse if (throwOnError) throw Error(\"parsePatchContent: unknown file blob\");\n\t\t\telse console.error(\"parsePatchContent: unknown file blob:\", fileOrPatchMetadata);\n\t\t\tcontinue;\n\t\t}\n\t\tconst currentFile = _processFile(fileOrPatchMetadata, {\n\t\t\tcacheKey: cacheKeyPrefix != null ? `${cacheKeyPrefix}-${files.length}` : void 0,\n\t\t\tisGitDiff,\n\t\t\tthrowOnError\n\t\t});\n\t\tif (currentFile != null) files.push(currentFile);\n\t}\n\treturn {\n\t\tpatchMetadata,\n\t\tfiles\n\t};\n}\nfunction processFile(fileDiffString, options) {\n\ttry {\n\t\treturn _processFile(fileDiffString, options);\n\t} finally {\n\t\treleaseStringDetachBuffer();\n\t}\n}\nfunction _processFile(fileDiffString, { cacheKey, isGitDiff = GIT_DIFF_FILE_BREAK_REGEX.test(fileDiffString), oldFile, newFile, throwOnError = false } = {}) {\n\tlet lastHunkEnd = 0;\n\tconst hunks = splitAtLinePrefix(fileDiffString, \"@@ \");\n\tlet currentFile;\n\tconst isPartial = oldFile == null || newFile == null;\n\tlet deletionLineIndex = 0;\n\tlet additionLineIndex = 0;\n\tfor (const hunk of hunks) {\n\t\tconst lines = splitWithNewlines(hunk);\n\t\tconst firstLine = lines[0];\n\t\tif (firstLine == null) {\n\t\t\tif (throwOnError) throw Error(\"parsePatchContent: invalid hunk\");\n\t\t\telse console.error(\"parsePatchContent: invalid hunk\", hunk);\n\t\t\tcontinue;\n\t\t}\n\t\tconst fileHeader = parseHunkHeader(firstLine);\n\t\tlet additionLines = 0;\n\t\tlet deletionLines = 0;\n\t\tif (fileHeader == null || currentFile == null) {\n\t\t\tif (currentFile != null) {\n\t\t\t\tif (throwOnError) throw Error(\"parsePatchContent: Invalid hunk\");\n\t\t\t\telse console.error(\"parsePatchContent: Invalid hunk\", hunk);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcurrentFile = {\n\t\t\t\tname: \"\",\n\t\t\t\ttype: \"change\",\n\t\t\t\thunks: [],\n\t\t\t\tsplitLineCount: 0,\n\t\t\t\tunifiedLineCount: 0,\n\t\t\t\tisPartial,\n\t\t\t\tadditionLines: !isPartial && oldFile != null && newFile != null ? splitFileContents(newFile.contents) : [],\n\t\t\t\tdeletionLines: !isPartial && oldFile != null && newFile != null ? splitFileContents(oldFile.contents) : [],\n\t\t\t\tcacheKey: maybeDetachOptionalString(cacheKey)\n\t\t\t};\n\t\t\tif (currentFile.additionLines.length === 1 && newFile?.contents === \"\") currentFile.additionLines.length = 0;\n\t\t\tif (currentFile.deletionLines.length === 1 && oldFile?.contents === \"\") currentFile.deletionLines.length = 0;\n\t\t\tfor (const line of lines) {\n\t\t\t\tif (line.startsWith(\"diff --git\")) {\n\t\t\t\t\tconst filenameMatch = line.trim().match(ALTERNATE_FILE_NAMES_GIT);\n\t\t\t\t\tconst prevName = filenameMatch?.[1] ?? filenameMatch?.[2];\n\t\t\t\t\tconst name = filenameMatch?.[3] ?? filenameMatch?.[4];\n\t\t\t\t\tif (prevName == null || name == null) {\n\t\t\t\t\t\tif (throwOnError) throw Error(\"parsePatchContent: invalid git diff header\");\n\t\t\t\t\t\telse console.error(\"parsePatchContent: invalid git diff header\", line);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tcurrentFile.name = detachString(name.trim());\n\t\t\t\t\tif (prevName !== name) currentFile.prevName = detachString(prevName.trim());\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst filenameMatch = line.startsWith(\"---\") || line.startsWith(\"+++\") ? line.match(isGitDiff ? FILENAME_HEADER_REGEX_GIT : FILENAME_HEADER_REGEX) : null;\n\t\t\t\tif (filenameMatch != null) {\n\t\t\t\t\tconst [, type, fileName] = filenameMatch;\n\t\t\t\t\tif (type === \"---\" && fileName !== \"/dev/null\") {\n\t\t\t\t\t\tconst detachedFileName = detachString(fileName.trim());\n\t\t\t\t\t\tcurrentFile.prevName = detachedFileName;\n\t\t\t\t\t\tcurrentFile.name = detachedFileName;\n\t\t\t\t\t} else if (type === \"+++\" && fileName !== \"/dev/null\") currentFile.name = detachString(fileName.trim());\n\t\t\t\t} else if (isGitDiff) {\n\t\t\t\t\tif (line.startsWith(\"new mode \")) currentFile.mode = detachString(line.slice(8).trim());\n\t\t\t\t\tif (line.startsWith(\"old mode \")) currentFile.prevMode = detachString(line.slice(8).trim());\n\t\t\t\t\tif (line.startsWith(\"new file mode\")) {\n\t\t\t\t\t\tcurrentFile.type = \"new\";\n\t\t\t\t\t\tcurrentFile.mode = detachString(line.slice(13).trim());\n\t\t\t\t\t}\n\t\t\t\t\tif (line.startsWith(\"deleted file mode\")) {\n\t\t\t\t\t\tcurrentFile.type = \"deleted\";\n\t\t\t\t\t\tcurrentFile.mode = detachString(line.slice(17).trim());\n\t\t\t\t\t}\n\t\t\t\t\tif (line.startsWith(\"similarity index\")) if (line.startsWith(\"similarity index 100%\")) currentFile.type = \"rename-pure\";\n\t\t\t\t\telse currentFile.type = \"rename-changed\";\n\t\t\t\t\tif (line.startsWith(\"index \")) {\n\t\t\t\t\t\tconst [, prevObjectId, newObjectId, mode] = line.trim().match(INDEX_LINE_METADATA) ?? [];\n\t\t\t\t\t\tif (prevObjectId != null) currentFile.prevObjectId = detachString(prevObjectId);\n\t\t\t\t\t\tif (newObjectId != null) currentFile.newObjectId = detachString(newObjectId);\n\t\t\t\t\t\tif (mode != null) currentFile.mode = detachString(mode);\n\t\t\t\t\t}\n\t\t\t\t\tif (line.startsWith(\"rename from \")) currentFile.prevName = detachString(line.slice(12).trim());\n\t\t\t\t\tif (line.startsWith(\"rename to \")) currentFile.name = detachString(line.slice(10).trim());\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tlet currentContent;\n\t\tlet lastLineType;\n\t\twhile (lines.length > 0 && (lines[lines.length - 1] === \"\\n\" || lines[lines.length - 1] === \"\\r\" || lines[lines.length - 1] === \"\\r\\n\" || lines[lines.length - 1] === \"\")) lines.pop();\n\t\tconst { additionStart, deletionStart } = fileHeader;\n\t\tdeletionLineIndex = isPartial ? deletionLineIndex : deletionStart - 1;\n\t\tadditionLineIndex = isPartial ? additionLineIndex : additionStart - 1;\n\t\tconst hunkData = {\n\t\t\tcollapsedBefore: 0,\n\t\t\tsplitLineCount: 0,\n\t\t\tsplitLineStart: 0,\n\t\t\tunifiedLineCount: 0,\n\t\t\tunifiedLineStart: 0,\n\t\t\tadditionCount: fileHeader.additionCount,\n\t\t\tadditionStart,\n\t\t\tadditionLines,\n\t\t\tdeletionCount: fileHeader.deletionCount,\n\t\t\tdeletionStart,\n\t\t\tdeletionLines,\n\t\t\tdeletionLineIndex,\n\t\t\tadditionLineIndex,\n\t\t\thunkContent: [],\n\t\t\thunkContext: maybeDetachOptionalString(fileHeader.hunkContext),\n\t\t\thunkSpecs: detachString(firstLine),\n\t\t\tnoEOFCRAdditions: false,\n\t\t\tnoEOFCRDeletions: false\n\t\t};\n\t\tlet parsedAdditionLines = 0;\n\t\tlet parsedDeletionLines = 0;\n\t\tfor (let lineIndex = 1; lineIndex < lines.length; lineIndex++) {\n\t\t\tconst rawLine = lines[lineIndex];\n\t\t\tif (parsedAdditionLines >= hunkData.additionCount && parsedDeletionLines >= hunkData.deletionCount && !rawLine.startsWith(\"\\\\\")) {\n\t\t\t\tif (throwOnError && isHunkBodyLine(rawLine) && !isFormatPatchVersionSeparator(rawLine)) throw Error(\"parsePatchContent: hunk has more lines than expected\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tconst firstChar = rawLine[0];\n\t\t\tif (firstChar !== \"+\" && firstChar !== \"-\" && firstChar !== \" \" && firstChar !== \"\\\\\") {\n\t\t\t\tif (throwOnError) throw Error(\"parsePatchContent: invalid hunk line\");\n\t\t\t\tconsole.error(`parseLineType: Invalid firstChar: \"${firstChar}\", full line: \"${rawLine}\"`);\n\t\t\t\tconsole.error(\"processFile: invalid rawLine:\", rawLine);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst type = parseRawLineType(firstChar);\n\t\t\tif (type === \"addition\") {\n\t\t\t\tif (throwOnError && parsedAdditionLines >= hunkData.additionCount) throw Error(\"parsePatchContent: hunk has too many addition lines\");\n\t\t\t\tconst line = getParsedLineContent(rawLine);\n\t\t\t\tif (currentContent == null || currentContent.type !== \"change\") {\n\t\t\t\t\tcurrentContent = createContentGroup(\"change\", deletionLineIndex, additionLineIndex);\n\t\t\t\t\thunkData.hunkContent.push(currentContent);\n\t\t\t\t}\n\t\t\t\tadditionLineIndex++;\n\t\t\t\tparsedAdditionLines++;\n\t\t\t\tif (isPartial) currentFile.additionLines.push(line);\n\t\t\t\tcurrentContent.additions++;\n\t\t\t\tadditionLines++;\n\t\t\t\tlastLineType = \"addition\";\n\t\t\t} else if (type === \"deletion\") {\n\t\t\t\tif (throwOnError && parsedDeletionLines >= hunkData.deletionCount) throw Error(\"parsePatchContent: hunk has too many deletion lines\");\n\t\t\t\tconst line = getParsedLineContent(rawLine);\n\t\t\t\tif (currentContent == null || currentContent.type !== \"change\") {\n\t\t\t\t\tcurrentContent = createContentGroup(\"change\", deletionLineIndex, additionLineIndex);\n\t\t\t\t\thunkData.hunkContent.push(currentContent);\n\t\t\t\t}\n\t\t\t\tdeletionLineIndex++;\n\t\t\t\tparsedDeletionLines++;\n\t\t\t\tif (isPartial) currentFile.deletionLines.push(line);\n\t\t\t\tcurrentContent.deletions++;\n\t\t\t\tdeletionLines++;\n\t\t\t\tlastLineType = \"deletion\";\n\t\t\t} else if (type === \"context\") {\n\t\t\t\tif (throwOnError && (parsedDeletionLines >= hunkData.deletionCount || parsedAdditionLines >= hunkData.additionCount)) throw Error(\"parsePatchContent: hunk has too many context lines\");\n\t\t\t\tconst line = getParsedLineContent(rawLine);\n\t\t\t\tif (currentContent == null || currentContent.type !== \"context\") {\n\t\t\t\t\tcurrentContent = createContentGroup(\"context\", deletionLineIndex, additionLineIndex);\n\t\t\t\t\thunkData.hunkContent.push(currentContent);\n\t\t\t\t}\n\t\t\t\tadditionLineIndex++;\n\t\t\t\tdeletionLineIndex++;\n\t\t\t\tparsedAdditionLines++;\n\t\t\t\tparsedDeletionLines++;\n\t\t\t\tif (isPartial) {\n\t\t\t\t\tcurrentFile.deletionLines.push(line);\n\t\t\t\t\tcurrentFile.additionLines.push(line);\n\t\t\t\t}\n\t\t\t\tcurrentContent.lines++;\n\t\t\t\tlastLineType = \"context\";\n\t\t\t} else if (type === \"metadata\" && currentContent != null) {\n\t\t\t\tif (currentContent.type === \"context\") {\n\t\t\t\t\thunkData.noEOFCRAdditions = true;\n\t\t\t\t\thunkData.noEOFCRDeletions = true;\n\t\t\t\t} else if (lastLineType === \"deletion\") hunkData.noEOFCRDeletions = true;\n\t\t\t\telse if (lastLineType === \"addition\") hunkData.noEOFCRAdditions = true;\n\t\t\t\tif (isPartial && (lastLineType === \"addition\" || lastLineType === \"context\")) {\n\t\t\t\t\tconst lastIndex = currentFile.additionLines.length - 1;\n\t\t\t\t\tif (lastIndex >= 0) currentFile.additionLines[lastIndex] = cleanLastNewline(currentFile.additionLines[lastIndex]);\n\t\t\t\t}\n\t\t\t\tif (isPartial && (lastLineType === \"deletion\" || lastLineType === \"context\")) {\n\t\t\t\t\tconst lastIndex = currentFile.deletionLines.length - 1;\n\t\t\t\t\tif (lastIndex >= 0) currentFile.deletionLines[lastIndex] = cleanLastNewline(currentFile.deletionLines[lastIndex]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (throwOnError && (parsedAdditionLines !== hunkData.additionCount || parsedDeletionLines !== hunkData.deletionCount)) throw Error(\"parsePatchContent: hunk line count mismatch\");\n\t\thunkData.additionLines = additionLines;\n\t\thunkData.deletionLines = deletionLines;\n\t\thunkData.collapsedBefore = Math.max(hunkData.additionStart - 1 - lastHunkEnd, 0);\n\t\tcurrentFile.hunks.push(hunkData);\n\t\tlastHunkEnd = hunkData.additionStart + hunkData.additionCount - 1;\n\t\tfor (const content of hunkData.hunkContent) if (content.type === \"context\") {\n\t\t\thunkData.splitLineCount += content.lines;\n\t\t\thunkData.unifiedLineCount += content.lines;\n\t\t} else {\n\t\t\thunkData.splitLineCount += Math.max(content.additions, content.deletions);\n\t\t\thunkData.unifiedLineCount += content.deletions + content.additions;\n\t\t}\n\t\thunkData.splitLineStart = currentFile.splitLineCount + hunkData.collapsedBefore;\n\t\thunkData.unifiedLineStart = currentFile.unifiedLineCount + hunkData.collapsedBefore;\n\t\tcurrentFile.splitLineCount += hunkData.collapsedBefore + hunkData.splitLineCount;\n\t\tcurrentFile.unifiedLineCount += hunkData.collapsedBefore + hunkData.unifiedLineCount;\n\t}\n\tif (currentFile == null) return;\n\tif (throwOnError && isPartial && !isGitDiff && currentFile.hunks.length === 0) throw Error(\"parsePatchContent: unified file has no hunks\");\n\tif (currentFile.hunks.length > 0 && !isPartial && currentFile.additionLines.length > 0 && currentFile.deletionLines.length > 0) {\n\t\tconst lastHunk = currentFile.hunks[currentFile.hunks.length - 1];\n\t\tconst lastHunkEnd = lastHunk.additionStart + lastHunk.additionCount - 1;\n\t\tconst totalFileLines = currentFile.additionLines.length;\n\t\tconst collapsedAfter = Math.max(totalFileLines - lastHunkEnd, 0);\n\t\tcurrentFile.splitLineCount += collapsedAfter;\n\t\tcurrentFile.unifiedLineCount += collapsedAfter;\n\t}\n\tif (!isGitDiff) {\n\t\tif (currentFile.prevName != null && currentFile.name !== currentFile.prevName) if (currentFile.hunks.length > 0) currentFile.type = \"rename-changed\";\n\t\telse currentFile.type = \"rename-pure\";\n\t\telse if ((oldFile == null || oldFile.contents === \"\") && newFile != null && newFile.contents !== \"\") currentFile.type = \"new\";\n\t\telse if (oldFile != null && oldFile.contents !== \"\" && (newFile == null || newFile.contents === \"\")) currentFile.type = \"deleted\";\n\t}\n\tif (currentFile.type !== \"rename-pure\" && currentFile.type !== \"rename-changed\") currentFile.prevName = void 0;\n\trealignChangeContentBySimilarity(currentFile);\n\treturn currentFile;\n}\n/**\n* Parses a patch file string into an array of parsed patches.\n*\n* @param data - The raw patch file content (supports multi-commit patches)\n* @param cacheKeyPrefix - Optional prefix for generating cache keys. When provided,\n*   each file in the patch will get a cache key in the format `prefix-patchIndex-fileIndex`.\n*   This enables caching of rendered diff results in the worker pool.\n*/\nfunction parsePatchFiles(data, cacheKeyPrefix, throwOnError = false) {\n\tconst patches = [];\n\tconst rawPatches = hasCommitMetadataBoundary(data) ? data.split(COMMIT_METADATA_SPLIT) : [data];\n\tfor (const patch of rawPatches) try {\n\t\tpatches.push(processPatch(patch, cacheKeyPrefix != null ? `${cacheKeyPrefix}-${patches.length}` : void 0, throwOnError));\n\t} catch (error) {\n\t\tif (throwOnError) throw error;\n\t\telse console.error(error);\n\t}\n\treturn patches;\n}\nfunction hasCommitMetadataBoundary(data) {\n\treturn data.startsWith(\"From \") || data.includes(\"\\nFrom \");\n}\nfunction splitFileContents(contents) {\n\tconst lines = splitWithNewlines(contents);\n\tfor (let index = 0; index < lines.length; index++) lines[index] = detachString(lines[index]);\n\treturn lines;\n}\nfunction splitWithNewlines(contents) {\n\tif (contents.length === 0) return [\"\"];\n\tconst lines = [];\n\tlet startIndex = 0;\n\tfor (;;) {\n\t\tconst newlineIndex = contents.indexOf(\"\\n\", startIndex);\n\t\tif (newlineIndex === -1) break;\n\t\tlines.push(contents.slice(startIndex, newlineIndex + 1));\n\t\tstartIndex = newlineIndex + 1;\n\t}\n\tif (startIndex < contents.length) lines.push(contents.slice(startIndex));\n\treturn lines;\n}\nfunction splitGitDiffFiles(contents) {\n\treturn splitAtLinePrefix(contents, \"diff --git\");\n}\nfunction splitUnifiedDiffFiles(contents) {\n\tif (contents.length === 0) return [\"\"];\n\tconst parts = [];\n\tlet partStartIndex = 0;\n\tlet lineStartIndex = 0;\n\tlet remainingDeletionLines = 0;\n\tlet remainingAdditionLines = 0;\n\tlet hasOpenedUnifiedFile = false;\n\twhile (lineStartIndex < contents.length) {\n\t\tconst nextLineStartIndex = getNextLineStartIndex(contents, lineStartIndex);\n\t\tif (remainingDeletionLines <= 0 && remainingAdditionLines <= 0) {\n\t\t\tif (isUnifiedDiffFileHeaderAt(contents, lineStartIndex)) {\n\t\t\t\tif (lineStartIndex > partStartIndex) parts.push(contents.slice(partStartIndex, lineStartIndex));\n\t\t\t\tpartStartIndex = lineStartIndex;\n\t\t\t\thasOpenedUnifiedFile = true;\n\t\t\t\tlineStartIndex = getNextLineStartIndex(contents, nextLineStartIndex);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (hasOpenedUnifiedFile && contents.startsWith(\"@@ -\", lineStartIndex)) {\n\t\t\t\tconst fileHeader = parseHunkHeader(contents.slice(lineStartIndex, nextLineStartIndex));\n\t\t\t\tif (fileHeader != null) {\n\t\t\t\t\tremainingDeletionLines = fileHeader.deletionCount;\n\t\t\t\t\tremainingAdditionLines = fileHeader.additionCount;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlineStartIndex = nextLineStartIndex;\n\t\t\tcontinue;\n\t\t}\n\t\tconst firstChar = contents[lineStartIndex];\n\t\tif (firstChar === \"\\\\\") {\n\t\t\tlineStartIndex = nextLineStartIndex;\n\t\t\tcontinue;\n\t\t}\n\t\tif (firstChar === \" \") {\n\t\t\tremainingDeletionLines = Math.max(remainingDeletionLines - 1, 0);\n\t\t\tremainingAdditionLines = Math.max(remainingAdditionLines - 1, 0);\n\t\t} else if (firstChar === \"-\") remainingDeletionLines = Math.max(remainingDeletionLines - 1, 0);\n\t\telse if (firstChar === \"+\") remainingAdditionLines = Math.max(remainingAdditionLines - 1, 0);\n\t\tlineStartIndex = nextLineStartIndex;\n\t}\n\tparts.push(contents.slice(partStartIndex));\n\treturn parts;\n}\nfunction startsWithUnifiedDiffFileHeader(contents) {\n\treturn isUnifiedDiffFileHeaderAt(contents, 0);\n}\nfunction isUnifiedDiffFileHeaderAt(contents, lineStartIndex) {\n\tconst nextLineStartIndex = getNextLineStartIndex(contents, lineStartIndex);\n\treturn isUnifiedDiffHeaderLineAt(contents, lineStartIndex, \"---\") && isUnifiedDiffHeaderLineAt(contents, nextLineStartIndex, \"+++\");\n}\nfunction isUnifiedDiffHeaderLineAt(contents, lineStartIndex, prefix) {\n\tif (!contents.startsWith(prefix, lineStartIndex)) return false;\n\tconst separator = contents[lineStartIndex + prefix.length];\n\tif (separator !== \" \" && separator !== \"\t\") return false;\n\tfor (let index = lineStartIndex + prefix.length + 1; index < contents.length; index++) {\n\t\tconst char = contents[index];\n\t\tif (char === \"\\n\" || char === \"\\r\") break;\n\t\tif (char !== \" \" && char !== \"\t\") return true;\n\t}\n\treturn false;\n}\nfunction getNextLineStartIndex(contents, lineStartIndex) {\n\tconst newlineIndex = contents.indexOf(\"\\n\", lineStartIndex);\n\treturn newlineIndex === -1 ? contents.length : newlineIndex + 1;\n}\nfunction isHunkBodyLine(line) {\n\tconst firstChar = line[0];\n\treturn firstChar === \"+\" || firstChar === \"-\" || firstChar === \" \";\n}\nfunction isFormatPatchVersionSeparator(line) {\n\tif (!line.startsWith(\"--\")) return false;\n\tfor (let index = 2; index < line.length; index++) {\n\t\tconst char = line[index];\n\t\tif (char !== \" \" && char !== \"\t\" && char !== \"\\n\" && char !== \"\\r\") return false;\n\t}\n\treturn true;\n}\nfunction parseHunkHeader(line) {\n\tif (!line.startsWith(\"@@ -\")) return;\n\tlet index = 4;\n\tconst deletionStartResult = readPositiveInteger(line, index);\n\tif (deletionStartResult == null) return;\n\tconst deletionStart = deletionStartResult.value;\n\tindex = deletionStartResult.endIndex;\n\tlet deletionCount = 1;\n\tif (line[index] === \",\") {\n\t\tconst deletionCountResult = readPositiveInteger(line, index + 1);\n\t\tif (deletionCountResult == null) return;\n\t\tdeletionCount = deletionCountResult.value;\n\t\tindex = deletionCountResult.endIndex;\n\t}\n\tif (line[index] !== \" \" || line[index + 1] !== \"+\") return;\n\tindex += 2;\n\tconst additionStartResult = readPositiveInteger(line, index);\n\tif (additionStartResult == null) return;\n\tconst additionStart = additionStartResult.value;\n\tindex = additionStartResult.endIndex;\n\tlet additionCount = 1;\n\tif (line[index] === \",\") {\n\t\tconst additionCountResult = readPositiveInteger(line, index + 1);\n\t\tif (additionCountResult == null) return;\n\t\tadditionCount = additionCountResult.value;\n\t\tindex = additionCountResult.endIndex;\n\t}\n\tif (line[index] !== \" \" || line[index + 1] !== \"@\" || line[index + 2] !== \"@\") return;\n\tlet hunkContext;\n\tconst contextStartIndex = index + 3;\n\tif (line[contextStartIndex] === \" \") hunkContext = trimLineEnd(line.slice(contextStartIndex + 1));\n\treturn {\n\t\tadditionCount,\n\t\tadditionStart,\n\t\tdeletionCount,\n\t\tdeletionStart,\n\t\thunkContext\n\t};\n}\nfunction readPositiveInteger(value, startIndex) {\n\tlet index = startIndex;\n\tlet parsedValue = 0;\n\tfor (; index < value.length; index++) {\n\t\tconst digit = value.charCodeAt(index) - 48;\n\t\tif (digit < 0 || digit > 9) break;\n\t\tparsedValue = parsedValue * 10 + digit;\n\t}\n\tif (index === startIndex) return;\n\treturn {\n\t\tvalue: parsedValue,\n\t\tendIndex: index\n\t};\n}\nfunction trimLineEnd(value) {\n\tif (value.endsWith(\"\\r\\n\")) return value.slice(0, -2);\n\tif (value.endsWith(\"\\n\")) return value.slice(0, -1);\n\treturn value;\n}\nfunction isGitDiffPatch(data) {\n\treturn data.startsWith(\"diff --git\") || data.includes(\"\\ndiff --git\");\n}\nfunction splitAtLinePrefix(contents, prefix) {\n\tif (contents.length === 0) return [\"\"];\n\tconst newlinePrefix = `\\n${prefix}`;\n\tconst firstBoundaryIndex = contents.startsWith(prefix) ? 0 : findLinePrefixIndex(contents, newlinePrefix, 0);\n\tif (firstBoundaryIndex === -1) return [contents];\n\tconst parts = [];\n\tif (firstBoundaryIndex > 0) parts.push(contents.slice(0, firstBoundaryIndex));\n\tlet startIndex = firstBoundaryIndex;\n\tfor (;;) {\n\t\tconst nextBoundaryIndex = findLinePrefixIndex(contents, newlinePrefix, startIndex + 1);\n\t\tif (nextBoundaryIndex === -1) break;\n\t\tparts.push(contents.slice(startIndex, nextBoundaryIndex));\n\t\tstartIndex = nextBoundaryIndex;\n\t}\n\tparts.push(contents.slice(startIndex));\n\treturn parts;\n}\nfunction findLinePrefixIndex(contents, newlinePrefix, fromIndex) {\n\tconst index = contents.indexOf(newlinePrefix, fromIndex);\n\treturn index === -1 ? -1 : index + 1;\n}\nfunction maybeDetachOptionalString(value) {\n\treturn value == null ? value : detachString(value);\n}\nfunction parseRawLineType(firstChar) {\n\treturn firstChar === \" \" ? \"context\" : firstChar === \"\\\\\" ? \"metadata\" : firstChar === \"+\" ? \"addition\" : \"deletion\";\n}\nfunction getParsedLineContent(rawLine) {\n\tconst processedLine = rawLine.slice(1);\n\treturn detachString(processedLine === \"\" ? \"\\n\" : processedLine);\n}\nfunction createContentGroup(type, deletionLineIndex, additionLineIndex) {\n\tif (type === \"change\") return {\n\t\ttype: \"change\",\n\t\tadditions: 0,\n\t\tdeletions: 0,\n\t\tadditionLineIndex,\n\t\tdeletionLineIndex\n\t};\n\treturn {\n\t\ttype: \"context\",\n\t\tlines: 0,\n\t\tadditionLineIndex,\n\t\tdeletionLineIndex\n\t};\n}\n//#endregion\nexport { parsePatchFiles, processFile, processPatch };\n\n//# sourceMappingURL=parsePatchFiles.js.map","import { parsePatchFiles } from \"@pierre/diffs/utils/parsePatchFiles\";\n\nexport interface TurnDiffFileSummary {\n  readonly path: string;\n  readonly additions: number;\n  readonly deletions: number;\n}\n\nexport function parseTurnDiffFilesFromUnifiedDiff(\n  diff: string,\n): ReadonlyArray<TurnDiffFileSummary> {\n  const normalized = diff.replace(/\\r\\n/g, \"\\n\").trim();\n  if (normalized.length === 0) {\n    return [];\n  }\n\n  const parsedPatches = parsePatchFiles(normalized);\n  const files = parsedPatches.flatMap((patch) =>\n    patch.files.map((file) => ({\n      path: file.name,\n      additions: file.hunks.reduce((total, hunk) => total + hunk.additionLines, 0),\n      deletions: file.hunks.reduce((total, hunk) => total + hunk.deletionLines, 0),\n    })),\n  );\n\n  return files.toSorted((left, right) => left.path.localeCompare(right.path));\n}\n","import {\n  CommandId,\n  type CheckpointRef,\n  EventId,\n  MessageId,\n  type ProjectId,\n  ThreadId,\n  TurnId,\n  type OrchestrationEvent,\n  type ProviderRuntimeEvent,\n  type VcsStatusLocalResult,\n} from \"@t3tools/contracts\";\nimport * as Cause from \"effect/Cause\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport type * as PlatformError from \"effect/PlatformError\";\nimport * as Stream from \"effect/Stream\";\nimport { makeDrainableWorker } from \"@t3tools/shared/DrainableWorker\";\nimport { isTemporaryWorktreeBranch } from \"@t3tools/shared/git\";\n\nimport { parseTurnDiffFilesFromUnifiedDiff } from \"../../checkpointing/Diffs.ts\";\nimport {\n  checkpointRefForThreadTurn,\n  resolveThreadWorkspaceCwd,\n} from \"../../checkpointing/Utils.ts\";\nimport * as CheckpointStore from \"../../checkpointing/CheckpointStore.ts\";\nimport { ProviderService } from \"../../provider/Services/ProviderService.ts\";\nimport { CheckpointReactor, type CheckpointReactorShape } from \"../Services/CheckpointReactor.ts\";\nimport { forkParked } from \"../../serverActivation.ts\";\nimport { OrchestrationEngineService } from \"../Services/OrchestrationEngine.ts\";\nimport { ProjectionSnapshotQuery } from \"../Services/ProjectionSnapshotQuery.ts\";\nimport { RuntimeReceiptBus } from \"../Services/RuntimeReceiptBus.ts\";\nimport type { CheckpointStoreError } from \"../../checkpointing/Errors.ts\";\nimport type { OrchestrationDispatchError } from \"../Errors.ts\";\nimport { isGitRepository } from \"../../git/Utils.ts\";\nimport { VcsStatusBroadcaster } from \"../../vcs/VcsStatusBroadcaster.ts\";\nimport * as WorkspaceEntries from \"../../workspace/WorkspaceEntries.ts\";\n\nconst nowIso = Effect.map(DateTime.now, DateTime.formatIso);\n\ntype ReactorInput =\n  | {\n      readonly source: \"runtime\";\n      readonly event: ProviderRuntimeEvent;\n    }\n  | {\n      readonly source: \"domain\";\n      readonly event: OrchestrationEvent;\n    };\n\nfunction toTurnId(value: string | undefined): TurnId | null {\n  return value === undefined ? null : TurnId.make(String(value));\n}\n\nfunction sameId(left: string | null | undefined, right: string | null | undefined): boolean {\n  if (left === null || left === undefined || right === null || right === undefined) {\n    return false;\n  }\n  return left === right;\n}\n\nfunction checkpointStatusFromRuntime(status: string | undefined): \"ready\" | \"missing\" | \"error\" {\n  switch (status) {\n    case \"failed\":\n      return \"error\";\n    case \"cancelled\":\n    case \"interrupted\":\n      return \"missing\";\n    case \"completed\":\n    default:\n      return \"ready\";\n  }\n}\n\nconst make = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const randomUUID = crypto.randomUUIDv4;\n  const serverEventId = randomUUID.pipe(Effect.map(EventId.make));\n  const serverCommandId = (tag: string) =>\n    randomUUID.pipe(Effect.map((uuid) => CommandId.make(`server:${tag}:${uuid}`)));\n  const orchestrationEngine = yield* OrchestrationEngineService;\n  const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n  const providerService = yield* ProviderService;\n  const checkpointStore = yield* CheckpointStore.CheckpointStore;\n  const receiptBus = yield* RuntimeReceiptBus;\n  const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;\n  const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;\n\n  const appendRevertFailureActivity = (input: {\n    readonly threadId: ThreadId;\n    readonly turnCount: number;\n    readonly detail: string;\n    readonly createdAt: string;\n  }) =>\n    Effect.all({\n      commandId: serverCommandId(\"checkpoint-revert-failure\"),\n      activityId: serverEventId,\n    }).pipe(\n      Effect.flatMap(({ commandId, activityId }) =>\n        orchestrationEngine.dispatch({\n          type: \"thread.activity.append\",\n          commandId,\n          threadId: input.threadId,\n          activity: {\n            id: activityId,\n            tone: \"error\",\n            kind: \"checkpoint.revert.failed\",\n            summary: \"Checkpoint revert failed\",\n            payload: {\n              turnCount: input.turnCount,\n              detail: input.detail,\n            },\n            turnId: null,\n            createdAt: input.createdAt,\n          },\n          createdAt: input.createdAt,\n        }),\n      ),\n    );\n\n  const appendCaptureFailureActivity = (input: {\n    readonly threadId: ThreadId;\n    readonly turnId: TurnId | null;\n    readonly detail: string;\n    readonly createdAt: string;\n  }) =>\n    Effect.all({\n      commandId: serverCommandId(\"checkpoint-capture-failure\"),\n      activityId: serverEventId,\n    }).pipe(\n      Effect.flatMap(({ commandId, activityId }) =>\n        orchestrationEngine.dispatch({\n          type: \"thread.activity.append\",\n          commandId,\n          threadId: input.threadId,\n          activity: {\n            id: activityId,\n            tone: \"error\",\n            kind: \"checkpoint.capture.failed\",\n            summary: \"Checkpoint capture failed\",\n            payload: {\n              detail: input.detail,\n            },\n            turnId: input.turnId,\n            createdAt: input.createdAt,\n          },\n          createdAt: input.createdAt,\n        }),\n      ),\n    );\n\n  const resolveSessionRuntimeForThread = Effect.fn(\"resolveSessionRuntimeForThread\")(function* (\n    threadId: ThreadId,\n  ): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {\n    const sessions = yield* providerService.listSessions();\n    const session = sessions.find((entry) => entry.threadId === threadId);\n    return session?.cwd\n      ? Option.some({ threadId: session.threadId, cwd: session.cwd })\n      : Option.none();\n  });\n\n  const resolveThreadDetail = Effect.fn(\"resolveThreadDetail\")(function* (threadId: ThreadId) {\n    return yield* projectionSnapshotQuery\n      .getThreadDetailById(threadId)\n      .pipe(Effect.map(Option.getOrUndefined));\n  });\n\n  const resolveThreadProjects = Effect.fn(\"resolveThreadProjects\")(function* (\n    projectId: ProjectId,\n  ) {\n    const project = yield* projectionSnapshotQuery\n      .getProjectShellById(projectId)\n      .pipe(Effect.map(Option.getOrUndefined));\n    return project ? [project] : [];\n  });\n\n  const isGitWorkspace = (cwd: string) => isGitRepository(cwd);\n\n  // Resolves the workspace CWD for checkpoint operations, preferring the\n  // active provider session CWD and falling back to the thread/project config.\n  // Returns undefined when no CWD can be determined or the workspace is not\n  // a git repository.\n  const resolveCheckpointCwd = Effect.fn(\"resolveCheckpointCwd\")(function* (input: {\n    readonly threadId: ThreadId;\n    readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };\n    readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;\n    readonly preferSessionRuntime: boolean;\n  }): Effect.fn.Return<string | undefined> {\n    const fromSession = yield* resolveSessionRuntimeForThread(input.threadId);\n    const fromThread = resolveThreadWorkspaceCwd({\n      thread: input.thread,\n      projects: input.projects,\n    });\n\n    const cwd = input.preferSessionRuntime\n      ? (Option.match(fromSession, {\n          onNone: () => undefined,\n          onSome: (runtime) => runtime.cwd,\n        }) ?? fromThread)\n      : (fromThread ??\n        Option.match(fromSession, {\n          onNone: () => undefined,\n          onSome: (runtime) => runtime.cwd,\n        }));\n\n    if (!cwd) {\n      return undefined;\n    }\n    if (!isGitWorkspace(cwd)) {\n      return undefined;\n    }\n    return cwd;\n  });\n\n  // Shared tail for both capture paths: creates the git checkpoint ref, diffs\n  // it against the previous turn, then dispatches the domain events to update\n  // the orchestration read model.\n  const captureAndDispatchCheckpoint = Effect.fn(\"captureAndDispatchCheckpoint\")(function* (input: {\n    readonly threadId: ThreadId;\n    readonly turnId: TurnId;\n    readonly thread: {\n      readonly messages: ReadonlyArray<{\n        readonly id: MessageId;\n        readonly role: string;\n        readonly turnId: TurnId | null;\n      }>;\n    };\n    readonly cwd: string;\n    readonly turnCount: number;\n    readonly status: \"ready\" | \"missing\" | \"error\";\n    readonly assistantMessageId: MessageId | undefined;\n    readonly createdAt: string;\n  }) {\n    const fromTurnCount = Math.max(0, input.turnCount - 1);\n    const fromCheckpointRef = checkpointRefForThreadTurn(input.threadId, fromTurnCount);\n    const targetCheckpointRef = checkpointRefForThreadTurn(input.threadId, input.turnCount);\n\n    const fromCheckpointExists = yield* checkpointStore.hasCheckpointRef({\n      cwd: input.cwd,\n      checkpointRef: fromCheckpointRef,\n    });\n    if (!fromCheckpointExists) {\n      yield* Effect.logWarning(\"checkpoint capture missing pre-turn baseline\", {\n        threadId: input.threadId,\n        turnId: input.turnId,\n        fromTurnCount,\n      });\n    }\n\n    yield* checkpointStore.captureCheckpoint({\n      cwd: input.cwd,\n      checkpointRef: targetCheckpointRef,\n    });\n\n    // Refresh the workspace entry index so the @-mention file picker\n    // reflects files created or deleted during this turn.\n    yield* workspaceEntries.refresh(input.cwd);\n\n    const files = yield* checkpointStore\n      .diffCheckpoints({\n        cwd: input.cwd,\n        fromCheckpointRef,\n        toCheckpointRef: targetCheckpointRef,\n        fallbackFromToHead: false,\n        ignoreWhitespace: false,\n      })\n      .pipe(\n        Effect.map((diff) =>\n          parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({\n            path: file.path,\n            kind: \"modified\" as const,\n            additions: file.additions,\n            deletions: file.deletions,\n          })),\n        ),\n        Effect.tapError((error) =>\n          appendCaptureFailureActivity({\n            threadId: input.threadId,\n            turnId: input.turnId,\n            detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,\n            createdAt: input.createdAt,\n          }),\n        ),\n        Effect.catch((error) =>\n          Effect.logWarning(\"failed to derive checkpoint file summary\", {\n            threadId: input.threadId,\n            turnId: input.turnId,\n            turnCount: input.turnCount,\n            detail: error.message,\n          }).pipe(Effect.as([])),\n        ),\n      );\n\n    const assistantMessageId =\n      input.assistantMessageId ??\n      input.thread.messages\n        .toReversed()\n        .find((entry) => entry.role === \"assistant\" && entry.turnId === input.turnId)?.id ??\n      MessageId.make(`assistant:${input.turnId}`);\n\n    yield* orchestrationEngine.dispatch({\n      type: \"thread.turn.diff.complete\",\n      commandId: yield* serverCommandId(\"checkpoint-turn-diff-complete\"),\n      threadId: input.threadId,\n      turnId: input.turnId,\n      completedAt: input.createdAt,\n      checkpointRef: targetCheckpointRef,\n      status: input.status,\n      files,\n      assistantMessageId,\n      checkpointTurnCount: input.turnCount,\n      createdAt: input.createdAt,\n    });\n    yield* receiptBus.publish({\n      type: \"checkpoint.diff.finalized\",\n      threadId: input.threadId,\n      turnId: input.turnId,\n      checkpointTurnCount: input.turnCount,\n      checkpointRef: targetCheckpointRef,\n      status: input.status,\n      createdAt: input.createdAt,\n    });\n    yield* receiptBus.publish({\n      type: \"turn.processing.quiesced\",\n      threadId: input.threadId,\n      turnId: input.turnId,\n      checkpointTurnCount: input.turnCount,\n      createdAt: input.createdAt,\n    });\n\n    yield* orchestrationEngine.dispatch({\n      type: \"thread.activity.append\",\n      commandId: yield* serverCommandId(\"checkpoint-captured-activity\"),\n      threadId: input.threadId,\n      activity: {\n        id: EventId.make(yield* randomUUID),\n        tone: \"info\",\n        kind: \"checkpoint.captured\",\n        summary: \"Checkpoint captured\",\n        payload: {\n          turnCount: input.turnCount,\n          status: input.status,\n        },\n        turnId: input.turnId,\n        createdAt: input.createdAt,\n      },\n      createdAt: input.createdAt,\n    });\n  });\n\n  // Captures a real git checkpoint when a turn completes via a runtime event.\n  const captureCheckpointFromTurnCompletion = Effect.fn(\"captureCheckpointFromTurnCompletion\")(\n    function* (event: Extract<ProviderRuntimeEvent, { type: \"turn.completed\" }>) {\n      const turnId = toTurnId(event.turnId);\n      if (!turnId) {\n        return;\n      }\n\n      const thread = yield* resolveThreadDetail(event.threadId);\n      if (!thread) {\n        return;\n      }\n\n      // When a primary turn is active, only that turn may produce completion checkpoints.\n      if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {\n        return;\n      }\n\n      // Only skip if a real (non-placeholder) checkpoint already exists for this turn.\n      // ProviderRuntimeIngestion may insert placeholder entries with status \"missing\"\n      // before this reactor runs; those must not prevent real git capture.\n      if (\n        thread.checkpoints.some(\n          (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== \"missing\",\n        )\n      ) {\n        return;\n      }\n\n      const projects = yield* resolveThreadProjects(thread.projectId);\n      const checkpointCwd = yield* resolveCheckpointCwd({\n        threadId: thread.id,\n        thread,\n        projects,\n        preferSessionRuntime: true,\n      });\n      if (!checkpointCwd) {\n        return;\n      }\n\n      // If a placeholder checkpoint exists for this turn, reuse its turn count\n      // instead of incrementing past it.\n      const existingPlaceholder = thread.checkpoints.find(\n        (checkpoint) => checkpoint.turnId === turnId && checkpoint.status === \"missing\",\n      );\n      const currentTurnCount = thread.checkpoints.reduce(\n        (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),\n        0,\n      );\n      const nextTurnCount = existingPlaceholder\n        ? existingPlaceholder.checkpointTurnCount\n        : currentTurnCount + 1;\n\n      yield* captureAndDispatchCheckpoint({\n        threadId: thread.id,\n        turnId,\n        thread,\n        cwd: checkpointCwd,\n        turnCount: nextTurnCount,\n        status: checkpointStatusFromRuntime(event.payload.state),\n        assistantMessageId: undefined,\n        createdAt: event.createdAt,\n      });\n    },\n  );\n\n  // Captures a real git checkpoint when a placeholder checkpoint (status \"missing\")\n  // is detected via a domain event. This replaces the placeholder with a real\n  // git-ref-based checkpoint.\n  //\n  // ProviderRuntimeIngestion creates placeholder checkpoints on turn.diff.updated\n  // events from the Codex runtime. This handler fires when the corresponding\n  // domain event arrives, allowing the reactor to capture the actual filesystem\n  // state into a git ref and dispatch a replacement checkpoint.\n  const captureCheckpointFromPlaceholder = Effect.fn(\"captureCheckpointFromPlaceholder\")(function* (\n    event: Extract<OrchestrationEvent, { type: \"thread.turn-diff-completed\" }>,\n  ) {\n    const { threadId, turnId, checkpointTurnCount, status } = event.payload;\n\n    // Only replace placeholders; skip events from our own real captures.\n    if (status !== \"missing\") {\n      return;\n    }\n\n    const thread = yield* resolveThreadDetail(threadId);\n    if (!thread) {\n      yield* Effect.logWarning(\"checkpoint capture from placeholder skipped: thread not found\", {\n        threadId,\n      });\n      return;\n    }\n\n    // If a real checkpoint already exists for this turn, skip.\n    if (\n      thread.checkpoints.some(\n        (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== \"missing\",\n      )\n    ) {\n      yield* Effect.logDebug(\n        \"checkpoint capture from placeholder skipped: real checkpoint already exists\",\n        { threadId, turnId },\n      );\n      return;\n    }\n\n    const projects = yield* resolveThreadProjects(thread.projectId);\n    const checkpointCwd = yield* resolveCheckpointCwd({\n      threadId,\n      thread,\n      projects,\n      preferSessionRuntime: true,\n    });\n    if (!checkpointCwd) {\n      return;\n    }\n\n    yield* captureAndDispatchCheckpoint({\n      threadId,\n      turnId,\n      thread,\n      cwd: checkpointCwd,\n      turnCount: checkpointTurnCount,\n      status: \"ready\",\n      assistantMessageId: event.payload.assistantMessageId ?? undefined,\n      createdAt: event.payload.completedAt,\n    });\n  });\n\n  const ensurePreTurnBaselineFromTurnStart = Effect.fn(\"ensurePreTurnBaselineFromTurnStart\")(\n    function* (event: Extract<ProviderRuntimeEvent, { type: \"turn.started\" }>) {\n      const turnId = toTurnId(event.turnId);\n      if (!turnId) {\n        return;\n      }\n\n      const thread = yield* resolveThreadDetail(event.threadId);\n      if (!thread) {\n        return;\n      }\n\n      const projects = yield* resolveThreadProjects(thread.projectId);\n      const checkpointCwd = yield* resolveCheckpointCwd({\n        threadId: thread.id,\n        thread,\n        projects,\n        preferSessionRuntime: false,\n      });\n      if (!checkpointCwd) {\n        return;\n      }\n\n      const currentTurnCount = thread.checkpoints.reduce(\n        (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),\n        0,\n      );\n      const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);\n      const baselineExists = yield* checkpointStore.hasCheckpointRef({\n        cwd: checkpointCwd,\n        checkpointRef: baselineCheckpointRef,\n      });\n      if (baselineExists) {\n        return;\n      }\n\n      yield* checkpointStore.captureCheckpoint({\n        cwd: checkpointCwd,\n        checkpointRef: baselineCheckpointRef,\n      });\n      yield* receiptBus.publish({\n        type: \"checkpoint.baseline.captured\",\n        threadId: thread.id,\n        checkpointTurnCount: currentTurnCount,\n        checkpointRef: baselineCheckpointRef,\n        createdAt: event.createdAt,\n      });\n    },\n  );\n\n  const refreshLocalGitStatusFromTurnCompletion = Effect.fn(\n    \"refreshLocalGitStatusFromTurnCompletion\",\n  )(function* (event: Extract<ProviderRuntimeEvent, { type: \"turn.completed\" }>) {\n    const sessionRuntime = yield* resolveSessionRuntimeForThread(event.threadId);\n    if (Option.isNone(sessionRuntime)) {\n      return;\n    }\n\n    const local = yield* vcsStatusBroadcaster.refreshLocalStatus(sessionRuntime.value.cwd).pipe(\n      Effect.catch((error) =>\n        Effect.logWarning(\"failed to refresh local git status after turn completion\", {\n          threadId: event.threadId,\n          turnId: event.turnId ?? null,\n          cwd: sessionRuntime.value.cwd,\n          detail: error.message,\n        }).pipe(Effect.as(null)),\n      ),\n    );\n    if (local !== null) {\n      yield* followWorktreeBranchDrift({\n        threadId: event.threadId,\n        cwd: sessionRuntime.value.cwd,\n        local,\n      });\n    }\n  });\n\n  // A `git checkout` run inside a thread's dedicated worktree (by an agent or\n  // the user) bypasses T3's commands, so the thread's recorded branch goes\n  // stale. Since #4460 the client only attributes PR state to a thread when\n  // the checked-out branch equals the recorded one, so stale metadata silently\n  // orphans the thread's PR. Follow the drift here: adopt the checked-out\n  // branch as the thread's branch, but only when the worktree belongs to\n  // exactly this thread — for shared cwds the strict matching is the point.\n  const followWorktreeBranchDrift = Effect.fn(\"followWorktreeBranchDrift\")(function* (input: {\n    readonly threadId: ThreadId;\n    readonly cwd: string;\n    readonly local: VcsStatusLocalResult;\n  }) {\n    // Detached HEAD has no branch to adopt; a temporary placeholder checkout\n    // means the first-turn auto-rename is still in flight — don't race it.\n    const checkedOutBranch = input.local.refName;\n    if (checkedOutBranch === null || isTemporaryWorktreeBranch(checkedOutBranch)) {\n      return;\n    }\n\n    yield* Effect.gen(function* () {\n      const thread = yield* projectionSnapshotQuery\n        .getThreadShellById(input.threadId)\n        .pipe(Effect.map(Option.getOrUndefined));\n      if (\n        !thread ||\n        thread.branch === null ||\n        thread.branch === checkedOutBranch ||\n        thread.worktreePath === null ||\n        thread.worktreePath !== input.cwd ||\n        isTemporaryWorktreeBranch(thread.branch)\n      ) {\n        return;\n      }\n\n      const shell = yield* projectionSnapshotQuery.getShellSnapshot();\n      const worktreeIsShared = shell.threads.some(\n        (other) => other.id !== thread.id && other.worktreePath === thread.worktreePath,\n      );\n      if (worktreeIsShared) {\n        return;\n      }\n\n      // expectedBranch makes this a compare-and-swap in the decider: if the\n      // recorded branch moved between our read and the dispatch (rename,\n      // concurrent drift-follow), the stale update is dropped.\n      yield* orchestrationEngine.dispatch({\n        type: \"thread.meta.update\",\n        commandId: yield* serverCommandId(\"worktree-branch-drift\"),\n        threadId: thread.id,\n        branch: checkedOutBranch,\n        expectedBranch: thread.branch,\n      });\n      yield* Effect.logInfo(\"thread branch followed worktree checkout\", {\n        threadId: thread.id,\n        previousBranch: thread.branch,\n        branch: checkedOutBranch,\n      });\n    }).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.failCause(cause);\n        }\n        return Effect.logWarning(\"failed to follow worktree branch drift\", {\n          threadId: input.threadId,\n          cause: Cause.pretty(cause),\n        });\n      }),\n    );\n  });\n\n  const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(\n    \"ensurePreTurnBaselineFromDomainTurnStart\",\n  )(function* (\n    event: Extract<\n      OrchestrationEvent,\n      { type: \"thread.turn-start-requested\" | \"thread.message-sent\" }\n    >,\n  ) {\n    if (event.type === \"thread.message-sent\") {\n      if (\n        event.payload.role !== \"user\" ||\n        event.payload.streaming ||\n        event.payload.turnId !== null\n      ) {\n        return;\n      }\n    }\n\n    const threadId = event.payload.threadId;\n    const thread = yield* resolveThreadDetail(threadId);\n    if (!thread) {\n      return;\n    }\n\n    const projects = yield* resolveThreadProjects(thread.projectId);\n    const checkpointCwd = yield* resolveCheckpointCwd({\n      threadId,\n      thread,\n      projects,\n      preferSessionRuntime: false,\n    });\n    if (!checkpointCwd) {\n      return;\n    }\n\n    const currentTurnCount = thread.checkpoints.reduce(\n      (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),\n      0,\n    );\n    const baselineCheckpointRef = checkpointRefForThreadTurn(threadId, currentTurnCount);\n    const baselineExists = yield* checkpointStore.hasCheckpointRef({\n      cwd: checkpointCwd,\n      checkpointRef: baselineCheckpointRef,\n    });\n    if (baselineExists) {\n      return;\n    }\n\n    yield* checkpointStore.captureCheckpoint({\n      cwd: checkpointCwd,\n      checkpointRef: baselineCheckpointRef,\n    });\n    yield* receiptBus.publish({\n      type: \"checkpoint.baseline.captured\",\n      threadId,\n      checkpointTurnCount: currentTurnCount,\n      checkpointRef: baselineCheckpointRef,\n      createdAt: event.occurredAt,\n    });\n  });\n\n  const handleRevertRequested = Effect.fn(\"handleRevertRequested\")(function* (\n    event: Extract<OrchestrationEvent, { type: \"thread.checkpoint-revert-requested\" }>,\n  ) {\n    const now = DateTime.formatIso(yield* DateTime.now);\n\n    const thread = yield* resolveThreadDetail(event.payload.threadId);\n    if (!thread) {\n      yield* appendRevertFailureActivity({\n        threadId: event.payload.threadId,\n        turnCount: event.payload.turnCount,\n        detail: \"Thread was not found in read model.\",\n        createdAt: now,\n      }).pipe(Effect.catch(() => Effect.void));\n      return;\n    }\n\n    const sessionRuntime = yield* resolveSessionRuntimeForThread(event.payload.threadId);\n    if (Option.isNone(sessionRuntime)) {\n      yield* appendRevertFailureActivity({\n        threadId: event.payload.threadId,\n        turnCount: event.payload.turnCount,\n        detail: \"No active provider session with workspace cwd is bound to this thread.\",\n        createdAt: now,\n      }).pipe(Effect.catch(() => Effect.void));\n      return;\n    }\n    if (!isGitWorkspace(sessionRuntime.value.cwd)) {\n      yield* appendRevertFailureActivity({\n        threadId: event.payload.threadId,\n        turnCount: event.payload.turnCount,\n        detail: \"Checkpoints are unavailable because this project is not a git repository.\",\n        createdAt: now,\n      }).pipe(Effect.catch(() => Effect.void));\n      return;\n    }\n\n    const currentTurnCount = thread.checkpoints.reduce(\n      (maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),\n      0,\n    );\n\n    if (event.payload.turnCount > currentTurnCount) {\n      yield* appendRevertFailureActivity({\n        threadId: event.payload.threadId,\n        turnCount: event.payload.turnCount,\n        detail: `Checkpoint turn count ${event.payload.turnCount} exceeds current turn count ${currentTurnCount}.`,\n        createdAt: now,\n      }).pipe(Effect.catch(() => Effect.void));\n      return;\n    }\n\n    const targetCheckpointRef =\n      event.payload.turnCount === 0\n        ? checkpointRefForThreadTurn(event.payload.threadId, 0)\n        : thread.checkpoints.find(\n            (checkpoint) => checkpoint.checkpointTurnCount === event.payload.turnCount,\n          )?.checkpointRef;\n\n    if (!targetCheckpointRef) {\n      yield* appendRevertFailureActivity({\n        threadId: event.payload.threadId,\n        turnCount: event.payload.turnCount,\n        detail: `Checkpoint ref for turn ${event.payload.turnCount} is unavailable in read model.`,\n        createdAt: now,\n      }).pipe(Effect.catch(() => Effect.void));\n      return;\n    }\n\n    const restored = yield* checkpointStore.restoreCheckpoint({\n      cwd: sessionRuntime.value.cwd,\n      checkpointRef: targetCheckpointRef,\n      fallbackToHead: event.payload.turnCount === 0,\n    });\n    if (!restored) {\n      yield* appendRevertFailureActivity({\n        threadId: event.payload.threadId,\n        turnCount: event.payload.turnCount,\n        detail: `Filesystem checkpoint is unavailable for turn ${event.payload.turnCount}.`,\n        createdAt: now,\n      }).pipe(Effect.catch(() => Effect.void));\n      return;\n    }\n\n    // Refresh the workspace entry index so the @-mention file picker\n    // reflects the reverted filesystem state.\n    yield* workspaceEntries.refresh(sessionRuntime.value.cwd);\n\n    const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);\n    if (rolledBackTurns > 0) {\n      yield* providerService.rollbackConversation({\n        threadId: sessionRuntime.value.threadId,\n        numTurns: rolledBackTurns,\n      });\n    }\n\n    const staleCheckpointRefs: Array<CheckpointRef> = [];\n    for (const checkpoint of thread.checkpoints) {\n      if (checkpoint.checkpointTurnCount > event.payload.turnCount) {\n        staleCheckpointRefs.push(checkpoint.checkpointRef);\n      }\n    }\n\n    if (staleCheckpointRefs.length > 0) {\n      yield* checkpointStore.deleteCheckpointRefs({\n        cwd: sessionRuntime.value.cwd,\n        checkpointRefs: staleCheckpointRefs,\n      });\n    }\n\n    yield* orchestrationEngine\n      .dispatch({\n        type: \"thread.revert.complete\",\n        commandId: yield* serverCommandId(\"checkpoint-revert-complete\"),\n        threadId: event.payload.threadId,\n        turnCount: event.payload.turnCount,\n        createdAt: now,\n      })\n      .pipe(\n        Effect.catch((error) =>\n          appendRevertFailureActivity({\n            threadId: event.payload.threadId,\n            turnCount: event.payload.turnCount,\n            detail: error.message,\n            createdAt: now,\n          }),\n        ),\n        Effect.asVoid,\n      );\n  });\n\n  const processDomainEvent = Effect.fn(\"processDomainEvent\")(function* (event: OrchestrationEvent) {\n    if (event.type === \"thread.turn-start-requested\" || event.type === \"thread.message-sent\") {\n      yield* ensurePreTurnBaselineFromDomainTurnStart(event);\n      return;\n    }\n\n    if (event.type === \"thread.checkpoint-revert-requested\") {\n      yield* handleRevertRequested(event).pipe(\n        Effect.catch((error) =>\n          Effect.flatMap(nowIso, (createdAt) =>\n            appendRevertFailureActivity({\n              threadId: event.payload.threadId,\n              turnCount: event.payload.turnCount,\n              detail: error.message,\n              createdAt,\n            }),\n          ),\n        ),\n      );\n      return;\n    }\n\n    // When ProviderRuntimeIngestion creates a placeholder checkpoint (status \"missing\")\n    // from a turn.diff.updated runtime event, capture the real git checkpoint to\n    // replace it. The providerService.streamEvents PubSub does not reliably deliver\n    // turn.completed runtime events to this reactor (shared subscription), so\n    // reacting to the domain event is the reliable path.\n    if (event.type === \"thread.turn-diff-completed\") {\n      yield* captureCheckpointFromPlaceholder(event).pipe(\n        Effect.catch((error) =>\n          Effect.flatMap(nowIso, (createdAt) =>\n            appendCaptureFailureActivity({\n              threadId: event.payload.threadId,\n              turnId: event.payload.turnId,\n              detail: error.message,\n              createdAt,\n            }).pipe(Effect.catch(() => Effect.void)),\n          ),\n        ),\n      );\n    }\n  });\n\n  const processRuntimeEvent = Effect.fn(\"processRuntimeEvent\")(function* (\n    event: ProviderRuntimeEvent,\n  ) {\n    if (event.type === \"turn.started\") {\n      yield* ensurePreTurnBaselineFromTurnStart(event);\n      return;\n    }\n\n    if (event.type === \"turn.completed\") {\n      const turnId = toTurnId(event.turnId);\n      yield* refreshLocalGitStatusFromTurnCompletion(event);\n      yield* captureCheckpointFromTurnCompletion(event).pipe(\n        Effect.catch((error) =>\n          Effect.flatMap(nowIso, (createdAt) =>\n            appendCaptureFailureActivity({\n              threadId: event.threadId,\n              turnId,\n              detail: error.message,\n              createdAt,\n            }).pipe(Effect.catch(() => Effect.void)),\n          ),\n        ),\n      );\n      return;\n    }\n  });\n\n  const processInput = (\n    input: ReactorInput,\n  ): Effect.Effect<\n    void,\n    CheckpointStoreError | OrchestrationDispatchError | PlatformError.PlatformError,\n    never\n  > =>\n    input.source === \"domain\" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);\n\n  const processInputSafely = (input: ReactorInput) =>\n    processInput(input).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.failCause(cause);\n        }\n        return Effect.logWarning(\"checkpoint reactor failed to process input\", {\n          source: input.source,\n          eventType: input.event.type,\n          cause: Cause.pretty(cause),\n        });\n      }),\n    );\n\n  const worker = yield* makeDrainableWorker(processInputSafely);\n\n  const start: CheckpointReactorShape[\"start\"] = Effect.fn(\"start\")(function* () {\n    yield* forkParked(\n      Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {\n        if (\n          event.type !== \"thread.turn-start-requested\" &&\n          event.type !== \"thread.message-sent\" &&\n          event.type !== \"thread.checkpoint-revert-requested\" &&\n          event.type !== \"thread.turn-diff-completed\"\n        ) {\n          return Effect.void;\n        }\n        return worker.enqueue({ source: \"domain\", event });\n      }),\n    );\n\n    yield* forkParked(\n      Stream.runForEach(providerService.streamEvents, (event) => {\n        if (event.type !== \"turn.started\" && event.type !== \"turn.completed\") {\n          return Effect.void;\n        }\n        return worker.enqueue({ source: \"runtime\", event });\n      }),\n    );\n  });\n\n  return {\n    start,\n    drain: worker.drain,\n  } satisfies CheckpointReactorShape;\n});\n\nexport const CheckpointReactorLive = Layer.effect(CheckpointReactor, make);\n","import type { OrchestrationEvent } from \"@t3tools/contracts\";\nimport { makeDrainableWorker } from \"@t3tools/shared/DrainableWorker\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Stream from \"effect/Stream\";\n\nimport { ProviderService } from \"../../provider/Services/ProviderService.ts\";\nimport * as TerminalManager from \"../../terminal/Manager.ts\";\nimport { OrchestrationEngineService } from \"../Services/OrchestrationEngine.ts\";\nimport {\n  ThreadDeletionReactor,\n  type ThreadDeletionReactorShape,\n} from \"../Services/ThreadDeletionReactor.ts\";\nimport { forkParked } from \"../../serverActivation.ts\";\n\ntype ThreadDeletedEvent = Extract<OrchestrationEvent, { type: \"thread.deleted\" }>;\n\nexport const logCleanupCauseUnlessInterrupted = <R, E>({\n  effect,\n  message,\n  threadId,\n}: {\n  readonly effect: Effect.Effect<void, E, R>;\n  readonly message: string;\n  readonly threadId: ThreadDeletedEvent[\"payload\"][\"threadId\"];\n}): Effect.Effect<void, E, R> =>\n  effect.pipe(\n    Effect.catchCause((cause) => {\n      if (Cause.hasInterruptsOnly(cause)) {\n        return Effect.failCause(cause);\n      }\n      return Effect.logDebug(message, {\n        threadId,\n        cause: Cause.pretty(cause),\n      });\n    }),\n  );\n\nconst make = Effect.gen(function* () {\n  const orchestrationEngine = yield* OrchestrationEngineService;\n  const providerService = yield* ProviderService;\n  const terminalManager = yield* TerminalManager.TerminalManager;\n\n  const stopProviderSession = (threadId: ThreadDeletedEvent[\"payload\"][\"threadId\"]) =>\n    logCleanupCauseUnlessInterrupted({\n      effect: providerService.stopSession({ threadId }),\n      message: \"thread deletion cleanup skipped provider session stop\",\n      threadId,\n    });\n\n  const closeThreadTerminals = (threadId: ThreadDeletedEvent[\"payload\"][\"threadId\"]) =>\n    logCleanupCauseUnlessInterrupted({\n      effect: terminalManager.close({ threadId, deleteHistory: true }),\n      message: \"thread deletion cleanup skipped terminal close\",\n      threadId,\n    });\n\n  const processThreadDeleted = Effect.fn(\"processThreadDeleted\")(function* (\n    event: ThreadDeletedEvent,\n  ) {\n    const { threadId } = event.payload;\n    yield* stopProviderSession(threadId);\n    yield* closeThreadTerminals(threadId);\n  });\n\n  const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>\n    processThreadDeleted(event).pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.failCause(cause);\n        }\n        return Effect.logWarning(\"thread deletion reactor failed to process event\", {\n          eventType: event.type,\n          threadId: event.payload.threadId,\n          cause: Cause.pretty(cause),\n        });\n      }),\n    );\n\n  const worker = yield* makeDrainableWorker(processThreadDeletedSafely);\n\n  const start: ThreadDeletionReactorShape[\"start\"] = Effect.fn(\"start\")(function* () {\n    yield* forkParked(\n      Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {\n        if (event.type !== \"thread.deleted\") {\n          return Effect.void;\n        }\n        return worker.enqueue(event);\n      }),\n    );\n  });\n\n  return {\n    start,\n    drain: worker.drain,\n  } satisfies ThreadDeletionReactorShape;\n});\n\nexport const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make);\n","import * as Schema from \"effect/Schema\";\n\nconst PAIRING_TOKEN_PARAM = \"token\";\nconst HOSTED_PAIRING_HOST_PARAM = \"host\";\nconst HOSTED_PAIRING_LABEL_PARAM = \"label\";\nconst SUPPORTED_REMOTE_BACKEND_PROTOCOLS = new Set([\"http:\", \"https:\", \"ws:\", \"wss:\"]);\n\nexport const readHashParams = (url: URL): URLSearchParams =>\n  new URLSearchParams(url.hash.startsWith(\"#\") ? url.hash.slice(1) : url.hash);\n\nexport class RemoteBackendUrlMissingError extends Schema.TaggedErrorClass<RemoteBackendUrlMissingError>()(\n  \"RemoteBackendUrlMissingError\",\n  {},\n) {\n  override get message(): string {\n    return \"Enter a backend URL.\";\n  }\n}\n\nexport class RemotePairingUrlInvalidError extends Schema.TaggedErrorClass<RemotePairingUrlInvalidError>()(\n  \"RemotePairingUrlInvalidError\",\n  {\n    cause: Schema.optional(Schema.Defect()),\n    protocol: Schema.optional(Schema.String),\n  },\n) {\n  override get message(): string {\n    return \"Pairing URL is invalid.\";\n  }\n}\n\nexport class RemoteBackendUrlInvalidError extends Schema.TaggedErrorClass<RemoteBackendUrlInvalidError>()(\n  \"RemoteBackendUrlInvalidError\",\n  {\n    source: Schema.Literals([\"direct-host\", \"hosted-pairing-host\"]),\n    cause: Schema.optional(Schema.Defect()),\n    protocol: Schema.optional(Schema.String),\n  },\n) {\n  override get message(): string {\n    return \"Backend URL is invalid.\";\n  }\n}\n\nexport class RemotePairingTokenMissingError extends Schema.TaggedErrorClass<RemotePairingTokenMissingError>()(\n  \"RemotePairingTokenMissingError\",\n  { host: Schema.String },\n) {\n  override get message(): string {\n    return \"Pairing URL is missing its token.\";\n  }\n}\n\nexport class RemotePairingCodeMissingError extends Schema.TaggedErrorClass<RemotePairingCodeMissingError>()(\n  \"RemotePairingCodeMissingError\",\n  { host: Schema.String },\n) {\n  override get message(): string {\n    return \"Enter a pairing code.\";\n  }\n}\n\nexport const RemotePairingTargetError = Schema.Union([\n  RemoteBackendUrlMissingError,\n  RemotePairingUrlInvalidError,\n  RemoteBackendUrlInvalidError,\n  RemotePairingTokenMissingError,\n  RemotePairingCodeMissingError,\n]);\nexport type RemotePairingTargetError = typeof RemotePairingTargetError.Type;\n\nconst hasSupportedRemoteBackendProtocol = (url: URL): boolean =>\n  SUPPORTED_REMOTE_BACKEND_PROTOCOLS.has(url.protocol);\n\nconst normalizeRemoteBaseUrl = (\n  rawValue: string,\n  source: RemoteBackendUrlInvalidError[\"source\"],\n): URL => {\n  const trimmed = rawValue.trim();\n  if (!trimmed) {\n    throw new RemoteBackendUrlMissingError();\n  }\n\n  const withoutLeadingSlashes = trimmed.replace(/^\\/+/, \"\");\n  const normalizedInput = /^[a-zA-Z][a-zA-Z\\d+-]*:\\/\\//.test(withoutLeadingSlashes)\n    ? withoutLeadingSlashes\n    : `https://${withoutLeadingSlashes}`;\n  let url: URL;\n  try {\n    url = new URL(normalizedInput);\n  } catch (cause) {\n    throw new RemoteBackendUrlInvalidError({ source, cause });\n  }\n  if (!hasSupportedRemoteBackendProtocol(url)) {\n    throw new RemoteBackendUrlInvalidError({\n      source,\n      protocol: url.protocol,\n    });\n  }\n  url.pathname = \"/\";\n  url.search = \"\";\n  url.hash = \"\";\n  return url;\n};\n\nconst toHttpBaseUrl = (url: URL): string => {\n  const next = new URL(url.toString());\n  if (next.protocol === \"ws:\") {\n    next.protocol = \"http:\";\n  } else if (next.protocol === \"wss:\") {\n    next.protocol = \"https:\";\n  }\n  next.pathname = \"/\";\n  next.search = \"\";\n  next.hash = \"\";\n  return next.toString();\n};\n\nconst toWsBaseUrl = (url: URL): string => {\n  const next = new URL(url.toString());\n  if (next.protocol === \"http:\") {\n    next.protocol = \"ws:\";\n  } else if (next.protocol === \"https:\") {\n    next.protocol = \"wss:\";\n  }\n  next.pathname = \"/\";\n  next.search = \"\";\n  next.hash = \"\";\n  return next.toString();\n};\n\nexport interface ResolvedRemotePairingTarget {\n  readonly credential: string;\n  readonly httpBaseUrl: string;\n  readonly wsBaseUrl: string;\n}\n\nexport interface HostedPairingRequest {\n  readonly host: string;\n  readonly token: string;\n  readonly label: string;\n}\n\nexport const getPairingTokenFromUrl = (url: URL): string | null => {\n  const hashToken = readHashParams(url).get(PAIRING_TOKEN_PARAM)?.trim() ?? \"\";\n  if (hashToken.length > 0) {\n    return hashToken;\n  }\n\n  const searchToken = url.searchParams.get(PAIRING_TOKEN_PARAM)?.trim() ?? \"\";\n  return searchToken.length > 0 ? searchToken : null;\n};\n\nexport const stripPairingTokenFromUrl = (url: URL): URL => {\n  const next = new URL(url.toString());\n  const hashParams = readHashParams(next);\n  if (hashParams.has(PAIRING_TOKEN_PARAM)) {\n    hashParams.delete(PAIRING_TOKEN_PARAM);\n    next.hash = hashParams.toString();\n  }\n  next.searchParams.delete(PAIRING_TOKEN_PARAM);\n  return next;\n};\n\nexport const setPairingTokenOnUrl = (url: URL, credential: string): URL => {\n  const next = new URL(url.toString());\n  next.searchParams.delete(PAIRING_TOKEN_PARAM);\n  next.hash = new URLSearchParams([[PAIRING_TOKEN_PARAM, credential]]).toString();\n  return next;\n};\n\nexport const readHostedPairingRequest = (url: URL): HostedPairingRequest | null => {\n  const host = url.searchParams.get(HOSTED_PAIRING_HOST_PARAM)?.trim() ?? \"\";\n  const token = getPairingTokenFromUrl(url)?.trim() ?? \"\";\n  const label = url.searchParams.get(HOSTED_PAIRING_LABEL_PARAM)?.trim() ?? \"\";\n\n  if (!host || !token) {\n    return null;\n  }\n\n  return {\n    host,\n    token,\n    label,\n  };\n};\n\nexport const resolveRemotePairingTarget = (input: {\n  readonly pairingUrl?: string;\n  readonly host?: string;\n  readonly pairingCode?: string;\n}): ResolvedRemotePairingTarget => {\n  const pairingUrl = input.pairingUrl?.trim() ?? \"\";\n  if (pairingUrl.length > 0) {\n    let url: URL;\n    try {\n      url = new URL(pairingUrl);\n    } catch (cause) {\n      throw new RemotePairingUrlInvalidError({ cause });\n    }\n    if (!hasSupportedRemoteBackendProtocol(url)) {\n      throw new RemotePairingUrlInvalidError({\n        protocol: url.protocol,\n      });\n    }\n    const hostedPairingRequest = readHostedPairingRequest(url);\n    if (hostedPairingRequest) {\n      const hostedBackendUrl = normalizeRemoteBaseUrl(\n        hostedPairingRequest.host,\n        \"hosted-pairing-host\",\n      );\n      return {\n        credential: hostedPairingRequest.token,\n        httpBaseUrl: toHttpBaseUrl(hostedBackendUrl),\n        wsBaseUrl: toWsBaseUrl(hostedBackendUrl),\n      };\n    }\n\n    const credential = getPairingTokenFromUrl(url) ?? \"\";\n    if (!credential) {\n      throw new RemotePairingTokenMissingError({ host: url.host });\n    }\n    return {\n      credential,\n      httpBaseUrl: toHttpBaseUrl(url),\n      wsBaseUrl: toWsBaseUrl(url),\n    };\n  }\n\n  const host = input.host?.trim() ?? \"\";\n  const pairingCode = input.pairingCode?.trim() ?? \"\";\n  if (!host) {\n    throw new RemoteBackendUrlMissingError();\n  }\n  const normalizedHost = normalizeRemoteBaseUrl(host, \"direct-host\");\n  if (!pairingCode) {\n    throw new RemotePairingCodeMissingError({ host: normalizedHost.host });\n  }\n\n  return {\n    credential: pairingCode,\n    httpBaseUrl: toHttpBaseUrl(normalizedHost),\n    wsBaseUrl: toWsBaseUrl(normalizedHost),\n  };\n};\n","import { readHashParams } from \"./remote.ts\";\n\nconst CONNECT_AUTH_STATE_PARAM = \"state\";\nconst CONNECT_AUTH_CHALLENGE_PARAM = \"challenge\";\nconst CONNECT_AUTH_CODE_SEPARATOR = \".\";\n\nconst CONNECT_AUTHORIZE_PATH = \"/connect\";\nconst CONNECT_CALLBACK_PATH = \"/connect/callback\";\n\n/**\n * The CLI prints URLs against this origin and the web bundle uses it to\n * decide whether it is the hosted deployment — the two must agree, so the\n * default lives here.\n */\nexport const DEFAULT_HOSTED_APP_URL = \"https://app.t3.codes\";\n\n/**\n * Requested at authorize time by the hosted page and honored by the CLI's\n * token exchange; keep both sides on this single definition.\n */\nexport const CONNECT_OAUTH_SCOPES = [\"openid\", \"profile\", \"email\"] as const;\n\nexport interface ConnectAuthorizeRequest {\n  readonly state: string;\n  readonly challenge: string;\n}\n\n/**\n * The URL a headless CLI prints for the user to open on a machine with a\n * browser. `state` and `code_challenge` ride the fragment so they never reach\n * the hosted app's server or CDN logs; neither is a secret.\n */\nexport function buildConnectAuthorizeRequestUrl(input: {\n  readonly hostedAppUrl: string;\n  readonly state: string;\n  readonly challenge: string;\n}): string {\n  const url = new URL(CONNECT_AUTHORIZE_PATH, input.hostedAppUrl);\n  url.hash = new URLSearchParams([\n    [CONNECT_AUTH_STATE_PARAM, input.state],\n    [CONNECT_AUTH_CHALLENGE_PARAM, input.challenge],\n  ]).toString();\n  return url.toString();\n}\n\nexport function readConnectAuthorizeRequest(url: URL): ConnectAuthorizeRequest | null {\n  const params = readHashParams(url);\n  const state = params.get(CONNECT_AUTH_STATE_PARAM)?.trim() ?? \"\";\n  const challenge = params.get(CONNECT_AUTH_CHALLENGE_PARAM)?.trim() ?? \"\";\n  if (!state || !challenge) {\n    return null;\n  }\n  return { state, challenge };\n}\n\nexport function connectCallbackUrl(hostedAppUrl: string): string {\n  return new URL(CONNECT_CALLBACK_PATH, hostedAppUrl).toString();\n}\n\nexport function buildConnectClerkAuthorizeUrl(input: {\n  readonly authorizationEndpoint: string;\n  readonly clientId: string;\n  readonly redirectUri: string;\n  readonly scopes: ReadonlyArray<string>;\n  readonly state: string;\n  readonly challenge: string;\n}): string {\n  const url = new URL(input.authorizationEndpoint);\n  url.searchParams.set(\"client_id\", input.clientId);\n  url.searchParams.set(\"redirect_uri\", input.redirectUri);\n  url.searchParams.set(\"response_type\", \"code\");\n  url.searchParams.set(\"scope\", input.scopes.join(\" \"));\n  url.searchParams.set(\"state\", input.state);\n  url.searchParams.set(\"code_challenge\", input.challenge);\n  url.searchParams.set(\"code_challenge_method\", \"S256\");\n  return url.toString();\n}\n\nexport interface ConnectAuthCode {\n  readonly code: string;\n  readonly state: string;\n}\n\n/**\n * The single blob the hosted callback page displays and the CLI accepts.\n * Bundling `state` with the authorization code lets the CLI keep the loopback\n * flow's CSRF check without any backend: it verifies the returned state\n * matches the one it generated. Clerk authorization codes and the CLI's\n * base64url states never contain \".\".\n */\nexport function encodeConnectAuthCode(input: ConnectAuthCode): string {\n  return `${input.code}${CONNECT_AUTH_CODE_SEPARATOR}${input.state}`;\n}\n\n/**\n * Validates an out-of-band authorization code against the state of the request this process\n * generated. Returns the parsed code or a user-facing error message; both\n * the prompt's live validation and the authoritative post-prompt check go\n * through here so they cannot drift.\n */\nexport function checkConnectAuthCode(\n  blob: string,\n  expectedState: string,\n): ConnectAuthCode | string {\n  const parsed = parseConnectAuthCode(blob);\n  if (parsed === null) {\n    return \"That does not look like a Synaptic Connect code. Copy the full code.\";\n  }\n  if (parsed.state !== expectedState) {\n    return \"That code belongs to a different connect request. Open the URL above and try again.\";\n  }\n  return parsed;\n}\n\nexport function parseConnectAuthCode(blob: string): ConnectAuthCode | null {\n  const trimmed = blob.trim();\n  const separatorIndex = trimmed.lastIndexOf(CONNECT_AUTH_CODE_SEPARATOR);\n  if (separatorIndex <= 0 || separatorIndex === trimmed.length - 1) {\n    return null;\n  }\n  const code = trimmed.slice(0, separatorIndex);\n  const state = trimmed.slice(separatorIndex + 1);\n  return { code, state };\n}\n","import * as Schema from \"effect/Schema\";\n\nconst ClerkPublishableKeyPrefix = Schema.Literals([\"pk_test\", \"pk_live\", \"unknown\"]);\n\nexport class ClerkPublishableKeyDecodeError extends Schema.TaggedErrorClass<ClerkPublishableKeyDecodeError>()(\n  \"ClerkPublishableKeyDecodeError\",\n  {\n    keyPrefix: ClerkPublishableKeyPrefix,\n    cause: Schema.Defect(),\n  },\n) {\n  override get message(): string {\n    return `Failed to decode Clerk publishable key (${this.keyPrefix}).`;\n  }\n}\n\nexport class ClerkPublishableKeyFrontendApiError extends Schema.TaggedErrorClass<ClerkPublishableKeyFrontendApiError>()(\n  \"ClerkPublishableKeyFrontendApiError\",\n  {\n    keyPrefix: ClerkPublishableKeyPrefix,\n    frontendApi: Schema.String,\n    reason: Schema.Literals([\"empty\", \"contains-path\", \"invalid-url\"]),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return `Invalid Clerk frontend API decoded from publishable key (${this.keyPrefix}; ${this.reason}).`;\n  }\n}\n\nfunction parseClerkFrontendApi(publishableKey: string): {\n  readonly hostname: string;\n  readonly url: string;\n} {\n  const keyPrefix = publishableKey.startsWith(\"pk_test_\")\n    ? \"pk_test\"\n    : publishableKey.startsWith(\"pk_live_\")\n      ? \"pk_live\"\n      : \"unknown\";\n  const encodedFrontendApi = publishableKey.split(\"_\").slice(2).join(\"_\");\n  let frontendApi: string;\n  try {\n    frontendApi = globalThis.atob(encodedFrontendApi).replace(/\\$$/u, \"\");\n  } catch (cause) {\n    throw new ClerkPublishableKeyDecodeError({ keyPrefix, cause });\n  }\n\n  if (frontendApi.length === 0) {\n    throw new ClerkPublishableKeyFrontendApiError({\n      keyPrefix,\n      frontendApi,\n      reason: \"empty\",\n    });\n  }\n  if (frontendApi.includes(\"/\")) {\n    throw new ClerkPublishableKeyFrontendApiError({\n      keyPrefix,\n      frontendApi,\n      reason: \"contains-path\",\n    });\n  }\n\n  const url = `https://${frontendApi}`;\n  try {\n    return { hostname: new URL(url).hostname, url };\n  } catch (cause) {\n    throw new ClerkPublishableKeyFrontendApiError({\n      keyPrefix,\n      frontendApi,\n      reason: \"invalid-url\",\n      cause,\n    });\n  }\n}\n\nexport function clerkFrontendApiUrlFromPublishableKey(publishableKey: string): string {\n  return parseClerkFrontendApi(publishableKey).url;\n}\n\nexport function clerkFrontendApiHostnameFromPublishableKey(publishableKey: string): string {\n  return parseClerkFrontendApi(publishableKey).hostname;\n}\n\nexport function isAllowedClerkFrontendApiHostname(\n  hostname: string,\n  configuredHostname: string | null,\n): boolean {\n  return (\n    hostname.endsWith(\".clerk.accounts.dev\") ||\n    hostname.endsWith(\".clerk.accounts.com\") ||\n    hostname === configuredHostname\n  );\n}\n\nexport function relayClerkTokenOptions(template: string) {\n  return {\n    template,\n    skipCache: true,\n  } as const;\n}\n","export function normalizeSecureRelayUrl(value: string): string | null {\n  try {\n    const url = new URL(value.trim());\n    if (\n      url.protocol !== \"https:\" ||\n      url.username.length > 0 ||\n      url.password.length > 0 ||\n      url.search.length > 0 ||\n      url.hash.length > 0 ||\n      !/^\\/+$/u.test(url.pathname)\n    ) {\n      return null;\n    }\n    return url.origin;\n  } catch {\n    return null;\n  }\n}\n\nexport function isSecureRelayUrl(value: string): boolean {\n  return normalizeSecureRelayUrl(value) !== null;\n}\n","import { CONNECT_OAUTH_SCOPES, DEFAULT_HOSTED_APP_URL } from \"@t3tools/shared/connectAuth\";\nimport { clerkFrontendApiUrlFromPublishableKey } from \"@t3tools/shared/relayAuth\";\nimport { normalizeSecureRelayUrl } from \"@t3tools/shared/relayUrl\";\nimport * as Config from \"effect/Config\";\nimport * as ConfigProvider from \"effect/ConfigProvider\";\nimport * as Effect from \"effect/Effect\";\nimport * as Schema from \"effect/Schema\";\nimport * as SchemaIssue from \"effect/SchemaIssue\";\n\ndeclare const __SYNAPTIC_BUILD_RELAY_URL__: string | undefined;\ndeclare const __SYNAPTIC_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;\ndeclare const __SYNAPTIC_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__: string | undefined;\ndeclare const __SYNAPTIC_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;\ndeclare const __SYNAPTIC_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;\ndeclare const __SYNAPTIC_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;\n\nconst CLOUD_CLI_OAUTH_REDIRECT_URI = \"http://127.0.0.1:34338/callback\";\nconst CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;\n\nfunction validateRelayUrl(value: string) {\n  const relayUrl = normalizeSecureRelayUrl(value);\n  return relayUrl === null\n    ? Effect.fail(\n        new Config.ConfigError(\n          new Schema.SchemaError(\n            new SchemaIssue.InvalidValue({\n              message: \"Relay URL must be a secure absolute HTTPS origin.\",\n            }),\n          ),\n        ),\n      )\n    : Effect.succeed(relayUrl);\n}\n\nfunction readBuildTimeValue(value: string | undefined): string {\n  return typeof value === \"undefined\" ? \"\" : value.trim();\n}\n\nfunction normalizeSecureUrl(value: string): string | null {\n  try {\n    const url = new URL(value);\n    return url.protocol === \"https:\" ? url.toString() : null;\n  } catch {\n    return null;\n  }\n}\n\nexport const buildTimeRelayUrl =\n  typeof __SYNAPTIC_BUILD_RELAY_URL__ === \"undefined\"\n    ? \"\"\n    : (normalizeSecureRelayUrl(__SYNAPTIC_BUILD_RELAY_URL__) ?? \"\");\nexport const buildTimeClerkPublishableKey = readBuildTimeValue(\n  typeof __SYNAPTIC_BUILD_CLERK_PUBLISHABLE_KEY__ === \"undefined\"\n    ? undefined\n    : __SYNAPTIC_BUILD_CLERK_PUBLISHABLE_KEY__,\n);\nexport const buildTimeClerkCliOAuthClientId = readBuildTimeValue(\n  typeof __SYNAPTIC_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__ === \"undefined\"\n    ? undefined\n    : __SYNAPTIC_BUILD_CLERK_CLI_OAUTH_CLIENT_ID__,\n);\nexport const buildTimeRelayClientTracing = {\n  tracesUrl: readBuildTimeValue(\n    typeof __SYNAPTIC_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__ === \"undefined\"\n      ? undefined\n      : __SYNAPTIC_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__,\n  ),\n  tracesDataset: readBuildTimeValue(\n    typeof __SYNAPTIC_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__ === \"undefined\"\n      ? undefined\n      : __SYNAPTIC_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__,\n  ),\n  tracesToken: readBuildTimeValue(\n    typeof __SYNAPTIC_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__ === \"undefined\"\n      ? undefined\n      : __SYNAPTIC_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__,\n  ),\n} as const;\n\nexport function resolveRelayClientTracingConfig(\n  env: Readonly<Record<string, string | undefined>> = process.env,\n  fallback = buildTimeRelayClientTracing,\n) {\n  const tracesUrl = env.SYNAPTIC_RELAY_CLIENT_OTLP_TRACES_URL?.trim() || fallback.tracesUrl;\n  const tracesDataset =\n    env.SYNAPTIC_RELAY_CLIENT_OTLP_TRACES_DATASET?.trim() || fallback.tracesDataset;\n  const tracesToken = env.SYNAPTIC_RELAY_CLIENT_OTLP_TRACES_TOKEN?.trim() || fallback.tracesToken;\n  const normalizedTracesUrl = normalizeSecureUrl(tracesUrl);\n  return normalizedTracesUrl && tracesDataset && tracesToken\n    ? { tracesUrl: normalizedTracesUrl, tracesDataset, tracesToken }\n    : null;\n}\n\nexport function makeRelayUrlConfig(fallback = buildTimeRelayUrl) {\n  const runtimeConfig = Config.nonEmptyString(\"SYNAPTIC_RELAY_URL\");\n  return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(\n    Config.mapOrFail(validateRelayUrl),\n  );\n}\n\nexport const relayUrlConfig = makeRelayUrlConfig();\n\n/**\n * Hosted app origin used for out-of-band OAuth on headless\n * machines. Overridable so staging/nightly builds can point their CLIs at a\n * matching hosted deployment.\n */\nexport const hostedAppUrlConfig = makePublicValueConfig(\n  \"SYNAPTIC_HOSTED_APP_URL\",\n  DEFAULT_HOSTED_APP_URL,\n).pipe(Config.mapOrFail(validateHostedAppUrl));\n\nfunction validateHostedAppUrl(value: string) {\n  try {\n    const url = new URL(value);\n    const isLoopbackHttp =\n      url.protocol === \"http:\" &&\n      (url.hostname === \"localhost\" || url.hostname === \"127.0.0.1\" || url.hostname === \"[::1]\");\n    if (\n      (url.protocol !== \"https:\" && !isLoopbackHttp) ||\n      url.pathname !== \"/\" ||\n      url.search !== \"\" ||\n      url.hash !== \"\"\n    ) {\n      throw new Error(\"invalid hosted app origin\");\n    }\n    return Effect.succeed(url.origin);\n  } catch {\n    return Effect.fail(\n      new Config.ConfigError(\n        new Schema.SchemaError(\n          new SchemaIssue.InvalidValue({\n            message: \"Hosted app URL must be an absolute HTTPS origin (or HTTP loopback origin).\",\n          }),\n        ),\n      ),\n    );\n  }\n}\n\nfunction makePublicValueConfig(name: string, fallback: string) {\n  const runtimeConfig = Config.nonEmptyString(name);\n  return (fallback ? runtimeConfig.pipe(Config.withDefault(fallback)) : runtimeConfig).pipe(\n    Config.map((value) => value.trim()),\n  );\n}\n\nexport interface CloudCliOAuthConfig {\n  readonly authorizationEndpoint: string;\n  readonly tokenEndpoint: string;\n  readonly clientId: string;\n  readonly redirectUri: string;\n  readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;\n}\n\nexport function makeCloudCliOAuthConfig({\n  clerkPublishableKeyFallback = buildTimeClerkPublishableKey,\n  clerkCliOAuthClientIdFallback = buildTimeClerkCliOAuthClientId,\n}: {\n  readonly clerkPublishableKeyFallback?: string;\n  readonly clerkCliOAuthClientIdFallback?: string;\n} = {}) {\n  return Config.all({\n    clerkPublishableKey: makePublicValueConfig(\n      \"SYNAPTIC_CLERK_PUBLISHABLE_KEY\",\n      clerkPublishableKeyFallback,\n    ),\n    clientId: makePublicValueConfig(\n      \"SYNAPTIC_CLERK_CLI_OAUTH_CLIENT_ID\",\n      clerkCliOAuthClientIdFallback,\n    ),\n  }).pipe(\n    Config.mapOrFail(({ clerkPublishableKey, clientId }) =>\n      Effect.try({\n        try: () => clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey),\n        catch: (cause) =>\n          new Config.ConfigError(\n            new ConfigProvider.SourceError({\n              message: \"Failed to derive Clerk Frontend API URL from the publishable key.\",\n              cause,\n            }),\n          ),\n      }).pipe(\n        Effect.map(\n          (clerkFrontendApiUrl) =>\n            ({\n              authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,\n              tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,\n              clientId,\n              redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,\n              scopes: CLOUD_CLI_OAUTH_SCOPES,\n            }) satisfies CloudCliOAuthConfig,\n        ),\n      ),\n    ),\n  );\n}\n\nexport const cloudCliOAuthConfig = makeCloudCliOAuthConfig();\n\nexport const hasCloudPublicConfig = Boolean(\n  (normalizeSecureRelayUrl(process.env.SYNAPTIC_RELAY_URL ?? \"\") ?? buildTimeRelayUrl) &&\n  (process.env.SYNAPTIC_CLERK_PUBLISHABLE_KEY?.trim() || buildTimeClerkPublishableKey) &&\n  (process.env.SYNAPTIC_CLERK_CLI_OAUTH_CLIENT_ID?.trim() || buildTimeClerkCliOAuthClientId),\n);\n","import {\n  type ProviderDriverKind,\n  type ProviderInstanceId,\n  type ServerProvider,\n  ServerProvider as ServerProviderSchema,\n} from \"@t3tools/contracts\";\nimport { causeErrorTag } from \"@t3tools/shared/observability\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport { writeFileStringAtomically } from \"../atomicWrite.ts\";\n\nconst decodeProviderStatusCache = Schema.decodeUnknownEffect(\n  Schema.fromJsonString(ServerProviderSchema),\n);\n\nconst mergeProviderModels = (\n  fallbackModels: ReadonlyArray<ServerProvider[\"models\"][number]>,\n  cachedModels: ReadonlyArray<ServerProvider[\"models\"][number]>,\n): ReadonlyArray<ServerProvider[\"models\"][number]> => {\n  const fallbackSlugs = new Set(fallbackModels.map((model) => model.slug));\n  return [...fallbackModels, ...cachedModels.filter((model) => !fallbackSlugs.has(model.slug))];\n};\n\nexport const orderProviderSnapshots = (\n  providers: ReadonlyArray<ServerProvider>,\n): ReadonlyArray<ServerProvider> =>\n  [...providers].toSorted(\n    (left, right) =>\n      (left.displayName ?? \"\").localeCompare(right.displayName ?? \"\") ||\n      left.driver.localeCompare(right.driver) ||\n      left.instanceId.localeCompare(right.instanceId),\n  );\n\nexport const isCachedProviderCorrelated = (input: {\n  readonly cachedProvider: ServerProvider;\n  readonly fallbackProvider: ServerProvider;\n}): boolean =>\n  input.cachedProvider.instanceId === input.fallbackProvider.instanceId &&\n  input.cachedProvider.driver === input.fallbackProvider.driver;\n\nexport const hydrateCachedProvider = (input: {\n  readonly cachedProvider: ServerProvider;\n  readonly fallbackProvider: ServerProvider;\n}): ServerProvider => {\n  if (!isCachedProviderCorrelated(input)) {\n    return input.fallbackProvider;\n  }\n\n  if (\n    !input.fallbackProvider.enabled ||\n    input.cachedProvider.enabled !== input.fallbackProvider.enabled\n  ) {\n    return input.fallbackProvider;\n  }\n\n  const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;\n  const hydratedProvider: ServerProvider = {\n    ...fallbackWithoutMessage,\n    models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),\n    installed: input.cachedProvider.installed,\n    version: input.cachedProvider.version,\n    status: input.cachedProvider.status,\n    auth: input.cachedProvider.auth,\n    checkedAt: input.cachedProvider.checkedAt,\n    slashCommands: input.cachedProvider.slashCommands,\n    skills: input.cachedProvider.skills,\n  };\n\n  return input.cachedProvider.message\n    ? { ...hydratedProvider, message: input.cachedProvider.message }\n    : hydratedProvider;\n};\n\n/**\n * Resolve the on-disk cache path for a provider instance snapshot.\n *\n * File naming: `<cacheDir>/<instanceId>.json`. For the default instance of\n * a built-in kind this equals the legacy `<kind>.json` path (because\n * `defaultInstanceIdForDriver(kind).toString() === kind`), so existing\n * cached snapshots remain readable without any rename step.\n *\n * Non-default instances (e.g. `codex_personal`) land in their own files and\n * never collide with other instances.\n *\n * Cache contents must still carry matching `instanceId` + `driver` identity\n * before hydration. The filename alone is not trusted as a routing key.\n */\nexport const resolveProviderStatusCachePath = Effect.fn(\"resolveProviderStatusCachePath\")(\n  function* (input: {\n    readonly cacheDir: string;\n    readonly instanceId: ProviderInstanceId;\n  }): Effect.fn.Return<string, never, Path.Path> {\n    const path = yield* Path.Path;\n    return path.join(input.cacheDir, `${input.instanceId}.json`);\n  },\n);\n\n/**\n * Legacy kind-keyed path resolver retained for callers that still think in\n * terms of `ProviderDriverKind`. Prefer `resolveProviderStatusCachePath` with an\n * `instanceId`; new code should route through the instance registry.\n *\n * @deprecated use `resolveProviderStatusCachePath` with an instance id.\n */\nexport const resolveLegacyProviderStatusCachePath = Effect.fn(\n  \"resolveLegacyProviderStatusCachePath\",\n)(function* (input: {\n  readonly cacheDir: string;\n  readonly provider: ProviderDriverKind;\n}): Effect.fn.Return<string, never, Path.Path> {\n  const path = yield* Path.Path;\n  return path.join(input.cacheDir, `${input.provider}.json`);\n});\n\nexport const readProviderStatusCache = (filePath: string) =>\n  Effect.gen(function* () {\n    const fs = yield* FileSystem.FileSystem;\n    const exists = yield* fs.exists(filePath).pipe(Effect.orElseSucceed(() => false));\n    if (!exists) {\n      return undefined;\n    }\n\n    const raw = yield* fs.readFileString(filePath).pipe(Effect.orElseSucceed(() => \"\"));\n    const trimmed = raw.trim();\n    if (trimmed.length === 0) {\n      return undefined;\n    }\n\n    return yield* decodeProviderStatusCache(trimmed).pipe(\n      Effect.matchCauseEffect({\n        onFailure: (cause) =>\n          Effect.logWarning(\"failed to parse provider status cache, ignoring\", {\n            path: filePath,\n            errorTag: causeErrorTag(cause),\n          }).pipe(Effect.as(undefined)),\n        onSuccess: Effect.succeed,\n      }),\n    );\n  });\n\nexport const writeProviderStatusCache = (input: {\n  readonly filePath: string;\n  readonly provider: ServerProvider;\n}) => {\n  const { updateState: _updateState, ...cacheableProvider } = input.provider;\n  return writeFileStringAtomically({\n    filePath: input.filePath,\n    contents: `${JSON.stringify(cacheableProvider, null, 2)}\\n`,\n  });\n};\n","/**\n * ProviderRegistryLive — aggregates per-instance snapshot streams into a\n * single materialized list.\n *\n * Historically this Layer composed four per-kind Live Layers\n * (`CodexProviderLive`, `ClaudeProviderLive`, …) that each exposed a\n * `ServerProviderShape`. Those Lives were deleted during the driver /\n * instance refactor — every driver now carries its `snapshot: ServerProviderShape`\n * bundled onto the `ProviderInstance` the registry produces.\n *\n * Each configured instance (including multi-instance setups like\n * `codex_personal` + `codex_work`) contributes one `ProviderSnapshotSource`,\n * keyed by `instanceId`. Instances whose driver is unavailable or whose\n * config failed to decode are merged from `instanceRegistry.listUnavailable`\n * as shadow snapshots so the UI can render their exact unavailable reason.\n *\n * Cache paths on disk are now keyed by `instanceId`. Because\n * `defaultInstanceIdForDriver(kind) === kind` for built-in kinds, existing\n * `<kind>.json` files remain the on-disk location for that driver's default\n * instance. Identity-less legacy cache contents are ignored and replaced by\n * the first live refresh.\n *\n * @module ProviderRegistryLive\n */\nimport {\n  defaultInstanceIdForDriver,\n  ProviderDriverKind,\n  type ProviderInstanceId,\n  type ServerProvider,\n  type ServerProviderUpdateState,\n} from \"@t3tools/contracts\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nimport * as PubSub from \"effect/PubSub\";\nimport * as Ref from \"effect/Ref\";\nimport * as Stream from \"effect/Stream\";\nimport * as Semaphore from \"effect/Semaphore\";\n\nimport { ServerConfig } from \"../../config.ts\";\nimport { ProviderInstanceRegistry } from \"../Services/ProviderInstanceRegistry.ts\";\nimport { ProviderRegistry, type ProviderRegistryShape } from \"../Services/ProviderRegistry.ts\";\nimport {\n  hydrateCachedProvider,\n  isCachedProviderCorrelated,\n  orderProviderSnapshots,\n  readProviderStatusCache,\n  resolveProviderStatusCachePath,\n  writeProviderStatusCache,\n} from \"../providerStatusCache.ts\";\nimport type { ProviderInstance } from \"../ProviderDriver.ts\";\nimport { makeManualOnlyProviderMaintenanceCapabilities } from \"../providerMaintenance.ts\";\nimport type { ProviderSnapshotSource } from \"../builtInProviderCatalog.ts\";\n\nconst loadProviders = (\n  providerSources: ReadonlyArray<ProviderSnapshotSource>,\n): Effect.Effect<ReadonlyArray<ServerProvider>> =>\n  Effect.forEach(\n    providerSources,\n    (providerSource) =>\n      providerSource.getSnapshot.pipe(\n        Effect.flatMap((snapshot) => correlateSnapshotWithSource(providerSource, snapshot)),\n      ),\n    {\n      concurrency: \"unbounded\",\n    },\n  );\n\nconst makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) =>\n  makeManualOnlyProviderMaintenanceCapabilities({\n    provider,\n    packageName: null,\n  });\n\nconst hasModelCapabilities = (model: ServerProvider[\"models\"][number]): boolean =>\n  (model.capabilities?.optionDescriptors?.length ?? 0) > 0;\n\nconst shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => {\n  if (provider.driver !== ProviderDriverKind.make(\"opencode\")) {\n    return true;\n  }\n\n  // OpenCode's initial snapshot is deliberately non-authoritative while its\n  // first probe is still running. A probe error from an installed CLI/server\n  // is likewise partial: it could not establish the current inventory.\n  // Conversely, disabled and missing-CLI snapshots are authoritative removals,\n  // as are successful ready/warning inventories (including an empty one after\n  // logout or plugin removal).\n  const isPendingInitialProbe =\n    provider.enabled && !provider.installed && provider.status === \"warning\";\n  const didInstalledProviderProbeFail = provider.installed && provider.status === \"error\";\n  return isPendingInitialProbe || didInstalledProviderProbeFail;\n};\n\nconst mergeProviderModels = (\n  provider: ServerProvider,\n  previousModels: ReadonlyArray<ServerProvider[\"models\"][number]>,\n  nextModels: ReadonlyArray<ServerProvider[\"models\"][number]>,\n): ReadonlyArray<ServerProvider[\"models\"][number]> => {\n  const shouldRetainMissingModels = shouldRetainMissingProviderModels(provider);\n\n  if (shouldRetainMissingModels && nextModels.length === 0 && previousModels.length > 0) {\n    return previousModels;\n  }\n\n  const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));\n  const mergedModels = nextModels.map((model) => {\n    const previousModel = previousBySlug.get(model.slug);\n    if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {\n      return model;\n    }\n    return {\n      ...model,\n      capabilities: previousModel.capabilities,\n    };\n  });\n  const nextSlugs = new Set(nextModels.map((model) => model.slug));\n  return shouldRetainMissingModels\n    ? [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))]\n    : mergedModels;\n};\n\nexport const mergeProviderSnapshot = (\n  previousProvider: ServerProvider | undefined,\n  nextProvider: ServerProvider,\n): ServerProvider =>\n  !previousProvider\n    ? nextProvider\n    : {\n        ...nextProvider,\n        models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models),\n      };\n\nexport const mergeProviderSnapshots = (\n  previousProviders: ReadonlyArray<ServerProvider>,\n  nextProviders: ReadonlyArray<ServerProvider>,\n): ReadonlyArray<ServerProvider> => {\n  const mergedProviders = new Map(\n    previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),\n  );\n\n  for (const provider of nextProviders) {\n    mergedProviders.set(\n      snapshotInstanceKey(provider),\n      mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),\n    );\n  }\n\n  return orderProviderSnapshots([...mergedProviders.values()]);\n};\n\nexport const selectProvidersByKind = (\n  providers: ReadonlyArray<ServerProvider>,\n  providerKinds: ReadonlySet<ProviderDriverKind>,\n): ReadonlyArray<ServerProvider> =>\n  providers.filter((provider) => providerKinds.has(provider.driver));\n\nexport const haveProvidersChanged = (\n  previousProviders: ReadonlyArray<ServerProvider>,\n  nextProviders: ReadonlyArray<ServerProvider>,\n): boolean => !Equal.equals(previousProviders, nextProviders);\n\nconst correlateSnapshotWithSource = (\n  source: ProviderSnapshotSource,\n  snapshot: ServerProvider,\n): Effect.Effect<ServerProvider> => {\n  if (snapshot.instanceId !== source.instanceId) {\n    return Effect.die(\n      new Error(\n        `Provider snapshot instance mismatch: source '${source.instanceId}' emitted '${snapshot.instanceId}'.`,\n      ),\n    );\n  }\n  if (snapshot.driver !== source.driverKind) {\n    return Effect.die(\n      new Error(\n        `Provider snapshot driver mismatch for instance '${source.instanceId}': source '${source.driverKind}' emitted '${snapshot.driver}'.`,\n      ),\n    );\n  }\n  return Effect.succeed(snapshot);\n};\n\n/**\n * Key a snapshot for aggregation and persistence. Snapshot sources\n * must be correlated by instance id before reaching this map; missing\n * identities are defects, not runtime routing fallbacks.\n */\nconst snapshotInstanceKey = (provider: ServerProvider): ProviderInstanceId => {\n  return provider.instanceId;\n};\n\n// Project a live `ProviderInstance` into the aggregator's consumption\n// shape. Each call re-captures the instance's `snapshot` closures, so\n// after `ProviderInstanceRegistry` rebuilds an instance (e.g. because\n// its settings changed), a fresh source rides the new PubSub instead\n// of a closed one.\nconst buildSnapshotSource = (instance: ProviderInstance): ProviderSnapshotSource => ({\n  instanceId: instance.instanceId,\n  driverKind: instance.driverKind,\n  getSnapshot: instance.snapshot.getSnapshot,\n  refresh: instance.snapshot.refresh,\n  streamChanges: instance.snapshot.streamChanges,\n});\n\nexport const ProviderRegistryLive = Layer.effect(\n  ProviderRegistry,\n  Effect.gen(function* () {\n    const instanceRegistry = yield* ProviderInstanceRegistry;\n    const config = yield* ServerConfig;\n    const fileSystem = yield* FileSystem.FileSystem;\n    const path = yield* Path.Path;\n\n    // Aggregator PubSub — consumers (WS gateway, etc.) subscribe here for\n    // coalesced updates across every instance.\n    const changesPubSub = yield* Effect.acquireRelease(\n      PubSub.unbounded<ReadonlyArray<ServerProvider>>(),\n      PubSub.shutdown,\n    );\n\n    // Boot-only: hydrate `providersRef` from the on-disk per-instance\n    // cache so the UI has something to render during the first refresh.\n    // Instances added post-boot skip this path; their first entry in\n    // `providersRef` comes from the reactive `syncLiveSources` pass\n    // below.\n    const bootInstances = yield* instanceRegistry.listInstances;\n    const bootSources = bootInstances.map(buildSnapshotSource);\n    const fallbackProviders = yield* loadProviders(bootSources);\n    const fallbackByInstance = new Map<ProviderInstanceId, ServerProvider>();\n    for (let index = 0; index < fallbackProviders.length; index++) {\n      const provider = fallbackProviders[index];\n      const source = bootSources[index];\n      if (provider === undefined || source === undefined) {\n        continue;\n      }\n      fallbackByInstance.set(source.instanceId, provider);\n    }\n\n    const cachedProviders = yield* Effect.forEach(\n      bootSources,\n      (source) =>\n        Effect.gen(function* () {\n          // One cache file per configured instance. For the default\n          // instance of a built-in kind the path equals `<kind>.json` —\n          // identical to the legacy filename. We still require the cache\n          // payload to carry matching instance id + driver kind; old\n          // identity-less payloads are discarded and the awaited refresh\n          // below repopulates the cache.\n          const filePath = yield* resolveProviderStatusCachePath({\n            cacheDir: config.providerStatusCacheDir,\n            instanceId: source.instanceId,\n          }).pipe(Effect.provideService(Path.Path, path));\n          const fallbackProvider = fallbackByInstance.get(source.instanceId);\n          if (fallbackProvider === undefined) {\n            return undefined;\n          }\n          return yield* readProviderStatusCache(filePath).pipe(\n            Effect.provideService(FileSystem.FileSystem, fileSystem),\n            Effect.flatMap((cachedProvider) => {\n              if (cachedProvider === undefined) {\n                return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));\n              }\n              const correlation = {\n                cachedProvider,\n                fallbackProvider,\n              } as const;\n              if (!isCachedProviderCorrelated(correlation)) {\n                return Effect.logWarning(\"provider status cache identity mismatch, ignoring\", {\n                  path: filePath,\n                  instanceId: source.instanceId,\n                  cachedInstanceId: cachedProvider.instanceId ?? null,\n                  driver: source.driverKind,\n                  cachedDriver: cachedProvider.driver ?? null,\n                }).pipe(Effect.as(undefined as ServerProvider | undefined));\n              }\n              return Effect.succeed(hydrateCachedProvider(correlation));\n            }),\n          );\n        }),\n      { concurrency: \"unbounded\" },\n    ).pipe(\n      Effect.map((providers) =>\n        orderProviderSnapshots(\n          providers.filter((provider): provider is ServerProvider => provider !== undefined),\n        ),\n      ),\n    );\n    const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(cachedProviders);\n    const maintenanceActionStatesRef = yield* Ref.make<\n      ReadonlyMap<ProviderInstanceId, { readonly update?: ServerProviderUpdateState | undefined }>\n    >(new Map());\n\n    // Live-source registry — the dynamic counterpart to the boot-time\n    // `bootSources`. Keyed by `instanceId`; the stored `ProviderInstance`\n    // reference is used for identity equality so \"no-op\" reconciles\n    // (settings unchanged) skip re-subscribing + re-probing.\n    const liveSubsRef = yield* Ref.make<ReadonlyMap<ProviderInstanceId, ProviderInstance>>(\n      new Map(),\n    );\n    // Serialize `syncLiveSources` so a rapid burst of reconciles doesn't\n    // interleave two passes clobbering each other's fiber bookkeeping.\n    const syncSemaphore = yield* Semaphore.make(1);\n\n    const getLiveSources: Effect.Effect<ReadonlyArray<ProviderSnapshotSource>> = Ref.get(\n      liveSubsRef,\n    ).pipe(Effect.map((map) => Array.from(map.values(), buildSnapshotSource)));\n\n    const persistProvider = (provider: ServerProvider) =>\n      Effect.gen(function* () {\n        // Persist every instance — the file name is the instance id, so\n        // multi-instance setups (e.g. `codex_personal`, `codex_work`) each\n        // get their own cache. We resolve the path fresh so snapshots\n        // produced by newly-added instances post-boot still land on disk\n        // without the aggregator holding a stale `cachePathByInstance`\n        // entry.\n        const key = snapshotInstanceKey(provider);\n        const filePath = yield* resolveProviderStatusCachePath({\n          cacheDir: config.providerStatusCacheDir,\n          instanceId: key,\n        }).pipe(Effect.provideService(Path.Path, path));\n        yield* writeProviderStatusCache({ filePath, provider }).pipe(\n          Effect.provideService(FileSystem.FileSystem, fileSystem),\n          Effect.provideService(Path.Path, path),\n          Effect.tapError(Effect.logError),\n          Effect.ignore,\n        );\n      });\n\n    const applyProviderUpdateState = Effect.fn(\"applyProviderUpdateState\")(function* (\n      provider: ServerProvider,\n    ) {\n      const maintenanceActionStates = yield* Ref.get(maintenanceActionStatesRef);\n      const updateState = maintenanceActionStates.get(provider.instanceId)?.update;\n      if (!updateState) {\n        const { updateState: _updateState, ...providerWithoutUpdateState } = provider;\n        return providerWithoutUpdateState;\n      }\n      return {\n        ...provider,\n        updateState,\n      };\n    });\n\n    const upsertProviders = Effect.fn(\"upsertProviders\")(function* (\n      nextProviders: ReadonlyArray<ServerProvider>,\n      options?: {\n        readonly publish?: boolean;\n        readonly persist?: boolean;\n        readonly replace?: boolean;\n      },\n    ) {\n      const nextProvidersWithUpdateState = yield* Effect.forEach(\n        nextProviders,\n        applyProviderUpdateState,\n        {\n          concurrency: \"unbounded\",\n        },\n      );\n      const [previousProviders, providers, providersToPersist] = yield* Ref.modify(\n        providersRef,\n        (previousProviders) => {\n          const mergedProviders = new Map(\n            previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),\n          );\n          const updatedKeys = new Set<ProviderInstanceId>();\n\n          for (const provider of nextProvidersWithUpdateState) {\n            const key = snapshotInstanceKey(provider);\n            updatedKeys.add(key);\n            mergedProviders.set(\n              key,\n              options?.replace === true\n                ? provider\n                : mergeProviderSnapshot(mergedProviders.get(key), provider),\n            );\n          }\n\n          const providers = orderProviderSnapshots([...mergedProviders.values()]);\n          const providersToPersist = providers.filter((provider) =>\n            updatedKeys.has(snapshotInstanceKey(provider)),\n          );\n          return [[previousProviders, providers, providersToPersist] as const, providers];\n        },\n      );\n\n      if (haveProvidersChanged(previousProviders, providers)) {\n        if (options?.persist !== false) {\n          yield* Effect.forEach(providersToPersist, persistProvider, {\n            concurrency: \"unbounded\",\n            discard: true,\n          });\n        }\n        if (options?.publish !== false) {\n          yield* PubSub.publish(changesPubSub, providers);\n        }\n      }\n\n      return providers;\n    });\n\n    const syncProvider = Effect.fn(\"syncProvider\")(function* (\n      provider: ServerProvider,\n      options?: {\n        readonly publish?: boolean;\n      },\n    ) {\n      return yield* upsertProviders([provider], options);\n    });\n\n    const setProviderMaintenanceActionState = Effect.fn(\"setProviderMaintenanceActionState\")(\n      function* (input: {\n        readonly instanceId: ProviderInstanceId;\n        readonly action: \"update\";\n        readonly state: ServerProviderUpdateState | null;\n      }) {\n        yield* Ref.update(maintenanceActionStatesRef, (previous) => {\n          const previousActions = previous.get(input.instanceId);\n          const nextActions = { ...previousActions };\n          if (input.state === null || input.state.status === \"idle\") {\n            delete nextActions[input.action];\n          } else {\n            nextActions[input.action] = input.state;\n          }\n\n          const next = new Map(previous);\n          if (Object.keys(nextActions).length === 0) {\n            next.delete(input.instanceId);\n          } else {\n            next.set(input.instanceId, nextActions);\n          }\n          return next;\n        });\n\n        const existingProviders = yield* Ref.get(providersRef);\n        const matchingProvider = existingProviders.find(\n          (candidate) => candidate.instanceId === input.instanceId,\n        );\n        if (!matchingProvider) {\n          return existingProviders;\n        }\n\n        const nextProvider = yield* applyProviderUpdateState(matchingProvider);\n        return yield* upsertProviders([nextProvider], {\n          persist: false,\n        });\n      },\n    );\n\n    const refreshOneSource = Effect.fn(\"refreshOneSource\")(function* (\n      providerSource: ProviderSnapshotSource,\n    ) {\n      return yield* providerSource.refresh.pipe(\n        Effect.flatMap((nextProvider) =>\n          correlateSnapshotWithSource(providerSource, nextProvider).pipe(\n            Effect.flatMap(syncProvider),\n          ),\n        ),\n      );\n    });\n\n    const refreshAll = Effect.fn(\"refreshAll\")(function* () {\n      const sources = yield* getLiveSources;\n      return yield* Effect.forEach(sources, (source) => refreshOneSource(source), {\n        concurrency: \"unbounded\",\n        discard: true,\n      }).pipe(Effect.andThen(Ref.get(providersRef)));\n    });\n\n    const refresh = Effect.fn(\"refresh\")(function* (provider?: ProviderDriverKind) {\n      if (provider === undefined) {\n        return yield* refreshAll();\n      }\n      // Kind-scoped refreshes target the default instance for that driver.\n      const defaultInstanceId = defaultInstanceIdForDriver(provider);\n      const sources = yield* getLiveSources;\n      const providerSource = sources.find(\n        (candidate) => candidate.instanceId === defaultInstanceId,\n      );\n      if (!providerSource) {\n        return yield* Ref.get(providersRef);\n      }\n      return yield* refreshOneSource(providerSource);\n    });\n\n    const refreshInstance = Effect.fn(\"refreshInstance\")(function* (\n      instanceId: ProviderInstanceId,\n    ) {\n      const sources = yield* getLiveSources;\n      const providerSource = sources.find((candidate) => candidate.instanceId === instanceId);\n      if (!providerSource) {\n        return yield* Ref.get(providersRef);\n      }\n      return yield* refreshOneSource(providerSource);\n    });\n\n    const getProviderMaintenanceCapabilitiesForInstance = Effect.fn(\n      \"getProviderMaintenanceCapabilitiesForInstance\",\n    )(function* (instanceId: ProviderInstanceId, provider: ProviderDriverKind) {\n      const instance = Array.from((yield* Ref.get(liveSubsRef)).values()).find(\n        (candidate) => candidate.instanceId === instanceId,\n      );\n      return (\n        instance?.snapshot.maintenanceCapabilities ??\n        makeManualProviderMaintenanceCapabilities(provider)\n      );\n    });\n\n    /**\n     * Diff the aggregator's live-source set against the current\n     * `ProviderInstanceRegistry` and:\n     *   - subscribe to each newly-added or rebuilt instance's\n     *     `streamChanges` (so periodic + enrichment refreshes land in\n     *     `providersRef`);\n     *   - read each newly-added/rebuilt instance's current snapshot after\n     *     subscribing, closing the race with its independently-running\n     *     background startup probe;\n     *   - prune `providersRef` of instances that no longer exist.\n     *\n     * Provider refreshes are owned by each managed provider and never run\n     * on this layer's construction path. Consumers see cached or pending\n     * snapshots immediately, then receive live probe results through the\n     * already-attached change stream.\n     *\n     * Per-instance subscription fibers are not tracked explicitly. When\n     * a rebuilt instance's old child scope closes, its PubSub shuts\n     * down and our `Stream.runForEach` fiber exits naturally.\n     */\n    const syncLiveSources = syncSemaphore.withPermits(1)(\n      Effect.gen(function* () {\n        const instances = yield* instanceRegistry.listInstances;\n        const unavailableProviders = yield* instanceRegistry.listUnavailable;\n        const nextByInstance = new Map<ProviderInstanceId, ProviderInstance>(\n          instances.map((instance) => [instance.instanceId, instance] as const),\n        );\n        const knownInstanceIds = new Set<ProviderInstanceId>(nextByInstance.keys());\n        for (const provider of unavailableProviders) {\n          knownInstanceIds.add(snapshotInstanceKey(provider));\n        }\n        const previousSubs = yield* Ref.get(liveSubsRef);\n\n        // Carry over subscriptions for instances whose identity is\n        // unchanged (reconcile treated them as no-op). Instances that\n        // disappeared, or were rebuilt with a different reference,\n        // fall through to the \"newly-added\" branch below.\n        const carriedOver = new Map<ProviderInstanceId, ProviderInstance>();\n        for (const [instanceId, previousInstance] of previousSubs) {\n          const nextInstance = nextByInstance.get(instanceId);\n          if (nextInstance !== undefined && nextInstance === previousInstance) {\n            carriedOver.set(instanceId, previousInstance);\n          }\n        }\n\n        // Collect new/rebuilt instances in `nextByInstance` insertion\n        // order (which preserves settings-author order).\n        const newlyAdded: Array<readonly [ProviderInstanceId, ProviderInstance]> = [];\n        for (const [instanceId, instance] of nextByInstance) {\n          if (carriedOver.has(instanceId)) {\n            continue;\n          }\n          newlyAdded.push([instanceId, instance] as const);\n        }\n\n        // Fork long-lived subscriptions to each new/rebuilt instance's\n        // change stream before reading its current snapshot. If the\n        // driver's own initial probe finishes during this sync, either\n        // the current read or the active subscriber observes the result.\n        for (const [, instance] of newlyAdded) {\n          const source = buildSnapshotSource(instance);\n          yield* Stream.runForEach(source.streamChanges, (provider) =>\n            correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),\n          ).pipe(Effect.forkScoped);\n        }\n        yield* Effect.yieldNow;\n\n        // Snapshot current state without starting a probe. Managed providers\n        // launch their startup refresh independently, so this closes the\n        // subscription race without putting external work on the registry\n        // or HTTP server construction path.\n        yield* Effect.forEach(\n          newlyAdded,\n          ([, instance]) =>\n            Effect.gen(function* () {\n              const source = buildSnapshotSource(instance);\n              const provider = yield* source.getSnapshot;\n              yield* correlateSnapshotWithSource(source, provider).pipe(\n                Effect.flatMap(syncProvider),\n              );\n            }).pipe(Effect.ignoreCause({ log: true })),\n          { concurrency: \"unbounded\", discard: true },\n        );\n        yield* upsertProviders(unavailableProviders, {\n          persist: false,\n          replace: true,\n        });\n\n        const nextSubs = new Map(carriedOver);\n        for (const [instanceId, instance] of newlyAdded) {\n          nextSubs.set(instanceId, instance);\n        }\n        yield* Ref.set(liveSubsRef, nextSubs);\n\n        // Drop aggregator state for instances that have disappeared —\n        // otherwise the UI would keep rendering ghosts.\n        const [previousProviders, providers] = yield* Ref.modify(\n          providersRef,\n          (previousProviders) => {\n            const providers = orderProviderSnapshots(\n              previousProviders.filter((provider) =>\n                knownInstanceIds.has(snapshotInstanceKey(provider)),\n              ),\n            );\n            return [[previousProviders, providers] as const, providers];\n          },\n        );\n        if (haveProvidersChanged(previousProviders, providers)) {\n          yield* PubSub.publish(changesPubSub, providers);\n        }\n        yield* Ref.update(maintenanceActionStatesRef, (previous) => {\n          const next = new Map(previous);\n          for (const instanceId of previous.keys()) {\n            if (!knownInstanceIds.has(instanceId)) {\n              next.delete(instanceId);\n            }\n          }\n          return next;\n        });\n      }),\n    );\n    const syncLiveSourcesAndContinue = syncLiveSources.pipe(\n      Effect.catchCause((cause) => {\n        if (Cause.hasInterruptsOnly(cause)) {\n          return Effect.interrupt;\n        }\n        return Effect.logError(\n          \"provider registry instance sync failed; keeping subscription alive\",\n          {\n            cause: Cause.pretty(cause),\n          },\n        );\n      }),\n    );\n\n    // Seed `providersRef` with the boot-time fallback snapshots so\n    // consumers calling `getProviders` immediately after layer build see\n    // a populated list — even before the first `syncLiveSources` refresh\n    // resolves. Cached snapshots (already in `providersRef`) merge with\n    // these via `upsertProviders` so on-disk state wins where present\n    // and pending fallbacks fill the gaps.\n    yield* upsertProviders(fallbackProviders, { publish: false });\n    // Subscribe to registry mutations BEFORE running the initial sync.\n    // `subscribeChanges` acquires the dequeue synchronously in this\n    // fibre; the subscription is active the instant this `yield*`\n    // returns. Forking the consumer loop later cannot lose a publish\n    // because no publish can reach a not-yet-subscribed dequeue.\n    //\n    // (Contrast with the pre-fix code that did\n    // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.\n    // `Stream.fromPubSub` defers `PubSub.subscribe` to stream start,\n    // and `forkScoped` only schedules the fibre — so a reconcile that\n    // published between \"fibre scheduled\" and \"fibre starts running\"\n    // was dropped, which made any settings change that replaced an\n    // instance never propagate to the aggregator's `providersRef`.)\n    // Subscribe to registry mutations BEFORE running the initial sync.\n    // `subscribeChanges` acquires the `PubSub.Subscription` synchronously\n    // in this fibre; the subscription is registered with the PubSub the\n    // instant this `yield*` returns, so any subsequent publish is\n    // buffered in the subscription regardless of when the consumer\n    // fibre below actually starts running.\n    //\n    // (Contrast with the pre-fix code that did\n    // `Stream.runForEach(instanceRegistry.streamChanges, …).pipe(Effect.forkScoped)`.\n    // `instanceRegistry.streamChanges` is `Stream.fromPubSub(changes)`,\n    // which defers `PubSub.subscribe` to stream start. `forkScoped` only\n    // schedules the consumer fibre — so a reconcile that published\n    // between \"fibre scheduled\" and \"fibre starts running + subscribes\"\n    // was dropped, which made any settings change that replaced an\n    // instance never propagate to the aggregator's `providersRef`.)\n    const instanceChanges = yield* instanceRegistry.subscribeChanges;\n    // Initial sync attaches subscriptions and snapshots current state for\n    // every instance present at boot. Provider probes are already running in\n    // their managed background fibers and never block this layer.\n    yield* syncLiveSources;\n    // React to registry mutations — instance added / removed / rebuilt.\n    // `Stream.fromSubscription` builds a stream over the pre-acquired\n    // subscription rather than subscribing on stream start, which is\n    // what closes the race.\n    yield* Stream.runForEach(\n      Stream.fromSubscription(instanceChanges),\n      () => syncLiveSourcesAndContinue,\n    ).pipe(Effect.forkScoped);\n\n    const recoverRefreshFailure = Effect.fn(\"recoverRefreshFailure\")(function* (\n      cause: Cause.Cause<unknown>,\n    ) {\n      if (Cause.hasInterruptsOnly(cause)) {\n        return yield* Effect.interrupt;\n      }\n      yield* Effect.logError(\"provider registry refresh failed; preserving cached providers\", {\n        cause: Cause.pretty(cause),\n      });\n      return yield* Ref.get(providersRef);\n    });\n\n    return {\n      getProviders: Ref.get(providersRef),\n      refresh: (provider?: ProviderDriverKind) =>\n        refresh(provider).pipe(Effect.catchCause(recoverRefreshFailure)),\n      refreshInstance: (instanceId: ProviderInstanceId) =>\n        refreshInstance(instanceId).pipe(Effect.catchCause(recoverRefreshFailure)),\n      getProviderMaintenanceCapabilitiesForInstance,\n      setProviderMaintenanceActionState,\n      get streamChanges() {\n        return Stream.fromPubSub(changesPubSub);\n      },\n    } satisfies ProviderRegistryShape;\n  }),\n);\n","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Headers from \"effect/unstable/http/Headers\";\n\nexport const httpHeaderRedactionLayer = Layer.effect(\n  Headers.CurrentRedactedNames,\n  Effect.map(Headers.CurrentRedactedNames, (names) => [...names, \"dpop\"]),\n);\n","import * as Effect from \"effect/Effect\";\nimport * as Logger from \"effect/Logger\";\nimport * as References from \"effect/References\";\nimport * as Layer from \"effect/Layer\";\n\nimport { ServerConfig } from \"./config.ts\";\n\nexport const ServerLoggerLive = Effect.gen(function* () {\n  const config = yield* ServerConfig;\n  const minimumLogLevelLayer = Layer.succeed(References.MinimumLogLevel, config.logLevel);\n  const loggerLayer = Logger.layer([Logger.consolePretty(), Logger.tracerLogger], {\n    mergeWithExisting: false,\n  });\n\n  return Layer.mergeAll(loggerLayer, minimumLogLevelLayer);\n}).pipe(Layer.unwrap);\n","import { httpHeaderRedactionLayer } from \"@t3tools/shared/httpObservability\";\nimport { makeLocalFileTracer, makeTraceSink } from \"@t3tools/shared/observability\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as References from \"effect/References\";\nimport * as Tracer from \"effect/Tracer\";\nimport * as OtlpExporter from \"effect/unstable/observability/OtlpExporter\";\nimport * as OtlpMetrics from \"effect/unstable/observability/OtlpMetrics\";\nimport * as OtlpSerialization from \"effect/unstable/observability/OtlpSerialization\";\nimport * as OtlpTracer from \"effect/unstable/observability/OtlpTracer\";\n\nimport * as ServerConfig from \"../../config.ts\";\nimport * as ResourceAttribution from \"../../resourceTelemetry/ResourceAttribution.ts\";\nimport { ServerLoggerLive } from \"../../serverLogger.ts\";\nimport * as BrowserTraceCollector from \"../BrowserTraceCollector.ts\";\n\nconst otlpSerializationLayer = OtlpSerialization.layerJson;\n\nexport const ObservabilityLive = Layer.unwrap(\n  Effect.gen(function* () {\n    const config = yield* ServerConfig.ServerConfig;\n    const attribution = yield* ResourceAttribution.ResourceAttribution;\n\n    const traceReferencesLayer = Layer.mergeAll(\n      Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),\n      Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),\n      httpHeaderRedactionLayer,\n    );\n\n    const tracerLayer = Layer.unwrap(\n      Effect.gen(function* () {\n        const sink = yield* makeTraceSink({\n          filePath: config.serverTracePath,\n          maxBytes: config.traceMaxBytes,\n          maxFiles: config.traceMaxFiles,\n          batchWindowMs: config.traceBatchWindowMs,\n          onFlush: (stats) =>\n            attribution.record({\n              component: \"server-trace\",\n              operation: \"append\",\n              logicalWriteBytes: stats.logicalWriteBytes,\n              count: stats.count,\n              durationMs: stats.durationMs,\n            }),\n        });\n        const delegate =\n          config.otlpTracesUrl === undefined\n            ? undefined\n            : yield* OtlpTracer.make({\n                url: config.otlpTracesUrl,\n                exportInterval: `${config.otlpExportIntervalMs} millis`,\n                resource: {\n                  serviceName: config.otlpServiceName,\n                  attributes: {\n                    \"service.runtime\": \"t3-server\",\n                    \"service.mode\": config.mode,\n                  },\n                },\n              });\n\n        const tracer = yield* makeLocalFileTracer({\n          filePath: config.serverTracePath,\n          maxBytes: config.traceMaxBytes,\n          maxFiles: config.traceMaxFiles,\n          batchWindowMs: config.traceBatchWindowMs,\n          sink,\n          ...(delegate ? { delegate } : {}),\n        });\n\n        return Layer.mergeAll(\n          Layer.succeed(Tracer.Tracer, tracer),\n          BrowserTraceCollector.layer(sink),\n        );\n      }),\n    ).pipe(Layer.provide(OtlpExporter.layerFlusher), Layer.provideMerge(otlpSerializationLayer));\n\n    const metricsLayer =\n      config.otlpMetricsUrl === undefined\n        ? Layer.empty\n        : OtlpMetrics.layer({\n            url: config.otlpMetricsUrl,\n            exportInterval: `${config.otlpExportIntervalMs} millis`,\n            resource: {\n              serviceName: config.otlpServiceName,\n              attributes: {\n                \"service.runtime\": \"t3-server\",\n                \"service.mode\": config.mode,\n              },\n            },\n          }).pipe(Layer.provideMerge(otlpSerializationLayer));\n\n    return Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer);\n  }),\n);\n","import type { RelayManagedEndpointRuntimeConfig } from \"@t3tools/contracts/relay\";\nimport * as RelayClient from \"@t3tools/shared/relayClient\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\nimport * as ChildProcess from \"effect/unstable/process/ChildProcess\";\nimport * as ChildProcessSpawner from \"effect/unstable/process/ChildProcessSpawner\";\n\nimport * as ServerSecretStore from \"../auth/ServerSecretStore.ts\";\nimport { CLOUD_ENDPOINT_RUNTIME_CONFIG, decodeRuntimeConfig } from \"./config.ts\";\n\nfunction bytesToString(bytes: Uint8Array): string {\n  return new TextDecoder().decode(bytes);\n}\n\nconst readRuntimeConfig = Effect.gen(function* () {\n  const secrets = yield* ServerSecretStore.ServerSecretStore;\n  const bytes = yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);\n  if (Option.isNone(bytes)) {\n    return null;\n  }\n  return Option.getOrNull(decodeRuntimeConfig(bytesToString(bytes.value)));\n});\n\nexport type CloudManagedEndpointRuntimeStatus =\n  | {\n      readonly status: \"disabled\";\n    }\n  | {\n      readonly status: \"failed\";\n      readonly providerKind: RelayManagedEndpointRuntimeConfig[\"providerKind\"];\n      readonly reason: string;\n      readonly tunnelId?: string;\n      readonly tunnelName?: string;\n    }\n  | {\n      readonly status: \"running\";\n      readonly providerKind: \"cloudflare_tunnel\";\n      readonly pid: number;\n      readonly tunnelId?: string;\n      readonly tunnelName?: string;\n    }\n  | {\n      readonly status: \"unsupported\";\n      readonly providerKind: RelayManagedEndpointRuntimeConfig[\"providerKind\"];\n    };\n\nexport class CloudManagedEndpointRuntime extends Context.Service<\n  CloudManagedEndpointRuntime,\n  {\n    readonly applyConfig: (\n      config: RelayManagedEndpointRuntimeConfig | null,\n    ) => Effect.Effect<CloudManagedEndpointRuntimeStatus>;\n  }\n>()(\"t3/cloud/ManagedEndpointRuntime/CloudManagedEndpointRuntime\") {}\n\ninterface ActiveConnector {\n  readonly child: ChildProcessSpawner.ChildProcessHandle;\n  readonly scope: Scope.Closeable;\n  readonly configKey: string;\n  readonly config: RelayManagedEndpointRuntimeConfig;\n}\n\nexport function classifyRelayClientOutput(line: string): \"connected\" | \"warning\" | \"debug\" {\n  if (/\\bRegistered tunnel connection\\b/iu.test(line)) {\n    return \"connected\";\n  }\n  // cloudflared uses zerolog level tokens. FTL (fatal) and PNC (panic) are more\n  // severe than ERR, so they must surface at least as loudly — without them a\n  // fatal connector failure would be logged at debug and hidden.\n  return /\\b(?:ERR|WRN|FTL|PNC)\\b/u.test(line) ? \"warning\" : \"debug\";\n}\n\nfunction runtimeConfigKey(config: RelayManagedEndpointRuntimeConfig): string {\n  return JSON.stringify({\n    providerKind: config.providerKind,\n    connectorToken: config.connectorToken,\n    tunnelId: config.tunnelId ?? null,\n    tunnelName: config.tunnelName ?? null,\n  });\n}\n\nconst stopConnector = (connector: ActiveConnector | null) =>\n  connector\n    ? Scope.close(connector.scope, Exit.void).pipe(\n        Effect.tap(() =>\n          Effect.logInfo(\"Relay client stopped\", {\n            pid: Number(connector.child.pid),\n          }),\n        ),\n        Effect.ignore,\n      )\n    : Effect.void;\n\nexport const make = Effect.gen(function* () {\n  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n  const relayClient = yield* RelayClient.RelayClient;\n  const activeRef = yield* Ref.make<ActiveConnector | null>(null);\n  const desiredConfigRef = yield* Ref.make<RelayManagedEndpointRuntimeConfig | null>(null);\n  const reconcileSemaphore = yield* Semaphore.make(1);\n  let reconcileConfig: CloudManagedEndpointRuntime[\"Service\"][\"applyConfig\"];\n\n  const stopActive = Effect.gen(function* () {\n    const active = yield* Ref.getAndSet(activeRef, null);\n    yield* stopConnector(active);\n  });\n\n  const superviseConnector = (connector: ActiveConnector) =>\n    Effect.gen(function* () {\n      const result = yield* Effect.result(connector.child.exitCode);\n      yield* reconcileSemaphore.withPermits(1)(\n        Effect.gen(function* () {\n          const active = yield* Ref.get(activeRef);\n          if (\n            active?.child.pid !== connector.child.pid ||\n            active.configKey !== connector.configKey\n          ) {\n            return;\n          }\n          yield* Ref.set(activeRef, null);\n          yield* stopConnector(connector);\n\n          const desiredConfig = yield* Ref.get(desiredConfigRef);\n          if (\n            !desiredConfig ||\n            desiredConfig.providerKind !== \"cloudflare_tunnel\" ||\n            runtimeConfigKey(desiredConfig) !== connector.configKey\n          ) {\n            return;\n          }\n\n          yield* Effect.logWarning(\"Relay client exited; restarting\", {\n            pid: Number(connector.child.pid),\n            ...(Result.isSuccess(result)\n              ? { exitCode: Number(result.success) }\n              : { cause: result.failure }),\n            tunnelId: connector.config.tunnelId,\n            tunnelName: connector.config.tunnelName,\n          });\n          yield* reconcileConfig(desiredConfig);\n        }),\n      );\n    }).pipe(\n      Effect.catchCause((cause) => Effect.logWarning(\"Relay client supervisor failed\", { cause })),\n    );\n\n  const observeConnectorOutput = (connector: ActiveConnector) =>\n    connector.child.all.pipe(\n      Stream.decodeText(),\n      Stream.splitLines,\n      Stream.map((line) => line.trim()),\n      Stream.filter((line) => line.length > 0),\n      Stream.runForEach((line) => {\n        const output = line.replaceAll(connector.config.connectorToken, \"<redacted>\");\n        const attributes = {\n          pid: Number(connector.child.pid),\n          tunnelId: connector.config.tunnelId,\n          tunnelName: connector.config.tunnelName,\n          output,\n        };\n        switch (classifyRelayClientOutput(line)) {\n          case \"connected\":\n            return Effect.logInfo(\"Relay client tunnel connection registered\", attributes);\n          case \"warning\":\n            return Effect.logWarning(\"Relay client reported a transport warning\", attributes);\n          case \"debug\":\n            return Effect.logDebug(\"Relay client output\", attributes);\n        }\n      }),\n      Effect.catchCause((cause) =>\n        Effect.logWarning(\"Relay client output observer failed\", {\n          cause,\n          pid: Number(connector.child.pid),\n          tunnelId: connector.config.tunnelId,\n          tunnelName: connector.config.tunnelName,\n        }),\n      ),\n    );\n\n  reconcileConfig = Effect.fn(\"CloudManagedEndpointRuntime.reconcileConfig\")(function* (config) {\n    if (!config || config.providerKind !== \"cloudflare_tunnel\") {\n      yield* stopActive;\n      return config\n        ? { status: \"unsupported\", providerKind: config.providerKind }\n        : { status: \"disabled\" };\n    }\n\n    const nextConfigKey = runtimeConfigKey(config);\n    const active = yield* Ref.get(activeRef);\n    if (active?.configKey === nextConfigKey) {\n      const isRunning = yield* active.child.isRunning.pipe(Effect.orElseSucceed(() => false));\n      if (isRunning) {\n        return {\n          status: \"running\",\n          providerKind: \"cloudflare_tunnel\",\n          pid: Number(active.child.pid),\n          ...(active.config.tunnelId ? { tunnelId: active.config.tunnelId } : {}),\n          ...(active.config.tunnelName ? { tunnelName: active.config.tunnelName } : {}),\n        } satisfies CloudManagedEndpointRuntimeStatus;\n      }\n    }\n\n    yield* stopActive;\n\n    const executable = yield* relayClient.resolve;\n    if (executable.status !== \"available\") {\n      return {\n        status: \"failed\",\n        providerKind: \"cloudflare_tunnel\",\n        reason:\n          executable.status === \"unsupported\"\n            ? `Relay client is unsupported on ${executable.platform}-${executable.arch}.`\n            : \"The relay client is not installed.\",\n        ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),\n        ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),\n      } satisfies CloudManagedEndpointRuntimeStatus;\n    }\n\n    const connectorScope = yield* Scope.make(\"sequential\");\n    const child = yield* spawner\n      .spawn(\n        ChildProcess.make(executable.executablePath, [\"tunnel\", \"run\"], {\n          detached: false,\n          env: {\n            ...process.env,\n            TUNNEL_TOKEN: config.connectorToken,\n          },\n          shell: false,\n          stderr: \"pipe\",\n          stdout: \"pipe\",\n        }),\n      )\n      .pipe(\n        Effect.provideService(Scope.Scope, connectorScope),\n        Effect.tap((child) =>\n          Effect.logInfo(\"Relay client process started; waiting for tunnel connection\", {\n            pid: Number(child.pid),\n            tunnelId: config.tunnelId,\n            tunnelName: config.tunnelName,\n          }),\n        ),\n        Effect.catch((cause) =>\n          Effect.logWarning(\"Failed to start relay client\", {\n            cause,\n            tunnelId: config.tunnelId,\n            tunnelName: config.tunnelName,\n          }).pipe(\n            Effect.andThen(Scope.close(connectorScope, Exit.void).pipe(Effect.ignore)),\n            Effect.as({\n              status: \"failed\",\n              providerKind: \"cloudflare_tunnel\",\n              reason: String(cause),\n              ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),\n              ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),\n            } satisfies CloudManagedEndpointRuntimeStatus),\n          ),\n        ),\n      );\n\n    if (\"status\" in child && child.status === \"failed\") {\n      return child;\n    }\n\n    if (!(\"status\" in child)) {\n      const connector = {\n        child,\n        scope: connectorScope,\n        configKey: nextConfigKey,\n        config,\n      } satisfies ActiveConnector;\n      yield* Ref.set(activeRef, connector);\n      yield* Effect.forkIn(observeConnectorOutput(connector), connectorScope);\n      yield* Effect.forkIn(superviseConnector(connector), connectorScope);\n      return {\n        status: \"running\",\n        providerKind: \"cloudflare_tunnel\",\n        pid: Number(child.pid),\n        ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),\n        ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),\n      } satisfies CloudManagedEndpointRuntimeStatus;\n    }\n\n    return {\n      status: \"failed\",\n      providerKind: \"cloudflare_tunnel\",\n      reason: \"Relay client did not start.\",\n      ...(config.tunnelId ? { tunnelId: config.tunnelId } : {}),\n      ...(config.tunnelName ? { tunnelName: config.tunnelName } : {}),\n    } satisfies CloudManagedEndpointRuntimeStatus;\n  });\n\n  const applyConfig = Effect.fn(\"CloudManagedEndpointRuntime.applyConfig\")(\n    (config: RelayManagedEndpointRuntimeConfig | null) =>\n      reconcileSemaphore.withPermits(1)(\n        Ref.set(desiredConfigRef, config).pipe(Effect.andThen(reconcileConfig(config))),\n      ),\n  );\n\n  const runtime = CloudManagedEndpointRuntime.of({\n    applyConfig,\n  });\n\n  const initialConfig = yield* readRuntimeConfig.pipe(\n    Effect.catch((cause) =>\n      Effect.logWarning(\"Failed to read managed endpoint runtime config\", { cause }).pipe(\n        Effect.as(null),\n      ),\n    ),\n  );\n  yield* runtime.applyConfig(initialConfig);\n  yield* Effect.addFinalizer(() => runtime.applyConfig(null));\n  return runtime;\n});\n\nexport const layer = Layer.effect(CloudManagedEndpointRuntime, make);\n","import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\n\nimport * as ServerSecretStore from \"../auth/ServerSecretStore.ts\";\nimport {\n  CLOUD_ENDPOINT_RUNTIME_CONFIG,\n  CLOUD_LINKED_USER_ID,\n  CLOUD_MINT_PUBLIC_KEY,\n  PUBLISH_AGENT_ACTIVITY_SECRET,\n  RELAY_ENVIRONMENT_CREDENTIAL_SECRET,\n  RELAY_ISSUER_SECRET,\n  RELAY_URL_SECRET,\n} from \"./config.ts\";\n\nexport const CLOUD_CLI_DESIRED_LINK_SECRET = \"cloud-cli-desired-link\";\n\n// \"managed\" provisions a Cloudflare tunnel (default, legacy value \"true\").\n// \"publish_only\" links the environment to the relay purely to publish agent\n// activity — no tunnel, no relay-advertised endpoint — so activity can flow to\n// mobile clients even when they reach the environment out of band (Tailscale,\n// direct pairing) without T3 Connect.\nexport type CliDesiredLinkMode = \"managed\" | \"publish_only\";\n\nconst MANAGED_BYTES = new TextEncoder().encode(\"managed\");\nconst PUBLISH_ONLY_BYTES = new TextEncoder().encode(\"publish_only\");\n\nexport const readCliDesiredCloudLink = Effect.gen(function* () {\n  const secrets = yield* ServerSecretStore.ServerSecretStore;\n  return Option.isSome(yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET));\n});\n\nexport const readCliDesiredLinkMode = Effect.gen(function* () {\n  const secrets = yield* ServerSecretStore.ServerSecretStore;\n  const value = yield* secrets.get(CLOUD_CLI_DESIRED_LINK_SECRET);\n  if (Option.isNone(value)) {\n    return \"managed\" as CliDesiredLinkMode;\n  }\n  // Legacy links stored the literal \"true\" and are always managed.\n  return new TextDecoder().decode(value.value) === \"publish_only\"\n    ? (\"publish_only\" as CliDesiredLinkMode)\n    : (\"managed\" as CliDesiredLinkMode);\n});\n\nexport const setCliDesiredCloudLink = Effect.fn(\"cloud.cli_state.set_desired\")(function* (\n  desired: boolean,\n  mode: CliDesiredLinkMode = \"managed\",\n) {\n  const secrets = yield* ServerSecretStore.ServerSecretStore;\n  if (desired) {\n    yield* secrets.set(\n      CLOUD_CLI_DESIRED_LINK_SECRET,\n      mode === \"publish_only\" ? PUBLISH_ONLY_BYTES : MANAGED_BYTES,\n    );\n  } else {\n    yield* secrets.remove(CLOUD_CLI_DESIRED_LINK_SECRET);\n  }\n});\n\nexport const clearPersistedCloudLink = Effect.gen(function* () {\n  const secrets = yield* ServerSecretStore.ServerSecretStore;\n  yield* Effect.all(\n    [\n      secrets.remove(CLOUD_CLI_DESIRED_LINK_SECRET),\n      secrets.remove(CLOUD_LINKED_USER_ID),\n      secrets.remove(RELAY_URL_SECRET),\n      secrets.remove(RELAY_ISSUER_SECRET),\n      secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),\n      secrets.remove(CLOUD_MINT_PUBLIC_KEY),\n      secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG),\n      secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET),\n    ],\n    { concurrency: \"unbounded\" },\n  );\n});\n","export type LoopbackAuthorizationStage = \"dev\" | \"nightly\" | \"latest\";\n\ndeclare const __SYNAPTIC_BUILD_CHANNEL__: \"nightly\" | \"latest\" | undefined;\n\nexport function resolveLoopbackAuthorizationStage(): LoopbackAuthorizationStage {\n  return typeof __SYNAPTIC_BUILD_CHANNEL__ === \"undefined\" ? \"dev\" : __SYNAPTIC_BUILD_CHANNEL__;\n}\n\nconst stageBrands = {\n  dev: \"Synaptic Code (Dev)\",\n  nightly: \"Synaptic Code (Nightly)\",\n  latest: \"Synaptic Code\",\n} as const satisfies Record<LoopbackAuthorizationStage, string>;\n\nexport function renderLoopbackAuthorizationCompleteHtml(\n  stage: LoopbackAuthorizationStage = resolveLoopbackAuthorizationStage(),\n): string {\n  const stageBrand = stageBrands[stage];\n\n  return `<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"color-scheme\" content=\"light dark\" />\n    <title>T3 Connect authorization complete</title>\n    <style>\n      :root {\n        color-scheme: light dark;\n        font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n        background: #f6f7f9;\n        color: #17191f;\n      }\n      * { box-sizing: border-box; }\n      body {\n        min-height: 100vh;\n        margin: 0;\n        display: grid;\n        place-items: center;\n        padding: 32px 16px;\n        background:\n          radial-gradient(48rem 22rem at 50% -8rem, rgba(47, 119, 235, 0.15), transparent),\n          #f6f7f9;\n      }\n      main {\n        width: min(100%, 576px);\n        overflow: hidden;\n        border: 1px solid rgba(23, 25, 31, 0.1);\n        border-radius: 20px;\n        background: rgba(255, 255, 255, 0.94);\n        box-shadow: 0 24px 64px rgba(16, 24, 40, 0.16);\n      }\n      .stage {\n        position: relative;\n        height: 96px;\n        overflow: hidden;\n        padding: 22px 24px;\n        color: white;\n      }\n      .stage-latest {\n        background:\n          radial-gradient(circle at 76% 18%, rgba(136, 204, 255, 0.52), transparent 38%),\n          linear-gradient(135deg, #2468df, #172f82);\n      }\n      .stage-dev {\n        background: linear-gradient(145deg, #5ab8fa 0%, #347ff8 46%, #1939bd 100%);\n      }\n      .stage-dev::before {\n        content: \"\";\n        position: absolute;\n        inset: 0;\n        opacity: 0.42;\n        background-image:\n          linear-gradient(rgba(234, 246, 255, 0.25) 1px, transparent 1px),\n          linear-gradient(90deg, rgba(234, 246, 255, 0.25) 1px, transparent 1px),\n          linear-gradient(rgba(234, 246, 255, 0.12) 1px, transparent 1px),\n          linear-gradient(90deg, rgba(234, 246, 255, 0.12) 1px, transparent 1px);\n        background-size: 32px 32px, 32px 32px, 8px 8px, 8px 8px;\n      }\n      .stage-nightly {\n        background:\n          radial-gradient(22rem 8rem at 78% 18%, rgba(81, 101, 216, 0.42), transparent 58%),\n          linear-gradient(145deg, #07152f 0%, #151443 52%, #32155b 100%);\n      }\n      .stage-nightly::before {\n        content: \"\";\n        position: absolute;\n        inset: 0;\n        opacity: 0.78;\n        background-image:\n          radial-gradient(circle at 12px 12px, rgba(228, 234, 255, 0.9) 0 1px, transparent 1.5px),\n          radial-gradient(circle at 38px 28px, rgba(228, 234, 255, 0.58) 0 0.8px, transparent 1.3px),\n          radial-gradient(circle at 58px 9px, rgba(200, 215, 255, 0.72) 0 0.9px, transparent 1.4px);\n        background-size: 72px 48px, 96px 64px, 128px 56px;\n      }\n      .stage::after {\n        content: \"\";\n        position: absolute;\n        inset: 0;\n        background:\n          radial-gradient(circle at 78% 20%, rgba(210, 255, 255, 0.36), transparent 34%),\n          linear-gradient(to bottom, transparent 24%, rgba(8, 28, 89, 0.38));\n      }\n      .stage-content {\n        position: relative;\n        z-index: 1;\n        height: 100%;\n        display: flex;\n        align-items: center;\n        justify-content: space-between;\n      }\n      .brand {\n        margin: 0;\n        font-size: 10px;\n        font-weight: 700;\n        letter-spacing: 0.2em;\n        text-transform: uppercase;\n      }\n      .brand { color: rgba(255, 255, 255, 0.82); }\n      .content { padding: 30px 32px 34px; }\n      .eyebrow {\n        margin: 0 0 8px;\n        color: #2866cc;\n        font-size: 10px;\n        font-weight: 700;\n        letter-spacing: 0.18em;\n        text-transform: uppercase;\n      }\n      h1 { margin: 0; font-size: clamp(26px, 5vw, 34px); line-height: 1.12; letter-spacing: -0.035em; }\n      .description { margin: 12px 0 0; color: #646975; font-size: 15px; line-height: 1.6; }\n      @media (prefers-color-scheme: dark) {\n        :root { background: #101115; color: #f1f3f7; }\n        body { background: radial-gradient(48rem 22rem at 50% -8rem, rgba(55, 102, 210, 0.2), transparent), #101115; }\n        main { border-color: rgba(255, 255, 255, 0.1); background: rgba(25, 27, 33, 0.96); }\n        .eyebrow { color: #77a8ff; }\n        .description { color: #a8adb8; }\n      }\n    </style>\n  </head>\n  <body>\n    <main>\n      <header class=\"stage stage-${stage}\" data-stage=\"${stage}\">\n        <div class=\"stage-content\">\n          <p class=\"brand\">${stageBrand}</p>\n        </div>\n      </header>\n      <section class=\"content\">\n        <p class=\"eyebrow\">Browser authorization complete</p>\n        <h1>You're connected</h1>\n        <p class=\"description\">Return to your terminal to finish setting up T3 Connect. You can close this window.</p>\n      </section>\n    </main>\n  </body>\n</html>`;\n}\n","// @effect-diagnostics nodeBuiltinImport:off - The CLI loopback OAuth callback is a Node HTTP boundary.\nimport * as NodeHttp from \"node:http\";\n\nimport * as NodeHttpServer from \"@effect/platform-node/NodeHttpServer\";\nimport * as Clock from \"effect/Clock\";\nimport * as Cause from \"effect/Cause\";\nimport * as Console from \"effect/Console\";\nimport * as Context from \"effect/Context\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Encoding from \"effect/Encoding\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Queue from \"effect/Queue\";\nimport * as Schema from \"effect/Schema\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Terminal from \"effect/Terminal\";\nimport * as HttpClient from \"effect/unstable/http/HttpClient\";\nimport * as HttpClientRequest from \"effect/unstable/http/HttpClientRequest\";\nimport * as HttpClientResponse from \"effect/unstable/http/HttpClientResponse\";\nimport * as HttpRouter from \"effect/unstable/http/HttpRouter\";\nimport * as HttpServerRequest from \"effect/unstable/http/HttpServerRequest\";\nimport * as HttpServerResponse from \"effect/unstable/http/HttpServerResponse\";\n\nimport {\n  buildConnectAuthorizeRequestUrl,\n  buildConnectClerkAuthorizeUrl,\n  checkConnectAuthCode,\n  connectCallbackUrl,\n} from \"@t3tools/shared/connectAuth\";\n\nimport * as ServerSecretStore from \"../auth/ServerSecretStore.ts\";\nimport * as ExternalLauncher from \"../process/externalLauncher.ts\";\nimport {\n  cloudCliOAuthConfig,\n  hostedAppUrlConfig,\n  type CloudCliOAuthConfig,\n} from \"./publicConfig.ts\";\nimport { renderLoopbackAuthorizationCompleteHtml } from \"./cliAuthHtml.ts\";\n\nconst CLOUD_CLI_OAUTH_TOKEN_SECRET = \"cloud-cli-oauth-token\";\nconst CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT = Duration.minutes(10);\nconst CLOUD_CLI_OAUTH_REFRESH_EARLY_MS = Duration.toMillis(Duration.minutes(5));\nconst boldTerminalText = (value: string): string => `\\u001b[1m${value}\\u001b[22m`;\n\nexport function formatLoopbackAuthorizationPrompt(authorizationUrl: string): string {\n  return [\n    \"Open this URL to authorize T3 Connect:\",\n    `  ${authorizationUrl}`,\n    \"\",\n    `Press ${boldTerminalText(\"Enter\")} to open it in your browser.`,\n    `No browser on this device? Press ${boldTerminalText(\"H\")} to switch to headless mode.`,\n  ].join(\"\\n\");\n}\n\nexport type LoopbackAuthorizationResult =\n  | { readonly _tag: \"AuthorizationCode\"; readonly code: string }\n  | { readonly _tag: \"HeadlessRequested\" };\n\nconst readLoopbackAuthorizationAction = Effect.fn(\n  \"cloud.cli_token.read_loopback_authorization_action\",\n)(function* (input: Queue.Dequeue<Terminal.UserInput, Cause.Done>) {\n  while (true) {\n    const event = yield* Queue.take(input).pipe(Effect.mapError(() => new Terminal.QuitError({})));\n    const keyName = event.key.name.toLowerCase();\n    if (!event.key.ctrl && !event.key.meta && keyName === \"h\") {\n      return \"headless\" as const;\n    }\n    if (keyName === \"enter\" || keyName === \"return\") {\n      return \"open-browser\" as const;\n    }\n  }\n});\n\nexport const waitForLoopbackAuthorization = Effect.fn(\n  \"cloud.cli_token.wait_for_loopback_authorization\",\n)(function* <E, R>(input: {\n  readonly authorizationUrl: string;\n  readonly callback: Effect.Effect<string, E, R>;\n  readonly terminal: Terminal.Terminal;\n  readonly launchBrowser: (\n    url: string,\n  ) => Effect.Effect<void, ExternalLauncher.ExternalLauncherError>;\n}) {\n  return yield* Effect.scoped(\n    Effect.gen(function* () {\n      const terminalInput = yield* input.terminal.readInput;\n      while (true) {\n        const result = yield* Effect.raceFirst(\n          input.callback.pipe(\n            Effect.map(\n              (code): LoopbackAuthorizationResult => ({ _tag: \"AuthorizationCode\", code }),\n            ),\n          ),\n          readLoopbackAuthorizationAction(terminalInput),\n        );\n        if (typeof result !== \"string\") {\n          return result;\n        }\n        if (result === \"headless\") {\n          return { _tag: \"HeadlessRequested\" } as const;\n        }\n        yield* input\n          .launchBrowser(input.authorizationUrl)\n          .pipe(\n            Effect.catch(() =>\n              Console.warn(\n                `Could not open a browser on this device. Open the URL above manually, or press ${boldTerminalText(\"H\")} to switch to headless mode.`,\n              ),\n            ),\n          );\n      }\n    }),\n  );\n});\n\nconst PersistedToken = Schema.Struct({\n  accessToken: Schema.String,\n  refreshToken: Schema.String,\n  expiresAtEpochMs: Schema.Number,\n  identity: Schema.optional(Schema.String),\n});\nexport type PersistedToken = typeof PersistedToken.Type;\n\nconst PersistedTokenJson = Schema.fromJsonString(PersistedToken);\nconst decodePersistedToken = Schema.decodeUnknownEffect(PersistedTokenJson);\nconst encodePersistedToken = Schema.encodeEffect(PersistedTokenJson);\n\nconst OAuthTokenResponse = Schema.Struct({\n  access_token: Schema.String,\n  refresh_token: Schema.optional(Schema.String),\n  id_token: Schema.optional(Schema.String),\n  expires_in: Schema.Number,\n  token_type: Schema.String,\n});\n\nconst OidcIdentityClaimsJson = Schema.fromJsonString(\n  Schema.Struct({\n    email: Schema.optional(Schema.String),\n    preferred_username: Schema.optional(Schema.String),\n    sub: Schema.optional(Schema.String),\n  }),\n);\nconst decodeOidcIdentityClaimsJson = Schema.decodeUnknownOption(OidcIdentityClaimsJson);\n\n/**\n * Best-effort read of the `email` (or fallback) claim from an OIDC id_token.\n * Only used to show the operator which account they linked, so a malformed\n * token degrades to \"no identity\" rather than an error.\n */\nfunction idTokenIdentity(idToken: string | undefined): string | null {\n  if (!idToken) return null;\n  const payload = idToken.split(\".\")[1];\n  if (!payload) return null;\n  const decoded = Encoding.decodeBase64UrlString(payload);\n  if (decoded._tag !== \"Success\") return null;\n  const claims = decodeOidcIdentityClaimsJson(decoded.success);\n  if (Option.isNone(claims)) return null;\n  for (const value of [claims.value.email, claims.value.preferred_username, claims.value.sub]) {\n    if (typeof value === \"string\" && value.length > 0) return value;\n  }\n  return null;\n}\n\nexport class CloudCliCredentialRemovalError extends Schema.TaggedErrorClass<CloudCliCredentialRemovalError>()(\n  \"CloudCliCredentialRemovalError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Could not remove the stored T3 Connect CLI credential.\";\n  }\n}\n\nexport class CloudCliCredentialRefreshError extends Schema.TaggedErrorClass<CloudCliCredentialRefreshError>()(\n  \"CloudCliCredentialRefreshError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Could not refresh the T3 Connect CLI credential.\";\n  }\n}\n\nexport class CloudCliCredentialReadError extends Schema.TaggedErrorClass<CloudCliCredentialReadError>()(\n  \"CloudCliCredentialReadError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Could not read the stored T3 Connect CLI credential.\";\n  }\n}\n\nexport class CloudCliAuthorizationError extends Schema.TaggedErrorClass<CloudCliAuthorizationError>()(\n  \"CloudCliAuthorizationError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Could not authorize the T3 Connect CLI.\";\n  }\n}\n\nexport class CloudCliAuthorizationTimeoutError extends Schema.TaggedErrorClass<CloudCliAuthorizationTimeoutError>()(\n  \"CloudCliAuthorizationTimeoutError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Timed out waiting for T3 Connect authorization.\";\n  }\n}\n\nexport const CloudCliTokenManagerError = Schema.Union([\n  CloudCliCredentialRemovalError,\n  CloudCliCredentialRefreshError,\n  CloudCliCredentialReadError,\n  CloudCliAuthorizationError,\n  CloudCliAuthorizationTimeoutError,\n]);\nexport type CloudCliTokenManagerError = typeof CloudCliTokenManagerError.Type;\n\nexport class CloudCliTokenManager extends Context.Service<\n  CloudCliTokenManager,\n  {\n    readonly get: Effect.Effect<\n      | { readonly _tag: \"Authorized\"; readonly token: PersistedToken }\n      | { readonly _tag: \"HeadlessRequested\" },\n      CloudCliTokenManagerError | Terminal.QuitError\n    >;\n    readonly getExisting: Effect.Effect<Option.Option<PersistedToken>, CloudCliTokenManagerError>;\n    readonly hasCredential: Effect.Effect<boolean, CloudCliTokenManagerError>;\n    readonly store: (token: PersistedToken) => Effect.Effect<void, CloudCliTokenManagerError>;\n    readonly clear: Effect.Effect<void, CloudCliTokenManagerError>;\n  }\n>()(\"t3/cloud/CliTokenManager/CloudCliTokenManager\") {}\n\nfunction stringToBytes(value: string): Uint8Array {\n  return new TextEncoder().encode(value);\n}\n\nfunction bytesToString(value: Uint8Array): string {\n  return new TextDecoder().decode(value);\n}\n\nconst exchangeToken = Effect.fn(\"cloud.cli_token.exchange\")(function* (\n  metadata: Pick<CloudCliOAuthConfig, \"tokenEndpoint\">,\n  params: Record<string, string>,\n) {\n  const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);\n  const response = yield* HttpClientRequest.post(metadata.tokenEndpoint).pipe(\n    HttpClientRequest.bodyUrlParams(params),\n    httpClient.execute,\n    Effect.flatMap(HttpClientResponse.schemaBodyJson(OAuthTokenResponse)),\n  );\n  const now = yield* Clock.currentTimeMillis;\n  const identity = idTokenIdentity(response.id_token);\n  return {\n    token: {\n      accessToken: response.access_token,\n      refreshToken: response.refresh_token ?? params.refresh_token ?? \"\",\n      expiresAtEpochMs: now + response.expires_in * 1_000,\n      ...(identity === null ? {} : { identity }),\n    } satisfies PersistedToken,\n    identity,\n  };\n});\n\nconst makePkceRequest = Effect.gen(function* () {\n  const crypto = yield* Crypto.Crypto;\n  const verifier = Encoding.encodeBase64Url(yield* crypto.randomBytes(32));\n  const challenge = Encoding.encodeBase64Url(\n    yield* crypto.digest(\"SHA-256\", new TextEncoder().encode(verifier)),\n  );\n  const state = Encoding.encodeBase64Url(yield* crypto.randomBytes(16));\n  return { verifier, challenge, state };\n});\n\nexport interface OutOfBandOAuthPromptInput {\n  readonly authorizeUrl: string;\n  readonly validate: (value: string) => Effect.Effect<string, string>;\n}\n\n/**\n * Out-of-band OAuth for machines without a local browser (SSH). The user\n * opens the hosted /connect URL elsewhere, signs in, and enters the displayed\n * code in this terminal. The PKCE verifier never leaves this process, so the\n * authorization code is useless to an observer, and the state bundled into\n * the blob preserves the loopback flow's CSRF check.\n */\nexport const outOfBandOAuthLogin = Effect.fn(\"cloud.cli_token.out_of_band_oauth_login\")(function* <\n  E,\n  R,\n>(promptForCode: (input: OutOfBandOAuthPromptInput) => Effect.Effect<string, E, R>) {\n  const metadata = yield* cloudCliOAuthConfig;\n  const hostedAppUrl = yield* hostedAppUrlConfig;\n  const { verifier, challenge, state } = yield* makePkceRequest;\n\n  const authorizationCode = yield* promptForCode({\n    authorizeUrl: buildConnectAuthorizeRequestUrl({ hostedAppUrl, state, challenge }),\n    validate: (value) => {\n      const checked = checkConnectAuthCode(value, state);\n      return typeof checked === \"string\" ? Effect.fail(checked) : Effect.succeed(value);\n    },\n  }).pipe(\n    // Clerk authorization codes expire on this horizon anyway; matching the\n    // loopback flow's timeout turns an abandoned prompt into a clear error.\n    Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),\n    Effect.catchTag(\"TimeoutError\", (cause) =>\n      Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),\n    ),\n  );\n  // promptForCode is caller-supplied, so re-check the returned value rather\n  // than trusting that the prompt ran validate.\n  const authCode = checkConnectAuthCode(authorizationCode, state);\n  if (typeof authCode === \"string\") {\n    return yield* new CloudCliAuthorizationError({ cause: authCode });\n  }\n\n  return yield* exchangeToken(metadata, {\n    grant_type: \"authorization_code\",\n    code: authCode.code,\n    redirect_uri: connectCallbackUrl(hostedAppUrl),\n    client_id: metadata.clientId,\n    code_verifier: verifier,\n  });\n});\n\nexport const make = Effect.gen(function* () {\n  // Capture exactly the services the login/refresh flows need at build time\n  // (matching the behavior before the out-of-band flow captured the instances), not\n  // the whole ambient context.\n  const crypto = yield* Crypto.Crypto;\n  const httpClient = yield* HttpClient.HttpClient;\n  const services = Context.make(Crypto.Crypto, crypto).pipe(\n    Context.add(HttpClient.HttpClient, httpClient),\n  );\n  const secrets = yield* ServerSecretStore.ServerSecretStore;\n  const terminal = yield* Terminal.Terminal;\n  const externalLauncher = yield* ExternalLauncher.ExternalLauncher;\n  const semaphore = yield* Semaphore.make(1);\n  const persist = Effect.fn(\"cloud.cli_token.persist\")(function* (token: PersistedToken) {\n    const encoded = yield* encodePersistedToken(token);\n    yield* secrets.set(CLOUD_CLI_OAUTH_TOKEN_SECRET, stringToBytes(encoded));\n    return token;\n  });\n\n  const clear = secrets\n    .remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)\n    .pipe(Effect.mapError((cause) => new CloudCliCredentialRemovalError({ cause })));\n\n  const read = Effect.fn(\"cloud.cli_token.read\")(function* () {\n    const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);\n    if (Option.isNone(encoded)) return Option.none<PersistedToken>();\n    return Option.some(yield* decodePersistedToken(bytesToString(encoded.value)));\n  });\n\n  const refresh = Effect.fn(\"cloud.cli_token.refresh\")(function* (token: PersistedToken) {\n    const metadata = yield* cloudCliOAuthConfig;\n    const { token: refreshed } = yield* exchangeToken(metadata, {\n      grant_type: \"refresh_token\",\n      refresh_token: token.refreshToken,\n      client_id: metadata.clientId,\n    });\n    return refreshed.identity === undefined && token.identity !== undefined\n      ? { ...refreshed, identity: token.identity }\n      : refreshed;\n  });\n\n  const login = Effect.fn(\"cloud.cli_token.login\")(function* () {\n    const metadata = yield* cloudCliOAuthConfig;\n    const { verifier, challenge, state } = yield* makePkceRequest;\n    const callback = yield* Deferred.make<string>();\n    const callbackRoute = HttpRouter.add(\n      \"GET\",\n      \"/callback\",\n      Effect.gen(function* () {\n        const request = yield* HttpServerRequest.HttpServerRequest;\n        const url = new URL(request.originalUrl, metadata.redirectUri);\n        const code = url.searchParams.get(\"code\");\n        if (url.searchParams.get(\"state\") !== state || !code) {\n          return HttpServerResponse.text(\"Invalid T3 Connect authorization callback.\", {\n            status: 400,\n          });\n        }\n        yield* Deferred.succeed(callback, code);\n        return HttpServerResponse.html(renderLoopbackAuthorizationCompleteHtml());\n      }),\n    );\n    yield* HttpRouter.serve(callbackRoute, {\n      disableListenLog: true,\n      disableLogger: true,\n    }).pipe(\n      Layer.provide(\n        NodeHttpServer.layer(NodeHttp.createServer, {\n          host: \"127.0.0.1\",\n          port: 34338,\n          disablePreemptiveShutdown: true,\n        }),\n      ),\n      Layer.build,\n    );\n    const authorizationUrl = buildConnectClerkAuthorizeUrl({\n      authorizationEndpoint: metadata.authorizationEndpoint,\n      clientId: metadata.clientId,\n      redirectUri: metadata.redirectUri,\n      scopes: metadata.scopes,\n      state,\n      challenge,\n    });\n    yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));\n    const authorization = yield* waitForLoopbackAuthorization({\n      authorizationUrl,\n      callback: Deferred.await(callback).pipe(\n        Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),\n        Effect.catchTag(\"TimeoutError\", (cause) =>\n          Effect.fail(new CloudCliAuthorizationTimeoutError({ cause })),\n        ),\n      ),\n      terminal,\n      launchBrowser: externalLauncher.launchBrowser,\n    });\n    if (authorization._tag === \"HeadlessRequested\") {\n      return authorization;\n    }\n    const { token } = yield* exchangeToken(metadata, {\n      grant_type: \"authorization_code\",\n      code: authorization.code,\n      redirect_uri: metadata.redirectUri,\n      client_id: metadata.clientId,\n      code_verifier: verifier,\n    });\n    return { _tag: \"Authorized\", token } as const;\n  });\n\n  const getExistingNoLock = Effect.fn(\"cloud.cli_token.get_existing_no_lock\")(function* () {\n    const token = yield* read();\n    if (Option.isNone(token)) return token;\n    const now = yield* Clock.currentTimeMillis;\n    if (token.value.expiresAtEpochMs - CLOUD_CLI_OAUTH_REFRESH_EARLY_MS > now) {\n      return token;\n    }\n    return Option.some(yield* refresh(token.value).pipe(Effect.flatMap(persist)));\n  });\n\n  const getExisting = semaphore.withPermits(1)(\n    getExistingNoLock().pipe(\n      Effect.mapError((cause) => new CloudCliCredentialRefreshError({ cause })),\n      Effect.provide(services),\n    ),\n  );\n  const hasCredential = semaphore.withPermits(1)(\n    read().pipe(\n      Effect.map(Option.isSome),\n      Effect.mapError((cause) => new CloudCliCredentialReadError({ cause })),\n    ),\n  );\n  const get = semaphore.withPermits(1)(\n    Effect.gen(function* () {\n      // A stored credential that can't be read or refreshed (corrupt, revoked,\n      // expired grant) must fall through to a fresh login rather than dead-end\n      // the command — authorizeCli applies the same fallback to out-of-band\n      // authorization.\n      const token = yield* getExistingNoLock().pipe(\n        Effect.orElseSucceed(() => Option.none<PersistedToken>()),\n      );\n      if (Option.isSome(token)) {\n        return { _tag: \"Authorized\", token: token.value } as const;\n      }\n      const authorization = yield* Effect.scoped(login());\n      return authorization._tag === \"Authorized\"\n        ? ({ _tag: \"Authorized\", token: yield* persist(authorization.token) } as const)\n        : authorization;\n    }).pipe(\n      Effect.mapError((cause) =>\n        Terminal.isQuitError(cause) ? cause : new CloudCliAuthorizationError({ cause }),\n      ),\n      Effect.provide(services),\n    ),\n  );\n  const store = Effect.fn(\"cloud.cli_token.store\")(function* (token: PersistedToken) {\n    yield* semaphore.withPermits(1)(\n      persist(token).pipe(\n        Effect.asVoid,\n        Effect.mapError((cause) => new CloudCliAuthorizationError({ cause })),\n      ),\n    );\n  });\n\n  return CloudCliTokenManager.of({ get, getExisting, hasCredential, store, clear });\n});\n\nexport const layer = Layer.effect(CloudCliTokenManager, make);\n","import * as NodeCrypto from \"node:crypto\";\nimport {\n  AuthRelayReadScope,\n  AuthRelayWriteScope,\n  AuthStandardClientScopes,\n  EnvironmentCloudEndpointUnavailableError,\n  EnvironmentCloudLinkStateResult,\n  EnvironmentCloudRelayConfigResult,\n  EnvironmentHttpApi,\n  EnvironmentHttpBadRequestError,\n  EnvironmentHttpConflictError,\n  EnvironmentHttpInternalServerError,\n  EnvironmentHttpUnauthorizedError,\n} from \"@t3tools/contracts\";\nimport {\n  RelayCloudEnvironmentHealthProofPayload,\n  RelayCloudEnvironmentHealthRequest,\n  RelayCloudMintCredentialProofPayload,\n  RelayCloudMintCredentialRequest,\n  RelayEnvironmentHealthResponseProofPayload,\n  type RelayEnvironmentHealthResponse as RelayEnvironmentHealthResponseShape,\n  RelayEnvironmentConfigRequest,\n  RelayEnvironmentLinkChallengeResponse,\n  RelayEnvironmentLinkResponse,\n  RelayEnvironmentMintResponseProofPayload,\n  type RelayEnvironmentMintResponse as RelayEnvironmentMintResponseShape,\n  RelayEnvironmentLinkProof,\n  RelayEnvironmentLinkProofPayload,\n  RelayLinkProofRequest,\n  RelayManagedEndpointOrigin,\n  RelayOkResponse,\n} from \"@t3tools/contracts/relay\";\nimport { withRelayClientTracing } from \"@t3tools/shared/relayTracing\";\nimport {\n  normalizeRelayIssuer,\n  RELAY_HEALTH_REQUEST_TYP,\n  RELAY_HEALTH_RESPONSE_TYP,\n  RELAY_LINK_PROOF_TYP,\n  RELAY_MINT_REQUEST_TYP,\n  RELAY_MINT_RESPONSE_TYP,\n  signRelayJwt,\n  verifyRelayJwt,\n} from \"@t3tools/shared/relayJwt\";\nimport { isSecureRelayUrl } from \"@t3tools/shared/relayUrl\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as HttpEffect from \"effect/unstable/http/HttpEffect\";\nimport { HttpServerRequest, HttpServerResponse } from \"effect/unstable/http\";\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/unstable/http\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\n\nimport * as EnvironmentAuth from \"../auth/EnvironmentAuth.ts\";\nimport * as ServerSecretStore from \"../auth/ServerSecretStore.ts\";\nimport { requireEnvironmentScope } from \"../auth/http.ts\";\nimport * as ServerConfig from \"../config.ts\";\nimport * as ServerEnvironment from \"../environment/ServerEnvironment.ts\";\nimport * as ManagedEndpointRuntime from \"./ManagedEndpointRuntime.ts\";\nimport {\n  SERVICE_STATE_FILE,\n  SERVICE_STOP_MARKER_FILE,\n  serviceStateHasPendingUpdate,\n} from \"./serviceProtocol.ts\";\nimport {\n  CLOUD_ENDPOINT_RUNTIME_CONFIG,\n  CLOUD_LINKED_USER_ID,\n  CLOUD_MINT_PUBLIC_KEY,\n  encodeEndpointRuntimeConfigJson,\n  PUBLISH_AGENT_ACTIVITY_SECRET,\n  RELAY_ENVIRONMENT_CREDENTIAL_SECRET,\n  RELAY_ISSUER_SECRET,\n  RELAY_URL_SECRET,\n} from \"./config.ts\";\nimport { relayUrlConfig } from \"./publicConfig.ts\";\nimport {\n  readCliDesiredCloudLink,\n  readCliDesiredLinkMode,\n  setCliDesiredCloudLink,\n} from \"./CliState.ts\";\nimport * as CliTokenManager from \"./CliTokenManager.ts\";\nimport { getOrCreateEnvironmentKeyPairFromSecretStore } from \"./environmentKeys.ts\";\nimport { traceRelayRequest } from \"./traceRelayRequest.ts\";\n\nconst CLOUD_MINT_NONCE_PREFIX = \"cloud-mint-nonce-\";\nconst CLOUD_MINT_JTI_PREFIX = \"cloud-mint-jti-\";\nconst CLOUD_HEALTH_NONCE_PREFIX = \"cloud-health-nonce-\";\nconst CLOUD_HEALTH_JTI_PREFIX = \"cloud-health-jti-\";\nconst CLOUD_PROOF_MAX_LIFETIME_SECONDS = 5 * 60;\nconst CLOUD_PROOF_CLOCK_SKEW_SECONDS = 60;\nconst LOOPBACK_HOSTNAMES = new Set([\"127.0.0.1\", \"::1\", \"localhost\"]);\nconst CLOUD_CREDENTIAL_RESPONSE_HEADERS = {\n  \"cache-control\": \"no-store\",\n  pragma: \"no-cache\",\n} as const;\n\nconst appendCloudCredentialResponseHeaders = HttpEffect.appendPreResponseHandler(\n  (_request, response) =>\n    Effect.succeed(HttpServerResponse.setHeaders(response, CLOUD_CREDENTIAL_RESPONSE_HEADERS)),\n);\n\nconst failEnvironmentCloudInternalError =\n  (message: string) =>\n  (cause: unknown): Effect.Effect<never, EnvironmentHttpInternalServerError> =>\n    Effect.logError(message, { cause }).pipe(\n      Effect.flatMap(() => Effect.fail(new EnvironmentHttpInternalServerError({ message }))),\n    );\n\nconst failCloudCliTokenManagerError = (error: CliTokenManager.CloudCliTokenManagerError) =>\n  failEnvironmentCloudInternalError(error.message)(error);\n\nconst requireRelayUrl = relayUrlConfig.pipe(\n  Effect.mapError(\n    () =>\n      new EnvironmentHttpInternalServerError({\n        message: \"SYNAPTIC_RELAY_URL must be configured as a secure absolute HTTPS origin.\",\n      }),\n  ),\n);\n\nfunction bytesToString(bytes: Uint8Array): string {\n  return new TextDecoder().decode(bytes);\n}\n\nfunction stringToBytes(value: string): Uint8Array {\n  return new TextEncoder().encode(value);\n}\n\nexport function consumeCloudReplayGuards(input: {\n  readonly secrets: ServerSecretStore.ServerSecretStore[\"Service\"];\n  readonly names: ReadonlyArray<string>;\n  readonly value: Uint8Array;\n}) {\n  return Effect.all(\n    input.names.map((name) =>\n      input.secrets.create(name, input.value).pipe(\n        Effect.as(true),\n        Effect.catchIf(ServerSecretStore.isSecretStoreError, (error) =>\n          ServerSecretStore.isSecretAlreadyExistsError(error)\n            ? Effect.succeed(false)\n            : Effect.fail(error),\n        ),\n      ),\n    ),\n    { concurrency: input.names.length },\n  ).pipe(Effect.map((created) => created.every(Boolean)));\n}\n\nfunction normalizePemForSignedPayload(value: string): string {\n  return value.trim();\n}\n\nfunction normalizeHostname(hostname: string): string {\n  return hostname\n    .trim()\n    .toLowerCase()\n    .replace(/^\\[(.*)\\]$/, \"$1\");\n}\n\nfunction validateCloudMintPublicKey(\n  publicKey: string,\n): Effect.Effect<void, EnvironmentHttpBadRequestError> {\n  return Effect.try({\n    try: () => NodeCrypto.createPublicKey(publicKey.replace(/\\\\n/g, \"\\n\")),\n    catch: () =>\n      new EnvironmentHttpBadRequestError({\n        message: \"Cloud mint public key must be a valid Ed25519 public key.\",\n      }),\n  }).pipe(\n    Effect.flatMap((key) =>\n      key.asymmetricKeyType === \"ed25519\"\n        ? Effect.void\n        : Effect.fail(\n            new EnvironmentHttpBadRequestError({\n              message: \"Cloud mint public key must be a valid Ed25519 public key.\",\n            }),\n          ),\n    ),\n  );\n}\n\nfunction validateRelayConfigPayload(\n  payload: RelayEnvironmentConfigRequest,\n): Effect.Effect<void, EnvironmentHttpBadRequestError> {\n  if (!isSecureRelayUrl(payload.relayUrl)) {\n    return Effect.fail(\n      new EnvironmentHttpBadRequestError({\n        message: \"Relay URL must be a secure absolute HTTPS URL.\",\n      }),\n    );\n  }\n  if (payload.relayIssuer !== undefined && !isSecureRelayUrl(payload.relayIssuer)) {\n    return Effect.fail(\n      new EnvironmentHttpBadRequestError({\n        message: \"Relay issuer must be a secure absolute HTTPS URL.\",\n      }),\n    );\n  }\n  if (payload.environmentCredential.trim().length === 0) {\n    return Effect.fail(\n      new EnvironmentHttpBadRequestError({\n        message: \"Relay environment credential is required.\",\n      }),\n    );\n  }\n  if (payload.cloudUserId.trim().length === 0) {\n    return Effect.fail(\n      new EnvironmentHttpBadRequestError({\n        message: \"Cloud user id is required.\",\n      }),\n    );\n  }\n  return Effect.void;\n}\n\nfunction validateLinkedCloudUser(input: {\n  readonly secrets: ServerSecretStore.ServerSecretStore[\"Service\"];\n  readonly cloudUserId: string;\n}): Effect.Effect<void, EnvironmentAuth.ServerAuthInternalError | EnvironmentHttpConflictError> {\n  return input.secrets.get(CLOUD_LINKED_USER_ID).pipe(\n    Effect.mapError(\n      (cause) =>\n        new EnvironmentAuth.ServerAuthLinkedCloudAccountVerificationError({\n          cause,\n        }),\n    ),\n    Effect.flatMap((existing) => {\n      if (Option.isNone(existing)) {\n        return Effect.void;\n      }\n      const existingCloudUserId = bytesToString(existing.value);\n      return existingCloudUserId === input.cloudUserId\n        ? Effect.void\n        : Effect.fail(\n            new EnvironmentHttpConflictError({\n              message:\n                \"This environment is already linked to a different cloud account. Unlink it before switching accounts.\",\n            }),\n          );\n    }),\n  );\n}\n\nfunction readInstalledCloudUserId(\n  secrets: ServerSecretStore.ServerSecretStore[\"Service\"],\n): Effect.Effect<string, EnvironmentAuth.ServerAuthInternalError> {\n  return secrets.get(CLOUD_LINKED_USER_ID).pipe(\n    Effect.mapError(\n      (cause) =>\n        new EnvironmentAuth.ServerAuthLinkedCloudAccountReadError({\n          cause,\n        }),\n    ),\n    Effect.flatMap((bytes) =>\n      Option.isSome(bytes)\n        ? Effect.succeed(bytesToString(bytes.value))\n        : Effect.fail(new EnvironmentAuth.ServerAuthLinkedCloudAccountMissingError({})),\n    ),\n  );\n}\n\nfunction isLoopbackHostname(hostname: string): boolean {\n  return LOOPBACK_HOSTNAMES.has(normalizeHostname(hostname));\n}\n\nfunction firstForwardedHeaderValue(value: string | undefined): string | undefined {\n  const first = value?.split(\",\")[0]?.trim();\n  return first && first.length > 0 ? first : undefined;\n}\n\nfunction requestAbsoluteUrl(request: HttpServerRequest.HttpServerRequest): string | null {\n  try {\n    return new URL(request.originalUrl).href;\n  } catch {\n    const host = firstForwardedHeaderValue(request.headers.host) ?? \"127.0.0.1\";\n    try {\n      return new URL(request.originalUrl, `http://${host}`).href;\n    } catch {\n      return null;\n    }\n  }\n}\n\nfunction hasForwardedAuthorityHeaders(request: HttpServerRequest.HttpServerRequest): boolean {\n  return (\n    firstForwardedHeaderValue(request.headers[\"x-forwarded-host\"]) !== undefined ||\n    firstForwardedHeaderValue(request.headers[\"x-forwarded-proto\"]) !== undefined\n  );\n}\n\nfunction endpointRequestPort(url: URL): number {\n  return Number(url.port || (url.protocol === \"https:\" ? 443 : 80));\n}\n\nfunction isAllowedEndpointOrigin(input: {\n  readonly origin: RelayManagedEndpointOrigin;\n  readonly requestUrl: string;\n}): boolean {\n  if (!isLoopbackHostname(input.origin.localHttpHost)) {\n    return false;\n  }\n\n  const url = new URL(input.requestUrl);\n  if (!isLoopbackHostname(url.hostname)) {\n    return false;\n  }\n\n  return input.origin.localHttpPort === endpointRequestPort(url);\n}\n\n// A managed (Cloudflare tunnel) endpoint is provisioned by the relay and must\n// point at a loopback origin. A manual endpoint is reached out of band (e.g.\n// Tailscale) or not advertised at all for publish-only links, so it is not\n// tied to the managed-tunnel scope.\nexport function isSupportedLinkProviderKind(request: RelayLinkProofRequest): boolean {\n  return (\n    request.endpoint.providerKind === \"cloudflare_tunnel\" ||\n    request.endpoint.providerKind === \"manual\"\n  );\n}\n\nexport function linkProofScopes(\n  request: RelayLinkProofRequest,\n): RelayEnvironmentLinkProofPayload[\"scopes\"] {\n  return request.endpoint.providerKind === \"cloudflare_tunnel\"\n    ? [\"agent_activity_notifications\", \"managed_tunnels\"]\n    : [\"agent_activity_notifications\"];\n}\n\nfunction hasExactScope(input: {\n  readonly scopes: ReadonlyArray<string>;\n  readonly expected: string;\n}): boolean {\n  return input.scopes.length === 1 && input.scopes[0] === input.expected;\n}\n\nfunction hasBoundedCloudProofLifetime(input: {\n  readonly iat: number;\n  readonly exp: number;\n  readonly nowSeconds: number;\n}): boolean {\n  return (\n    input.exp > input.iat &&\n    input.exp - input.iat <= CLOUD_PROOF_MAX_LIFETIME_SECONDS &&\n    input.iat <= input.nowSeconds + CLOUD_PROOF_CLOCK_SKEW_SECONDS\n  );\n}\n\nconst decodeCloudHealthProof = Schema.decodeUnknownEffect(RelayCloudEnvironmentHealthProofPayload);\nconst decodeCloudMintProof = Schema.decodeUnknownEffect(RelayCloudMintCredentialProofPayload);\n\ninterface CloudHttpDependencies {\n  readonly secrets: ServerSecretStore.ServerSecretStore[\"Service\"];\n  readonly environment: ServerEnvironment.ServerEnvironment[\"Service\"];\n  readonly endpointRuntime: ManagedEndpointRuntime.CloudManagedEndpointRuntime[\"Service\"];\n  readonly environmentAuth: EnvironmentAuth.EnvironmentAuth[\"Service\"];\n  readonly cliTokenManager: CliTokenManager.CloudCliTokenManager[\"Service\"];\n  readonly httpClient: HttpClient.HttpClient;\n}\n\nconst cloudHttpDependencies = Effect.gen(function* () {\n  return {\n    secrets: yield* ServerSecretStore.ServerSecretStore,\n    environment: yield* ServerEnvironment.ServerEnvironment,\n    endpointRuntime: yield* ManagedEndpointRuntime.CloudManagedEndpointRuntime,\n    environmentAuth: yield* EnvironmentAuth.EnvironmentAuth,\n    cliTokenManager: yield* CliTokenManager.CloudCliTokenManager,\n    httpClient: yield* HttpClient.HttpClient,\n  } satisfies CloudHttpDependencies;\n});\n\nconst makeCloudLinkProof = Effect.fn(\"environment.cloud.makeLinkProof\")(function* (\n  dependencies: CloudHttpDependencies,\n  request: RelayLinkProofRequest,\n  requestUrl: string,\n) {\n  const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);\n  if (\n    !isSupportedLinkProviderKind(request) ||\n    !isAllowedEndpointOrigin({\n      origin: request.origin,\n      requestUrl,\n    })\n  ) {\n    return yield* new EnvironmentHttpBadRequestError({\n      message: \"Invalid managed endpoint origin.\",\n    });\n  }\n  const now = yield* DateTime.now;\n  const expiresAt = DateTime.add(now, { minutes: 5 });\n  const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);\n  const descriptor = yield* dependencies.environment.getDescriptor;\n  const payload = {\n    iss: `t3-env:${descriptor.environmentId}`,\n    aud: normalizeRelayIssuer(request.relayIssuer),\n    sub: descriptor.environmentId,\n    jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),\n    iat: nowSeconds,\n    exp: Math.floor(expiresAt.epochMilliseconds / 1_000),\n    challenge: request.challenge,\n    descriptor,\n    environmentId: descriptor.environmentId,\n    environmentPublicKey: normalizePemForSignedPayload(keyPair.publicKey),\n    endpoint: request.endpoint,\n    origin: request.origin,\n    scopes: linkProofScopes(request),\n  } satisfies RelayEnvironmentLinkProofPayload;\n  return yield* signRelayJwt({\n    privateKey: keyPair.privateKey,\n    typ: RELAY_LINK_PROOF_TYP,\n    payload,\n  }).pipe(\n    Effect.mapError(\n      (cause) =>\n        new EnvironmentAuth.ServerAuthCloudLinkJwtSigningError({\n          cause,\n        }),\n    ),\n  );\n});\n\nconst cloudLinkProofHandler = Effect.fn(\"environment.cloud.linkProof\")(\n  function* (dependencies: CloudHttpDependencies, request: RelayLinkProofRequest) {\n    yield* requireEnvironmentScope(AuthRelayWriteScope);\n    const httpRequest = yield* HttpServerRequest.HttpServerRequest;\n    const requestUrl = requestAbsoluteUrl(httpRequest);\n    if (requestUrl === null || hasForwardedAuthorityHeaders(httpRequest)) {\n      return yield* new EnvironmentHttpBadRequestError({\n        message: \"Invalid managed endpoint origin.\",\n      });\n    }\n    const proof = yield* makeCloudLinkProof(dependencies, request, requestUrl);\n    yield* appendCloudCredentialResponseHeaders;\n    return proof satisfies RelayEnvironmentLinkProof;\n  },\n  Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n    failEnvironmentCloudInternalError(error.message)(error),\n  ),\n  Effect.catchIf(\n    ServerSecretStore.isSecretStoreError,\n    failEnvironmentCloudInternalError(\"Could not generate environment link proof.\"),\n  ),\n  Effect.catchTag(\n    \"PlatformError\",\n    failEnvironmentCloudInternalError(\"Could not generate environment link proof.\"),\n  ),\n);\n\nconst applyCloudRelayConfig = Effect.fn(\"environment.cloud.applyRelayConfig\")(function* (\n  dependencies: CloudHttpDependencies,\n  payload: RelayEnvironmentConfigRequest,\n) {\n  yield* validateRelayConfigPayload(payload);\n  yield* validateLinkedCloudUser({\n    secrets: dependencies.secrets,\n    cloudUserId: payload.cloudUserId,\n  });\n  yield* validateCloudMintPublicKey(payload.cloudMintPublicKey);\n  const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(\n    payload.endpointRuntime,\n  );\n  const ok =\n    endpointRuntimeStatus.status === \"disabled\" || endpointRuntimeStatus.status === \"running\";\n  if (!ok) {\n    return yield* new EnvironmentCloudEndpointUnavailableError({\n      message: \"Managed endpoint runtime could not be started.\",\n      endpointRuntimeStatus,\n    });\n  }\n\n  yield* dependencies.secrets.set(RELAY_URL_SECRET, stringToBytes(payload.relayUrl));\n  yield* dependencies.secrets.set(\n    RELAY_ISSUER_SECRET,\n    stringToBytes(payload.relayIssuer ?? payload.relayUrl),\n  );\n  yield* dependencies.secrets.set(CLOUD_LINKED_USER_ID, stringToBytes(payload.cloudUserId));\n  yield* dependencies.secrets.set(\n    RELAY_ENVIRONMENT_CREDENTIAL_SECRET,\n    stringToBytes(payload.environmentCredential),\n  );\n  yield* dependencies.secrets.set(CLOUD_MINT_PUBLIC_KEY, stringToBytes(payload.cloudMintPublicKey));\n  if (payload.endpointRuntime) {\n    const endpointRuntimeJson = yield* encodeEndpointRuntimeConfigJson(payload.endpointRuntime);\n    yield* dependencies.secrets.set(\n      CLOUD_ENDPOINT_RUNTIME_CONFIG,\n      stringToBytes(endpointRuntimeJson),\n    );\n  } else {\n    yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);\n  }\n  return { ok, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;\n});\n\nconst cloudRelayConfigHandler = Effect.fn(\"environment.cloud.relayConfig\")(\n  function* (dependencies: CloudHttpDependencies, payload: RelayEnvironmentConfigRequest) {\n    yield* requireEnvironmentScope(AuthRelayWriteScope);\n    return yield* applyCloudRelayConfig(dependencies, payload);\n  },\n  Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n    failEnvironmentCloudInternalError(error.message)(error),\n  ),\n  Effect.catchIf(\n    ServerSecretStore.isSecretStoreError,\n    failEnvironmentCloudInternalError(\"Could not persist environment relay configuration.\"),\n  ),\n  Effect.catchTag(\n    \"SchemaError\",\n    failEnvironmentCloudInternalError(\"Could not persist environment relay configuration.\"),\n  ),\n);\n\nconst relayClientRequest = <A>(\n  dependencies: CloudHttpDependencies,\n  input: {\n    readonly url: string;\n    readonly token: string;\n    readonly payload: unknown;\n    readonly schema: Schema.Decoder<A>;\n  },\n) =>\n  HttpClientRequest.post(input.url).pipe(\n    HttpClientRequest.bearerToken(input.token),\n    HttpClientRequest.bodyJson(input.payload),\n    Effect.flatMap(dependencies.httpClient.execute),\n    Effect.flatMap(HttpClientResponse.filterStatusOk),\n    Effect.flatMap(HttpClientResponse.schemaBodyJson(input.schema)),\n    Effect.mapError(\n      (cause) =>\n        new EnvironmentHttpInternalServerError({\n          message: `T3 Connect relay request failed: ${String(cause)}`,\n        }),\n    ),\n    withRelayClientTracing,\n  );\n\nconst reconcileDesiredCloudLinkWith = Effect.fn(\"environment.cloud.reconcileDesiredLinkWith\")(\n  function* (dependencies: CloudHttpDependencies, localOrigin: string) {\n    const localUrl = yield* Effect.try({\n      try: () => new URL(localOrigin),\n      catch: () =>\n        new EnvironmentHttpBadRequestError({\n          message: \"Could not resolve local environment origin.\",\n        }),\n    });\n    if (localUrl.origin !== localOrigin) {\n      return yield* new EnvironmentHttpBadRequestError({\n        message: \"Could not resolve local environment origin.\",\n      });\n    }\n    const localWsOrigin = localOrigin.replace(/^http/u, \"ws\");\n    const token = yield* dependencies.cliTokenManager.getExisting.pipe(\n      Effect.flatMap(\n        Option.match({\n          onNone: () =>\n            Effect.fail(\n              new EnvironmentHttpUnauthorizedError({\n                message:\n                  \"This environment requires T3 Connect authorization, a hosted service this fork does not run.\",\n              }),\n            ),\n          onSome: Effect.succeed,\n        }),\n      ),\n    );\n    const mode = yield* readCliDesiredLinkMode;\n    const managedTunnelsEnabled = mode !== \"publish_only\";\n    const relayUrl = yield* requireRelayUrl;\n    const challenge = yield* relayClientRequest(dependencies, {\n      url: `${relayUrl}/v1/client/environment-link-challenges`,\n      token: token.accessToken,\n      payload: {\n        notificationsEnabled: true,\n        liveActivitiesEnabled: true,\n        managedTunnelsEnabled,\n      },\n      schema: RelayEnvironmentLinkChallengeResponse,\n    });\n    const proof = yield* makeCloudLinkProof(\n      dependencies,\n      {\n        challenge: challenge.challenge,\n        relayIssuer: relayUrl,\n        endpoint: {\n          httpBaseUrl: localOrigin,\n          wsBaseUrl: localWsOrigin,\n          providerKind: managedTunnelsEnabled ? \"cloudflare_tunnel\" : \"manual\",\n        },\n        origin: {\n          localHttpHost: localUrl.hostname,\n          localHttpPort: endpointRequestPort(localUrl),\n        },\n      },\n      localOrigin,\n    );\n    const link = yield* relayClientRequest(dependencies, {\n      url: `${relayUrl}/v1/client/environment-links`,\n      token: token.accessToken,\n      payload: {\n        proof,\n        notificationsEnabled: true,\n        liveActivitiesEnabled: true,\n        managedTunnelsEnabled,\n      },\n      schema: RelayEnvironmentLinkResponse,\n    });\n    yield* setCliDesiredCloudLink(true, mode);\n    return yield* applyCloudRelayConfig(dependencies, {\n      relayUrl,\n      relayIssuer: link.relayIssuer,\n      cloudUserId: link.cloudUserId,\n      environmentCredential: link.environmentCredential,\n      cloudMintPublicKey: link.cloudMintPublicKey,\n      endpointRuntime: link.endpointRuntime,\n    });\n  },\n  Effect.catchIf(\n    ServerSecretStore.isSecretStoreError,\n    failEnvironmentCloudInternalError(\"Could not persist desired T3 Connect link state.\"),\n  ),\n  Effect.catchTags({\n    CloudCliCredentialRemovalError: failCloudCliTokenManagerError,\n    CloudCliCredentialRefreshError: failCloudCliTokenManagerError,\n    CloudCliCredentialReadError: failCloudCliTokenManagerError,\n    CloudCliAuthorizationError: failCloudCliTokenManagerError,\n    CloudCliAuthorizationTimeoutError: failCloudCliTokenManagerError,\n  }),\n);\n\nexport const reconcileDesiredCloudLink = Effect.fn(\"environment.cloud.reconcileDesiredLink\")(\n  function* (localOrigin: string) {\n    return yield* reconcileDesiredCloudLinkWith(yield* cloudHttpDependencies, localOrigin);\n  },\n);\n\n// The launcher owns this durable state, so read it directly both when a trial\n// decides whether it owns pre-activation cleanup and while a server tears down.\nexport const pendingServiceUpdateExists = Effect.gen(function* () {\n  const config = yield* ServerConfig.ServerConfig;\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const runtimeDir = path.join(config.baseDir, \"runtime\");\n  const stateText = yield* fs\n    .readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))\n    .pipe(Effect.option);\n  return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);\n});\n\n// A pending update alone is not proof a replacement server is coming: an\n// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during\n// the pending window also tears this server down. The launcher marks that case\n// just before it signals the child, so pending + no marker is the handoff.\nconst pendingUpdateHandoffExists = Effect.gen(function* () {\n  if (!(yield* pendingServiceUpdateExists)) {\n    return false;\n  }\n  const config = yield* ServerConfig.ServerConfig;\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const runtimeDir = path.join(config.baseDir, \"runtime\");\n  const stopping = yield* fs\n    .exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))\n    .pipe(Effect.orElseSucceed(() => false));\n  return !stopping;\n});\n\n// Cloudflare bills per provisioned tunnel, so an environment that goes offline\n// must not leave its tunnel behind. Releasing deletes only the tunnel — the\n// relay keeps the link and its hostname reservation, and the next startup's\n// link reconcile provisions a replacement tunnel under the same URL.\nexport const releaseManagedTunnelOnShutdown = Effect.fn(\n  \"environment.cloud.releaseManagedTunnelOnShutdown\",\n)(function* () {\n  const dependencies = yield* cloudHttpDependencies;\n  // Only a managed link stores a runtime config; publish-only links have no\n  // tunnel to release.\n  const runtimeConfig = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);\n  if (Option.isNone(runtimeConfig)) {\n    return false;\n  }\n  // Only CLI-desired managed links release on shutdown, because the startup\n  // reconcile that provisions the replacement tunnel only runs for them. A\n  // link installed by a web/mobile client comes back after a restart by\n  // reapplying the stored connector token — it has no boot-time re-provision\n  // path — so its tunnel must survive the restart. (Unlink still deletes it.)\n  if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== \"managed\") {\n    return false;\n  }\n  // A shutdown that hands off to a pending remote update is not the\n  // environment going offline: the launcher immediately brings a server back\n  // (the new version, or the old one after a rollback). Deleting the tunnel\n  // here forces that server to provision a replacement UUID, and the public\n  // hostname's route to the new tunnel takes 1-2 minutes to propagate — the\n  // dominant cost of an update restart. Keep the tunnel instead: the next\n  // boot respawns the connector from the stored config and is reachable as\n  // soon as it connects, and the reconcile confirms the still-live tunnel\n  // without replacing it.\n  if (yield* pendingUpdateHandoffExists) {\n    yield* Effect.logInfo(\"Keeping the managed tunnel across the update restart\");\n    return false;\n  }\n  const token = yield* dependencies.cliTokenManager.getExisting;\n  if (Option.isNone(token)) {\n    return false;\n  }\n  // The link belongs to the relay it was installed against, so target the\n  // persisted URL: SYNAPTIC_RELAY_URL may have changed since the link was made.\n  const relayUrl = yield* dependencies.secrets.get(RELAY_URL_SECRET);\n  if (Option.isNone(relayUrl)) {\n    return false;\n  }\n  const environmentId = yield* dependencies.environment.getEnvironmentId;\n  // Stop the local connector before the relay deletes the tunnel it serves.\n  yield* dependencies.endpointRuntime.applyConfig(null);\n  const response = yield* HttpClientRequest.delete(\n    `${bytesToString(relayUrl.value)}/v1/client/environment-links/${encodeURIComponent(environmentId)}/tunnel`,\n  ).pipe(\n    HttpClientRequest.bearerToken(token.value.accessToken),\n    dependencies.httpClient.execute,\n    Effect.flatMap(HttpClientResponse.filterStatusOk),\n    Effect.flatMap(HttpClientResponse.schemaBodyJson(RelayOkResponse)),\n    withRelayClientTracing,\n  );\n  // ok:false means the relay skipped deletion because a concurrent provision\n  // owns the recorded tunnel now — leave the stored config alone.\n  if (!response.ok) {\n    return false;\n  }\n  // The connector token died with the tunnel. Drop the stored config so the\n  // next start waits for the link reconcile instead of respawning the relay\n  // client with a dead token. Kept when the release request fails: the tunnel\n  // still exists, so the stored token keeps working across the restart.\n  // Only dropped while it is still the config this shutdown released — a fast\n  // restart may already have reconciled and stored a fresh config for its\n  // replacement tunnel, and that one must survive this finalizer.\n  const storedConfig = yield* dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG);\n  if (\n    Option.isSome(storedConfig) &&\n    bytesToString(storedConfig.value) === bytesToString(runtimeConfig.value)\n  ) {\n    yield* dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG);\n  }\n  return true;\n});\n\nconst readCloudLinkState = Effect.fn(\"environment.cloud.readLinkState\")(function* (\n  dependencies: CloudHttpDependencies,\n) {\n  const [cloudUserId, relayUrl, relayIssuer, endpointRuntimeConfig, publishAgentActivity] =\n    yield* Effect.all(\n      [\n        dependencies.secrets.get(CLOUD_LINKED_USER_ID),\n        dependencies.secrets.get(RELAY_URL_SECRET),\n        dependencies.secrets.get(RELAY_ISSUER_SECRET),\n        dependencies.secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG),\n        dependencies.secrets.get(PUBLISH_AGENT_ACTIVITY_SECRET),\n      ],\n      { concurrency: 5 },\n    );\n  return {\n    linked: Option.isSome(cloudUserId),\n    cloudUserId: Option.isSome(cloudUserId) ? bytesToString(cloudUserId.value) : null,\n    relayUrl: Option.isSome(relayUrl) ? bytesToString(relayUrl.value) : null,\n    relayIssuer: Option.isSome(relayIssuer) ? bytesToString(relayIssuer.value) : null,\n    // The managed tunnel runtime config is only stored for managed links; a\n    // publish-only link leaves it absent.\n    managedTunnelActive: Option.isSome(endpointRuntimeConfig),\n    publishAgentActivity: Option.isSome(publishAgentActivity)\n      ? bytesToString(publishAgentActivity.value) === \"true\"\n      : false,\n  } satisfies EnvironmentCloudLinkStateResult;\n});\n\nconst cloudLinkStateHandler = Effect.fn(\"environment.cloud.linkState\")(\n  function* (dependencies: CloudHttpDependencies) {\n    yield* requireEnvironmentScope(AuthRelayReadScope);\n    return yield* readCloudLinkState(dependencies);\n  },\n  Effect.catchIf(\n    ServerSecretStore.isSecretStoreError,\n    failEnvironmentCloudInternalError(\"Could not read environment relay configuration.\"),\n  ),\n);\n\nconst cloudUnlinkHandler = Effect.fn(\"environment.cloud.unlink\")(\n  function* (dependencies: CloudHttpDependencies) {\n    yield* requireEnvironmentScope(AuthRelayWriteScope);\n    const endpointRuntimeStatus = yield* dependencies.endpointRuntime.applyConfig(null);\n    yield* Effect.all(\n      [\n        dependencies.secrets.remove(CLOUD_LINKED_USER_ID),\n        dependencies.secrets.remove(RELAY_URL_SECRET),\n        dependencies.secrets.remove(RELAY_ISSUER_SECRET),\n        dependencies.secrets.remove(RELAY_ENVIRONMENT_CREDENTIAL_SECRET),\n        dependencies.secrets.remove(CLOUD_MINT_PUBLIC_KEY),\n        dependencies.secrets.remove(CLOUD_ENDPOINT_RUNTIME_CONFIG),\n        dependencies.secrets.remove(PUBLISH_AGENT_ACTIVITY_SECRET),\n      ],\n      { concurrency: 7 },\n    );\n    yield* setCliDesiredCloudLink(false);\n    return { ok: true, endpointRuntimeStatus } satisfies EnvironmentCloudRelayConfigResult;\n  },\n  Effect.catchIf(\n    ServerSecretStore.isSecretStoreError,\n    failEnvironmentCloudInternalError(\"Could not remove environment relay configuration.\"),\n  ),\n);\n\nconst cloudPreferencesHandler = Effect.fn(\"environment.cloud.preferences\")(\n  function* (\n    dependencies: CloudHttpDependencies,\n    payload: { readonly publishAgentActivity: boolean },\n  ) {\n    yield* requireEnvironmentScope(AuthRelayWriteScope);\n    yield* dependencies.secrets.set(\n      PUBLISH_AGENT_ACTIVITY_SECRET,\n      stringToBytes(String(payload.publishAgentActivity)),\n    );\n    return yield* readCloudLinkState(dependencies);\n  },\n  Effect.catchIf(\n    ServerSecretStore.isSecretStoreError,\n    failEnvironmentCloudInternalError(\"Could not persist environment cloud preferences.\"),\n  ),\n);\n\nconst cloudEnvironmentHealthHandler = Effect.fn(\"environment.cloud.health\")(\n  function* (dependencies: CloudHttpDependencies, request: RelayCloudEnvironmentHealthRequest) {\n    const cloudMintPublicKey = yield* dependencies.secrets\n      .get(CLOUD_MINT_PUBLIC_KEY)\n      .pipe(\n        Effect.flatMap((bytes) =>\n          Option.isSome(bytes)\n            ? Effect.succeed(bytesToString(bytes.value))\n            : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),\n        ),\n      );\n    const relayIssuer = yield* dependencies.secrets\n      .get(RELAY_ISSUER_SECRET)\n      .pipe(\n        Effect.flatMap((bytes) =>\n          Option.isSome(bytes)\n            ? Effect.succeed(bytesToString(bytes.value))\n            : dependencies.secrets\n                .get(RELAY_URL_SECRET)\n                .pipe(\n                  Effect.flatMap((fallbackBytes) =>\n                    Option.isSome(fallbackBytes)\n                      ? Effect.succeed(bytesToString(fallbackBytes.value))\n                      : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),\n                  ),\n                ),\n        ),\n      );\n    const environmentId = yield* dependencies.environment.getEnvironmentId;\n    const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);\n    const now = yield* DateTime.now;\n    const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);\n    const proofOption = yield* verifyRelayJwt({\n      publicKey: cloudMintPublicKey,\n      token: request.proof,\n      typ: RELAY_HEALTH_REQUEST_TYP,\n      issuer: normalizeRelayIssuer(relayIssuer),\n      audience: `t3-env:${environmentId}`,\n      nowEpochSeconds: nowSeconds,\n    }).pipe(Effect.flatMap(decodeCloudHealthProof), Effect.option);\n    if (\n      Option.isNone(proofOption) ||\n      proofOption.value.environmentId !== environmentId ||\n      proofOption.value.sub !== linkedCloudUserId ||\n      !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||\n      !hasExactScope({ scopes: proofOption.value.scope, expected: \"environment:status\" })\n    ) {\n      return yield* new EnvironmentHttpUnauthorizedError({\n        message: \"Invalid cloud health request.\",\n      });\n    }\n    const proof = proofOption.value;\n\n    const jtiSecretName = `${CLOUD_HEALTH_JTI_PREFIX}${proof.jti}`;\n    const nonceSecretName = `${CLOUD_HEALTH_NONCE_PREFIX}${proof.nonce}`;\n    const consumedReplayGuards = yield* consumeCloudReplayGuards({\n      secrets: dependencies.secrets,\n      names: [jtiSecretName, nonceSecretName],\n      value: stringToBytes(DateTime.formatIso(now)),\n    });\n    if (!consumedReplayGuards) {\n      return yield* new EnvironmentHttpConflictError({\n        message: \"Cloud health request was already consumed.\",\n      });\n    }\n\n    const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);\n    const descriptor = yield* dependencies.environment.getDescriptor;\n    const responseExpiresAt = DateTime.add(now, { minutes: 5 });\n    const responsePayload = {\n      iss: `t3-env:${environmentId}`,\n      aud: normalizeRelayIssuer(relayIssuer),\n      sub: environmentId,\n      jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),\n      iat: nowSeconds,\n      exp: Math.floor(responseExpiresAt.epochMilliseconds / 1_000),\n      environmentId,\n      requestNonce: proof.nonce,\n      status: \"online\",\n      descriptor,\n      checkedAt: DateTime.formatIso(now),\n    } satisfies RelayEnvironmentHealthResponseProofPayload;\n    const responseProof = yield* signRelayJwt({\n      privateKey: keyPair.privateKey,\n      typ: RELAY_HEALTH_RESPONSE_TYP,\n      payload: responsePayload,\n    }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new EnvironmentAuth.ServerAuthCloudHealthJwtSigningError({\n            cause,\n          }),\n      ),\n    );\n    const response = {\n      environmentId,\n      status: \"online\",\n      descriptor,\n      checkedAt: responsePayload.checkedAt,\n      proof: responseProof,\n    } satisfies RelayEnvironmentHealthResponseShape;\n\n    yield* appendCloudCredentialResponseHeaders;\n    return response;\n  },\n  Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n    failEnvironmentCloudInternalError(error.message)(error),\n  ),\n  Effect.catchIf(\n    ServerSecretStore.isSecretStoreError,\n    failEnvironmentCloudInternalError(\"Could not answer cloud health request.\"),\n  ),\n  Effect.catchTag(\n    \"PlatformError\",\n    failEnvironmentCloudInternalError(\"Could not answer cloud health request.\"),\n  ),\n);\n\nconst cloudMintCredentialHandler = Effect.fn(\"environment.cloud.mintCredential\")(\n  function* (dependencies: CloudHttpDependencies, request: RelayCloudMintCredentialRequest) {\n    const cloudMintPublicKey = yield* dependencies.secrets\n      .get(CLOUD_MINT_PUBLIC_KEY)\n      .pipe(\n        Effect.flatMap((bytes) =>\n          Option.isSome(bytes)\n            ? Effect.succeed(bytesToString(bytes.value))\n            : Effect.fail(new EnvironmentAuth.ServerAuthCloudMintPublicKeyMissingError({})),\n        ),\n      );\n    const relayIssuer = yield* dependencies.secrets\n      .get(RELAY_ISSUER_SECRET)\n      .pipe(\n        Effect.flatMap((bytes) =>\n          Option.isSome(bytes)\n            ? Effect.succeed(bytesToString(bytes.value))\n            : dependencies.secrets\n                .get(RELAY_URL_SECRET)\n                .pipe(\n                  Effect.flatMap((fallbackBytes) =>\n                    Option.isSome(fallbackBytes)\n                      ? Effect.succeed(bytesToString(fallbackBytes.value))\n                      : Effect.fail(new EnvironmentAuth.ServerAuthCloudRelayIssuerMissingError({})),\n                  ),\n                ),\n        ),\n      );\n    const environmentId = yield* dependencies.environment.getEnvironmentId;\n    const linkedCloudUserId = yield* readInstalledCloudUserId(dependencies.secrets);\n    const now = yield* DateTime.now;\n    const nowSeconds = Math.floor(now.epochMilliseconds / 1_000);\n    const proofOption = yield* verifyRelayJwt({\n      publicKey: cloudMintPublicKey,\n      token: request.proof,\n      typ: RELAY_MINT_REQUEST_TYP,\n      issuer: normalizeRelayIssuer(relayIssuer),\n      audience: `t3-env:${environmentId}`,\n      nowEpochSeconds: nowSeconds,\n    }).pipe(Effect.flatMap(decodeCloudMintProof), Effect.option);\n    if (\n      Option.isNone(proofOption) ||\n      proofOption.value.environmentId !== environmentId ||\n      proofOption.value.sub !== linkedCloudUserId ||\n      proofOption.value.cnf.jkt !== proofOption.value.clientProofKeyThumbprint ||\n      !hasBoundedCloudProofLifetime({ ...proofOption.value, nowSeconds }) ||\n      !hasExactScope({ scopes: proofOption.value.scope, expected: \"environment:connect\" })\n    ) {\n      return yield* new EnvironmentHttpUnauthorizedError({\n        message: \"Invalid cloud mint request.\",\n      });\n    }\n    const proof = proofOption.value;\n\n    const jtiSecretName = `${CLOUD_MINT_JTI_PREFIX}${proof.jti}`;\n    const nonceSecretName = `${CLOUD_MINT_NONCE_PREFIX}${proof.nonce}`;\n    const consumedReplayGuards = yield* consumeCloudReplayGuards({\n      secrets: dependencies.secrets,\n      names: [jtiSecretName, nonceSecretName],\n      value: stringToBytes(DateTime.formatIso(now)),\n    });\n    if (!consumedReplayGuards) {\n      return yield* new EnvironmentHttpConflictError({\n        message: \"Cloud mint request was already consumed.\",\n      });\n    }\n\n    const keyPair = yield* getOrCreateEnvironmentKeyPairFromSecretStore(dependencies.secrets);\n    const issued = yield* dependencies.environmentAuth.createPairingLink({\n      scopes: AuthStandardClientScopes,\n      subject: \"cloud-connect\",\n      ttl: Duration.minutes(2),\n      label: \"Synaptic Connect\",\n      proofKeyThumbprint: proof.clientProofKeyThumbprint,\n    });\n    const responsePayload = {\n      iss: `t3-env:${environmentId}`,\n      aud: normalizeRelayIssuer(relayIssuer),\n      sub: environmentId,\n      jti: yield* Crypto.Crypto.pipe(Effect.flatMap((crypto) => crypto.randomUUIDv4)),\n      iat: nowSeconds,\n      exp: Math.floor(issued.expiresAt.epochMilliseconds / 1_000),\n      environmentId,\n      clientProofKeyThumbprint: proof.clientProofKeyThumbprint,\n      requestNonce: proof.nonce,\n      credential: issued.credential,\n    } satisfies RelayEnvironmentMintResponseProofPayload;\n    const responseProof = yield* signRelayJwt({\n      privateKey: keyPair.privateKey,\n      typ: RELAY_MINT_RESPONSE_TYP,\n      payload: responsePayload,\n    }).pipe(\n      Effect.mapError(\n        (cause) =>\n          new EnvironmentAuth.ServerAuthCloudMintJwtSigningError({\n            cause,\n          }),\n      ),\n    );\n    const response = {\n      credential: issued.credential,\n      expiresAt: DateTime.formatIso(issued.expiresAt),\n      proof: responseProof,\n    } satisfies RelayEnvironmentMintResponseShape;\n\n    yield* appendCloudCredentialResponseHeaders;\n    return response;\n  },\n  Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (error) =>\n    failEnvironmentCloudInternalError(error.message)(error),\n  ),\n  Effect.catchIf(\n    ServerSecretStore.isSecretStoreError,\n    failEnvironmentCloudInternalError(\"Could not issue cloud connection credential.\"),\n  ),\n  Effect.catchTag(\n    \"PlatformError\",\n    failEnvironmentCloudInternalError(\"Could not issue cloud connection credential.\"),\n  ),\n);\n\nexport const connectHttpApiLayer = HttpApiBuilder.group(\n  EnvironmentHttpApi,\n  \"connect\",\n  Effect.fnUntraced(function* (handlers) {\n    const dependencies = yield* cloudHttpDependencies;\n    return handlers\n      .handle(\"linkProof\", ({ payload }) => cloudLinkProofHandler(dependencies, payload))\n      .handle(\"relayConfig\", ({ payload }) => cloudRelayConfigHandler(dependencies, payload))\n      .handle(\"linkState\", () => cloudLinkStateHandler(dependencies))\n      .handle(\"unlink\", () => cloudUnlinkHandler(dependencies))\n      .handle(\"preferences\", ({ payload }) => cloudPreferencesHandler(dependencies, payload))\n      .handle(\"health\", ({ payload }) => cloudEnvironmentHealthHandler(dependencies, payload))\n      .handle(\"mintCredential\", ({ payload }) => cloudMintCredentialHandler(dependencies, payload))\n      .handle(\"t3MintCredential\", ({ payload }) =>\n        traceRelayRequest(cloudMintCredentialHandler(dependencies, payload)),\n      );\n  }),\n);\n","import { makeRelayClientTracingLayer } from \"@t3tools/shared/relayTracing\";\n\nimport { resolveRelayClientTracingConfig } from \"./publicConfig.ts\";\n\nconst relayClientTracingConfig = resolveRelayClientTracingConfig();\n\nexport const headlessRelayClientTracingLayer = makeRelayClientTracingLayer(\n  relayClientTracingConfig,\n  {\n    serviceName: \"t3-headless-relay-client\",\n    runtime: \"node\",\n    client: \"headless-cli\",\n  },\n);\n\nexport const serverRelayBrokerTracingLayer = makeRelayClientTracingLayer(relayClientTracingConfig, {\n  serviceName: \"t3-server\",\n  runtime: \"node\",\n  client: \"environment-server\",\n  component: \"relay-broker\",\n});\n","import {\n  AuthOrchestrationOperateScope,\n  AuthOrchestrationReadScope,\n  EnvironmentHttpApi,\n} from \"@t3tools/contracts\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\n\nimport { projectThreadDetailSnapshot } from \"./ActivityPayloadProjection.ts\";\nimport { normalizeDispatchCommand } from \"./Normalizer.ts\";\nimport {\n  annotateEnvironmentRequest,\n  failEnvironmentInternal,\n  failEnvironmentInvalidRequest,\n  failEnvironmentNotFound,\n  requireEnvironmentScope,\n} from \"../auth/http.ts\";\nimport { OrchestrationEngineService } from \"./Services/OrchestrationEngine.ts\";\nimport { ProjectionSnapshotQuery } from \"./Services/ProjectionSnapshotQuery.ts\";\n\nexport const orchestrationHttpApiLayer = HttpApiBuilder.group(\n  EnvironmentHttpApi,\n  \"orchestration\",\n  Effect.fnUntraced(function* (handlers) {\n    const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;\n    const orchestrationEngine = yield* OrchestrationEngineService;\n\n    return handlers\n      .handle(\n        \"snapshot\",\n        Effect.fn(\"environment.orchestration.snapshot\")(function* (args) {\n          yield* annotateEnvironmentRequest(args.endpoint.name);\n          yield* requireEnvironmentScope(AuthOrchestrationReadScope);\n          // Serve the lightweight command read model (thread bodies empty)\n          // instead of the fully hydrated snapshot. Hydrating every message\n          // and activity payload in the database has OOM-killed servers, and\n          // the route's only consumer (the project CLI) reads projects alone —\n          // UI clients load the shell and per-thread snapshots instead.\n          return yield* projectionSnapshotQuery\n            .getCommandReadModel()\n            .pipe(\n              Effect.catch((cause) =>\n                failEnvironmentInternal(\"orchestration_snapshot_failed\", cause),\n              ),\n            );\n        }),\n      )\n      .handle(\n        \"shellSnapshot\",\n        Effect.fn(\"environment.orchestration.shellSnapshot\")(function* (args) {\n          yield* annotateEnvironmentRequest(args.endpoint.name);\n          yield* requireEnvironmentScope(AuthOrchestrationReadScope);\n          return yield* projectionSnapshotQuery\n            .getShellSnapshot()\n            .pipe(\n              Effect.catch((cause) =>\n                failEnvironmentInternal(\"orchestration_snapshot_failed\", cause),\n              ),\n            );\n        }),\n      )\n      .handle(\n        \"threadSnapshot\",\n        Effect.fn(\"environment.orchestration.threadSnapshot\")(function* (args) {\n          yield* annotateEnvironmentRequest(args.endpoint.name);\n          yield* requireEnvironmentScope(AuthOrchestrationReadScope);\n          const snapshot = yield* projectionSnapshotQuery\n            .getThreadDetailSnapshot(\n              args.params.threadId,\n              args.payload.turnLimit === undefined\n                ? undefined\n                : {\n                    turnLimit: args.payload.turnLimit,\n                    ...(args.payload.beforeCursor !== undefined\n                      ? { beforeCursor: args.payload.beforeCursor }\n                      : {}),\n                  },\n            )\n            .pipe(\n              Effect.catch((cause) =>\n                failEnvironmentInternal(\"orchestration_thread_snapshot_failed\", cause),\n              ),\n            );\n          if (Option.isNone(snapshot)) {\n            return yield* failEnvironmentNotFound(\"thread_not_found\");\n          }\n          return projectThreadDetailSnapshot(snapshot.value);\n        }),\n      )\n      .handle(\n        \"dispatch\",\n        Effect.fn(\"environment.orchestration.dispatch\")(function* (args) {\n          yield* annotateEnvironmentRequest(args.endpoint.name);\n          yield* requireEnvironmentScope(AuthOrchestrationOperateScope);\n          const normalizedCommand = yield* normalizeDispatchCommand(args.payload).pipe(\n            Effect.catch(() => failEnvironmentInvalidRequest(\"invalid_command\")),\n          );\n          return yield* orchestrationEngine\n            .dispatch(normalizedCommand)\n            .pipe(\n              Effect.catch((cause) =>\n                failEnvironmentInternal(\"orchestration_dispatch_failed\", cause),\n              ),\n            );\n        }),\n      );\n  }),\n);\n","import { EnvironmentHttpApi } from \"@t3tools/contracts\";\nimport * as Duration from \"effect/Duration\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schedule from \"effect/Schedule\";\nimport { FetchHttpClient, HttpRouter, HttpServer } from \"effect/unstable/http\";\nimport * as HttpApiBuilder from \"effect/unstable/httpapi/HttpApiBuilder\";\n\nimport * as BackgroundPolicy from \"./background/BackgroundPolicy.ts\";\nimport * as HostPowerMonitor from \"./background/HostPowerMonitor.ts\";\nimport * as ServerConfig from \"./config.ts\";\nimport {\n  otlpTracesProxyRouteLayer,\n  assetRouteLayer,\n  serverEnvironmentHttpApiLayer,\n  staticAndDevRouteLayer,\n  browserApiCorsLayer,\n  httpCompressionLayer,\n} from \"./http.ts\";\nimport { fixPath } from \"./os-jank.ts\";\nimport { websocketRpcRouteLayer } from \"./ws.ts\";\nimport * as ExternalLauncher from \"./process/externalLauncher.ts\";\nimport { layerConfig as SqlitePersistenceLayerLive } from \"./persistence/Layers/Sqlite.ts\";\nimport * as ServerLifecycleEvents from \"./serverLifecycleEvents.ts\";\nimport * as AnalyticsService from \"./telemetry/AnalyticsService.ts\";\nimport { ProviderSessionDirectoryLive } from \"./provider/Layers/ProviderSessionDirectory.ts\";\nimport * as ProviderSessionRuntime from \"./persistence/ProviderSessionRuntime.ts\";\nimport { ProviderAdapterRegistryLive } from \"./provider/Layers/ProviderAdapterRegistry.ts\";\nimport * as ProviderEventLoggers from \"./provider/Layers/ProviderEventLoggers.ts\";\nimport { ProviderServiceLive } from \"./provider/Layers/ProviderService.ts\";\nimport { ProviderSessionReaperLive } from \"./provider/Layers/ProviderSessionReaper.ts\";\nimport * as OpenCodeRuntime from \"./provider/opencodeRuntime.ts\";\nimport * as CheckpointDiffQuery from \"./checkpointing/CheckpointDiffQuery.ts\";\nimport * as CheckpointStore from \"./checkpointing/CheckpointStore.ts\";\nimport * as AzureDevOpsCli from \"./sourceControl/AzureDevOpsCli.ts\";\nimport * as BitbucketApi from \"./sourceControl/BitbucketApi.ts\";\nimport * as GitHubCli from \"./sourceControl/GitHubCli.ts\";\nimport * as GitLabCli from \"./sourceControl/GitLabCli.ts\";\nimport * as TextGeneration from \"./textGeneration/TextGeneration.ts\";\nimport { ProviderInstanceRegistryHydrationLive } from \"./provider/Layers/ProviderInstanceRegistryHydration.ts\";\nimport * as TerminalManager from \"./terminal/Manager.ts\";\nimport * as McpHttpServer from \"./mcp/McpHttpServer.ts\";\nimport * as McpSessionRegistry from \"./mcp/McpSessionRegistry.ts\";\nimport * as PreviewAutomationBroker from \"./mcp/PreviewAutomationBroker.ts\";\nimport * as PreviewManager from \"./preview/Manager.ts\";\nimport * as PortScanner from \"./preview/PortScanner.ts\";\nimport * as ProcessRunner from \"./processRunner.ts\";\nimport * as GitManager from \"./git/GitManager.ts\";\nimport * as Keybindings from \"./keybindings.ts\";\nimport * as ServerRuntimeStartup from \"./serverRuntimeStartup.ts\";\nimport { OrchestrationReactorLive } from \"./orchestration/Layers/OrchestrationReactor.ts\";\nimport { RuntimeReceiptBusLive } from \"./orchestration/Layers/RuntimeReceiptBus.ts\";\nimport { ProviderRuntimeIngestionLive } from \"./orchestration/Layers/ProviderRuntimeIngestion.ts\";\nimport { ProviderCommandReactorLive } from \"./orchestration/Layers/ProviderCommandReactor.ts\";\nimport { CheckpointReactorLive } from \"./orchestration/Layers/CheckpointReactor.ts\";\nimport { ThreadDeletionReactorLive } from \"./orchestration/Layers/ThreadDeletionReactor.ts\";\nimport * as AgentAwarenessRelay from \"./relay/AgentAwarenessRelay.ts\";\nimport { hasCloudPublicConfig } from \"./cloud/publicConfig.ts\";\nimport { ProviderRegistryLive } from \"./provider/Layers/ProviderRegistry.ts\";\nimport * as ServerSettings from \"./serverSettings.ts\";\nimport * as ProjectFaviconResolver from \"./project/ProjectFaviconResolver.ts\";\nimport * as T3ProjectFileLoader from \"./project/T3ProjectFileLoader.ts\";\nimport * as RepositoryIdentityResolver from \"./project/RepositoryIdentityResolver.ts\";\nimport * as WorkspaceEntries from \"./workspace/WorkspaceEntries.ts\";\nimport * as WorkspaceFileSystem from \"./workspace/WorkspaceFileSystem.ts\";\nimport * as WorkspacePaths from \"./workspace/WorkspacePaths.ts\";\nimport * as GitVcsDriver from \"./vcs/GitVcsDriver.ts\";\nimport * as VcsDriverRegistry from \"./vcs/VcsDriverRegistry.ts\";\nimport * as VcsProjectConfig from \"./vcs/VcsProjectConfig.ts\";\nimport * as VcsProcess from \"./vcs/VcsProcess.ts\";\nimport * as VcsProvisioningService from \"./vcs/VcsProvisioningService.ts\";\nimport * as VcsStatusBroadcaster from \"./vcs/VcsStatusBroadcaster.ts\";\nimport * as GitWorkflowService from \"./git/GitWorkflowService.ts\";\nimport * as ReviewService from \"./review/ReviewService.ts\";\nimport * as SourceControlProviderRegistry from \"./sourceControl/SourceControlProviderRegistry.ts\";\nimport * as SourceControlRepositoryService from \"./sourceControl/SourceControlRepositoryService.ts\";\nimport * as ProjectSetupScriptRunner from \"./project/ProjectSetupScriptRunner.ts\";\nimport { ObservabilityLive } from \"./observability/Layers/Observability.ts\";\nimport * as ServerEnvironment from \"./environment/ServerEnvironment.ts\";\nimport { authHttpApiLayer, environmentAuthenticatedAuthLayer } from \"./auth/http.ts\";\nimport * as ServerSecretStore from \"./auth/ServerSecretStore.ts\";\nimport * as EnvironmentAuth from \"./auth/EnvironmentAuth.ts\";\nimport {\n  connectHttpApiLayer,\n  pendingServiceUpdateExists,\n  reconcileDesiredCloudLink,\n  releaseManagedTunnelOnShutdown,\n} from \"./cloud/http.ts\";\nimport { serverRelayBrokerTracingLayer } from \"./cloud/relayTracing.ts\";\nimport * as CloudManagedEndpointRuntime from \"./cloud/ManagedEndpointRuntime.ts\";\nimport * as CloudCliTokenManager from \"./cloud/CliTokenManager.ts\";\nimport * as CloudCliState from \"./cloud/CliState.ts\";\nimport * as ServerSelfUpdate from \"./cloud/selfUpdate.ts\";\nimport * as ServiceLauncherClient from \"./cloud/serviceLauncherClient.ts\";\nimport * as ProcessDiagnostics from \"./diagnostics/ProcessDiagnostics.ts\";\nimport * as ProcessResourceMonitor from \"./diagnostics/ProcessResourceMonitor.ts\";\nimport * as TraceDiagnostics from \"./diagnostics/TraceDiagnostics.ts\";\nimport * as DesktopTelemetryReceiver from \"./resourceTelemetry/DesktopTelemetryReceiver.ts\";\nimport * as NativeTelemetryClient from \"./resourceTelemetry/NativeTelemetryClient.ts\";\nimport * as ResourceAttribution from \"./resourceTelemetry/ResourceAttribution.ts\";\nimport * as ResourceMonitorBinary from \"./resourceTelemetry/ResourceMonitorBinary.ts\";\nimport * as ResourceTelemetry from \"./resourceTelemetry/ResourceTelemetry.ts\";\nimport * as UsageService from \"./usage/UsageService.ts\";\nimport { OrchestrationLayerLive } from \"./orchestration/runtimeLayer.ts\";\nimport {\n  clearPersistedServerRuntimeState,\n  makePersistedServerRuntimeState,\n  persistServerRuntimeState,\n} from \"./serverRuntimeState.ts\";\nimport { orchestrationHttpApiLayer } from \"./orchestration/http.ts\";\nimport * as NetService from \"@t3tools/shared/Net\";\nimport * as RelayClient from \"@t3tools/shared/relayClient\";\nimport { disableTailscaleServe, ensureTailscaleServe } from \"@t3tools/tailscale\";\nimport { forkParked, ServerActivation } from \"./serverActivation.ts\";\n\n// Effect's default preemptive shutdown waits 20s before finalizing request scopes.\n// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer\n// already closes the websocket gracefully. Do not add an artificial drain before\n// those finalizers get a chance to run.\nconst HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;\nconst ResourceAttributionLayerLive = ResourceAttribution.layer;\nconst ApplicationObservabilityLive = ObservabilityLive.pipe(\n  Layer.provideMerge(ResourceAttributionLayerLive),\n);\n\nconst PtyAdapterLive = Layer.unwrap(\n  Effect.gen(function* () {\n    if (typeof Bun !== \"undefined\") {\n      const BunPtyAdapter = yield* Effect.promise(() => import(\"./terminal/BunPtyAdapter.ts\"));\n      return BunPtyAdapter.layer;\n    } else {\n      const NodePtyAdapter = yield* Effect.promise(() => import(\"./terminal/NodePtyAdapter.ts\"));\n      return NodePtyAdapter.layer;\n    }\n  }),\n);\n\nconst ServerSettingsLayerLive = ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer));\n\nconst NativeTelemetryLayerLive = NativeTelemetryClient.layer.pipe(\n  Layer.provide(ResourceMonitorBinary.layer),\n);\nconst DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer.pipe(\n  Layer.provideMerge(ServerSettingsLayerLive),\n);\n\nconst ResourceTelemetryLayerLive = ResourceTelemetry.layer.pipe(\n  Layer.provideMerge(NativeTelemetryLayerLive),\n  Layer.provideMerge(DesktopTelemetryReceiverLayerLive),\n);\n\nconst HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(\n  Layer.provide(DesktopTelemetryReceiverLayerLive),\n);\n\nconst BackgroundLayerLive = BackgroundPolicy.layer.pipe(\n  Layer.provide(HostPowerMonitorLayerLive),\n  Layer.provideMerge(ServerSettingsLayerLive),\n);\n\nconst UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive));\n\nconst ResourceDiagnosticsLayerLive = Layer.mergeAll(\n  ResourceTelemetryLayerLive,\n  ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),\n  ProcessResourceMonitor.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),\n);\n\nconst RelayClientLive = Layer.unwrap(\n  Effect.gen(function* () {\n    const config = yield* ServerConfig.ServerConfig;\n    return RelayClient.layerCloudflared({ baseDir: config.baseDir });\n  }),\n);\n\nconst HttpServerLive = Layer.unwrap(\n  Effect.gen(function* () {\n    const config = yield* ServerConfig.ServerConfig;\n    if (typeof Bun !== \"undefined\") {\n      const BunHttpServer = yield* Effect.promise(\n        () => import(\"@effect/platform-bun/BunHttpServer\"),\n      );\n      return BunHttpServer.layer({\n        port: config.port,\n        hostname: config.host ?? \"127.0.0.1\",\n        gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,\n        websocket: {\n          // Negotiate permessage-deflate with clients that offer it; clients\n          // that don't still get uncompressed frames on their connection. A\n          // dedicated compressor keeps a per-connection sliding window\n          // (context takeover) so the compression dictionary is shared across\n          // server-to-client frames. Decompression uses the shared\n          // decompressor: uWebSockets' dedicated decompressor path can abort\n          // connections (close 1006) on valid DEFLATE input — see\n          // https://github.com/uNetworking/uWebSockets.js/issues/633.\n          perMessageDeflate: {\n            compress: \"dedicated\",\n            decompress: \"shared\",\n          },\n        },\n      });\n    } else {\n      const [NodeHttpServer, NodeHttp] = yield* Effect.all([\n        Effect.promise(() => import(\"@effect/platform-node/NodeHttpServer\")),\n        Effect.promise(() => import(\"node:http\")),\n      ]);\n      return NodeHttpServer.layer(NodeHttp.createServer, {\n        host: config.host ?? \"127.0.0.1\",\n        port: config.port,\n        gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,\n        // Negotiate permessage-deflate with clients that offer it; clients\n        // that don't still get uncompressed frames on their connection.\n        // Context takeover stays enabled (ws default) so the compression\n        // window is shared across frames — that also makes small frames cheap\n        // to compress, so no size threshold is set (ws only honors\n        // `threshold` when context takeover is disabled).\n        websocket: { perMessageDeflate: true },\n      });\n    }\n  }),\n);\n\nconst PlatformServicesLive = Layer.unwrap(\n  Effect.gen(function* () {\n    if (typeof Bun !== \"undefined\") {\n      const { layer } = yield* Effect.promise(() => import(\"@effect/platform-bun/BunServices\"));\n      return layer;\n    } else {\n      const { layer } = yield* Effect.promise(() => import(\"@effect/platform-node/NodeServices\"));\n      return layer;\n    }\n  }),\n);\n\nconst ReactorLayerLive = Layer.empty.pipe(\n  Layer.provideMerge(OrchestrationReactorLive),\n  Layer.provideMerge(ProviderRuntimeIngestionLive),\n  Layer.provideMerge(ProviderCommandReactorLive),\n  Layer.provideMerge(CheckpointReactorLive),\n  Layer.provideMerge(ThreadDeletionReactorLive),\n  Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),\n  Layer.provideMerge(RuntimeReceiptBusLive),\n);\n\nconst ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(\n  Layer.provide(ProviderSessionRuntime.layer),\n);\n\n// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter\n// by looking up the default `ProviderInstance` per driver in the instance\n// registry. Adapter construction itself moved inside each driver's\n// `create()`; `ProviderEventLoggers.layer` owns the shared native/canonical\n// NDJSON writers and is provided at the outer runtime layer so both\n// `ProviderService` and the per-instance drivers read the same logger pair.\nconst ProviderLayerLive = ProviderServiceLive.pipe(\n  Layer.provide(ProviderAdapterRegistryLive),\n  Layer.provideMerge(ProviderSessionDirectoryLayerLive),\n);\n\nconst PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));\n\nconst VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(\n  Layer.provide(VcsProjectConfig.layer),\n);\n\nconst SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(\n  Layer.provide(\n    Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),\n  ),\n  Layer.provideMerge(GitVcsDriver.layer),\n  Layer.provideMerge(VcsDriverRegistryLayerLive),\n);\n\nconst GitManagerLayerLive = GitManager.layer.pipe(\n  Layer.provideMerge(ProjectSetupScriptRunner.layer),\n  Layer.provideMerge(GitVcsDriver.layer),\n  Layer.provideMerge(SourceControlProviderRegistryLayerLive),\n  Layer.provideMerge(TextGeneration.layer),\n);\n\nconst GitLayerLive = Layer.empty.pipe(\n  Layer.provideMerge(GitManagerLayerLive),\n  Layer.provideMerge(GitVcsDriver.layer),\n);\n\nconst GitWorkflowLayerLive = GitWorkflowService.layer.pipe(\n  Layer.provideMerge(VcsDriverRegistryLayerLive),\n  Layer.provideMerge(GitLayerLive),\n);\n\nconst SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(\n  Layer.provideMerge(GitVcsDriver.layer),\n  Layer.provideMerge(SourceControlProviderRegistryLayerLive),\n);\n\nconst ReviewLayerLive = ReviewService.layer.pipe(\n  Layer.provideMerge(GitVcsDriver.layer),\n  Layer.provideMerge(VcsDriverRegistryLayerLive),\n);\n\nconst VcsLayerLive = Layer.empty.pipe(\n  Layer.provideMerge(VcsProjectConfig.layer),\n  Layer.provideMerge(VcsDriverRegistryLayerLive),\n  Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),\n  Layer.provideMerge(GitWorkflowLayerLive),\n  Layer.provideMerge(ReviewLayerLive),\n  Layer.provideMerge(SourceControlRepositoryServiceLayerLive),\n  Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),\n);\n\nconst CheckpointingLayerLive = Layer.empty.pipe(\n  Layer.provideMerge(CheckpointDiffQuery.layer),\n  Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),\n);\n\nconst PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));\n\nconst TerminalLayerLive = TerminalManager.layer.pipe(\n  Layer.provide(PtyAdapterLive),\n  Layer.provide(PortScannerLayerLive),\n);\n\nconst PreviewLayerLive = Layer.empty.pipe(\n  Layer.provideMerge(PreviewManager.layer),\n  Layer.provideMerge(PortScannerLayerLive),\n);\n\nconst WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));\n\nconst WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(\n  Layer.provide(WorkspacePaths.layer),\n  Layer.provide(WorkspaceEntriesLayerLive),\n);\n\nconst WorkspaceLayerLive = Layer.mergeAll(\n  WorkspacePaths.layer,\n  WorkspaceEntriesLayerLive,\n  WorkspaceFileSystemLayerLive,\n);\n\nconst ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(\n  Layer.provide(WorkspacePaths.layer),\n  Layer.provide(T3ProjectFileLoader.layer),\n);\n\nconst AuthLayerLive = EnvironmentAuth.layer.pipe(\n  Layer.provideMerge(PersistenceLayerLive),\n  Layer.provide(ServerSecretStore.layer),\n);\n\nconst CloudManagedEndpointRuntimeLive = Layer.mergeAll(\n  RelayClientLive,\n  CloudManagedEndpointRuntime.layer.pipe(\n    Layer.provide(ServerSecretStore.layer),\n    Layer.provide(RelayClientLive),\n  ),\n);\n\nconst ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(\n  Layer.provideMerge(ProviderLayerLive),\n  Layer.provideMerge(OrchestrationLayerLive),\n);\n\nconst RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(\n  // Core Services\n  Layer.provideMerge(ServerSettingsLayerLive),\n  Layer.provideMerge(CheckpointingLayerLive),\n  Layer.provideMerge(SourceControlProviderRegistryLayerLive),\n  Layer.provideMerge(GitLayerLive),\n  Layer.provideMerge(VcsLayerLive),\n  Layer.provideMerge(ProviderRuntimeLayerLive),\n  Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),\n  Layer.provideMerge(PersistenceLayerLive),\n  Layer.provideMerge(Keybindings.layer),\n  Layer.provideMerge(ProviderRegistryLive),\n  // The instance registry is the new routing keystone — text generation,\n  // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`\n  // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;\n  // `providerInstances` hydration merges `settings.providers.<kind>`\n  // with explicit `providerInstances` entries on boot.\n  Layer.provideMerge(ProviderInstanceRegistryHydrationLive),\n  // Shared native/canonical NDJSON writers used by both the per-instance\n  // drivers (native stream, written from inside each `<X>Adapter`) and\n  // `ProviderService` (canonical stream, written after event normalization).\n  // Provided once at the runtime level so every consumer sees the same\n  // logger instances.\n  Layer.provideMerge(ProviderEventLoggers.layer),\n  // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old\n  // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but\n  // the rewritten registry reads snapshots off the instance registry and\n  // no longer transitively provides it. Exposing it at the runtime level\n  // keeps a single Live for all opencode consumers.\n  Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),\n  Layer.provideMerge(WorkspaceLayerLive),\n  Layer.provideMerge(ProjectFaviconResolverLayerLive),\n  Layer.provideMerge(RepositoryIdentityResolver.layer),\n  Layer.provideMerge(ServerEnvironment.layer),\n  Layer.provideMerge(AuthLayerLive),\n  Layer.provideMerge(ServerSecretStore.layer),\n  Layer.provideMerge(\n    Layer.mergeAll(\n      CloudCliTokenManager.layer.pipe(\n        Layer.provide(ServerSecretStore.layer),\n        Layer.provide(ExternalLauncher.layer),\n      ),\n      CloudManagedEndpointRuntimeLive,\n    ),\n  ),\n);\n\nconst RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(\n  // Misc.\n  Layer.provideMerge(BackgroundLayerLive),\n  Layer.provideMerge(ResourceDiagnosticsLayerLive),\n  Layer.provideMerge(UsageLayerLive),\n  Layer.provideMerge(TraceDiagnostics.layer),\n  Layer.provideMerge(AnalyticsService.layer),\n  Layer.provideMerge(ExternalLauncher.layer),\n  Layer.provideMerge(ServerLifecycleEvents.layer),\n  Layer.provide(NetService.layer),\n);\n\nconst commandReadinessLayer = HttpRouter.middleware(\n  (httpEffect) =>\n    Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>\n      startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),\n    ),\n  { global: true },\n);\n\nexport const makeRoutesLayer = Layer.mergeAll(\n  Layer.mergeAll(\n    HttpApiBuilder.layer(EnvironmentHttpApi).pipe(\n      Layer.provide(authHttpApiLayer),\n      Layer.provide(connectHttpApiLayer),\n      Layer.provide(orchestrationHttpApiLayer),\n      Layer.provide(serverEnvironmentHttpApiLayer),\n      Layer.provide(environmentAuthenticatedAuthLayer),\n    ),\n    otlpTracesProxyRouteLayer,\n    assetRouteLayer,\n    staticAndDevRouteLayer,\n    websocketRpcRouteLayer,\n  ),\n  McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),\n).pipe(\n  Layer.provide(PreviewAutomationBroker.layer),\n  Layer.provide(ServerSelfUpdate.layer),\n  Layer.provide(commandReadinessLayer),\n  Layer.provide(browserApiCorsLayer),\n  Layer.provide(httpCompressionLayer),\n);\n\nexport const makeServerLayer = Layer.unwrap(\n  Effect.gen(function* () {\n    const config = yield* ServerConfig.ServerConfig;\n    const activation = yield* Deferred.make<void>();\n    const awaitActivation = Deferred.await(activation);\n    const activationLayer = Layer.succeed(ServerActivation, awaitActivation);\n    const runtimeStateParked = yield* Deferred.make<void>();\n    const tailscaleParked = yield* Deferred.make<void>();\n    const cloudLinkParked = yield* Deferred.make<void>();\n    const routesReady = yield* Deferred.make<void>();\n    const launcherLayer = ServiceLauncherClient.layer;\n\n    yield* fixPath();\n\n    const httpListeningLayer = Layer.effectDiscard(\n      Effect.gen(function* () {\n        yield* HttpServer.HttpServer;\n        const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;\n        yield* startup.markHttpListening;\n      }),\n    );\n    const runtimeStateLayer = Layer.effectDiscard(\n      Effect.acquireRelease(\n        Effect.gen(function* () {\n          yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);\n          yield* awaitActivation;\n          const server = yield* HttpServer.HttpServer;\n          const address = server.address;\n          if (typeof address === \"string\" || !(\"port\" in address)) {\n            return;\n          }\n\n          const state = yield* makePersistedServerRuntimeState({\n            config,\n            port: address.port,\n          });\n          yield* persistServerRuntimeState({\n            path: config.serverRuntimeStatePath,\n            state,\n          }).pipe(\n            Effect.catchCause((cause) =>\n              Effect.logWarning(\"Failed to persist server runtime state\", { cause }),\n            ),\n          );\n        }),\n        () =>\n          clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(\n            Effect.catchCause((cause) =>\n              Effect.logWarning(\"Failed to clear server runtime state\", { cause }),\n            ),\n          ),\n      ),\n    );\n    const tailscaleServeLayer = config.tailscaleServeEnabled\n      ? Layer.effectDiscard(\n          Effect.acquireRelease(\n            Effect.gen(function* () {\n              yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);\n              yield* awaitActivation;\n              const server = yield* HttpServer.HttpServer;\n              const address = server.address;\n              if (typeof address === \"string\" || !(\"port\" in address)) {\n                return null;\n              }\n\n              const localPort = address.port;\n              return yield* ensureTailscaleServe({\n                localPort,\n                servePort: config.tailscaleServePort,\n                localHost: \"127.0.0.1\",\n              }).pipe(\n                Effect.as({ localPort, servePort: config.tailscaleServePort }),\n                Effect.tap(() =>\n                  Effect.logInfo(\"Tailscale Serve configured\", {\n                    localPort,\n                    servePort: config.tailscaleServePort,\n                  }),\n                ),\n                Effect.catch((cause) =>\n                  Effect.logWarning(\"Failed to configure Tailscale Serve\", {\n                    cause,\n                    localPort,\n                    servePort: config.tailscaleServePort,\n                  }).pipe(Effect.as(null)),\n                ),\n              );\n            }),\n            (configured) =>\n              configured\n                ? disableTailscaleServe({ servePort: configured.servePort }).pipe(\n                    Effect.tap(() =>\n                      Effect.logInfo(\"Tailscale Serve disabled\", {\n                        servePort: configured.servePort,\n                      }),\n                    ),\n                    Effect.catch((cause) =>\n                      Effect.logWarning(\"Failed to disable Tailscale Serve\", {\n                        cause,\n                        servePort: configured.servePort,\n                      }),\n                    ),\n                  )\n                : Effect.void,\n          ),\n        )\n      : Layer.empty;\n    const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(\n      Effect.gen(function* () {\n        if (!hasCloudPublicConfig) {\n          yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);\n          return;\n        }\n        const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(\n          Effect.timeout(\"10 seconds\"),\n          Effect.tap((released) =>\n            released ? Effect.logInfo(\"Released the managed tunnel on shutdown\") : Effect.void,\n          ),\n          Effect.catchCause((cause) =>\n            Effect.logWarning(\n              \"Failed to release the managed tunnel on shutdown; the next link reuses it\",\n              { cause },\n            ),\n          ),\n          Effect.asVoid,\n        );\n        // A launcher trial can be stopped before activation. The previous\n        // server is already gone, so the trial owns cleanup immediately; the\n        // pending-state check keeps the tunnel for normal commit or rollback,\n        // while the launcher's explicit-stop marker allows it to be released.\n        // Other runtimes wait for activation so a failed standby cannot tear\n        // down the active runtime's tunnel.\n        const cleanupBeforeActivation = yield* pendingServiceUpdateExists;\n        if (cleanupBeforeActivation) {\n          yield* Effect.addFinalizer(() => releaseManagedTunnel);\n        }\n        yield* forkParked(\n          Effect.gen(function* () {\n            if (!cleanupBeforeActivation) {\n              yield* Effect.addFinalizer(() => releaseManagedTunnel);\n            }\n            if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;\n            const server = yield* HttpServer.HttpServer;\n            const address = server.address;\n            if (typeof address === \"string\" || !(\"port\" in address)) return;\n            // No settling delay before the first attempt: routes are already\n            // serving by the time activation opens this gate (the startup\n            // sequence awaits routesReady), and the retry schedule below\n            // covers anything this sleep used to hedge against. Every\n            // millisecond here is dead time on the path to remote\n            // reachability after a restart.\n            yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(\n              Effect.retry({\n                while: (error) =>\n                  error._tag !== \"EnvironmentHttpBadRequestError\" &&\n                  error._tag !== \"EnvironmentHttpUnauthorizedError\" &&\n                  error._tag !== \"EnvironmentHttpConflictError\",\n                schedule: Schedule.exponential(\"1 second\").pipe(\n                  Schedule.modifyDelay(({ duration }) =>\n                    Effect.succeed(Duration.min(duration, Duration.seconds(30))),\n                  ),\n                  Schedule.upTo({ duration: \"10 minutes\" }),\n                ),\n              }),\n              Effect.tap(() => Effect.logInfo(\"T3 Connect desired link reconciled on startup\")),\n              Effect.catch((cause) =>\n                Effect.logWarning(\"Failed to reconcile T3 Connect desired link on startup\", {\n                  cause,\n                }),\n              ),\n            );\n          }),\n        );\n        yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);\n      }),\n    );\n\n    const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({\n      activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),\n      abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),\n      awaitAuxiliaryParked: Effect.all(\n        [\n          Deferred.await(runtimeStateParked),\n          Deferred.await(cloudLinkParked),\n          Deferred.await(routesReady),\n          ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),\n        ],\n        { concurrency: \"unbounded\" },\n      ).pipe(Effect.asVoid),\n    }).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));\n\n    const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {\n      disableLogger: !config.logWebSocketEvents,\n    }).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));\n    const serverApplicationLayer = Layer.mergeAll(\n      routesLayer,\n      httpListeningLayer,\n      runtimeStateLayer,\n      tailscaleServeLayer,\n      cloudDesiredLinkReconcileLayer,\n    );\n\n    return serverApplicationLayer.pipe(\n      Layer.provideMerge(runtimeServicesLive),\n      Layer.provide(activationLayer),\n      Layer.provideMerge(serverRelayBrokerTracingLayer),\n      Layer.provideMerge(HttpServerLive),\n      Layer.provide(ApplicationObservabilityLive),\n      Layer.provideMerge(FetchHttpClient.layer),\n      Layer.provideMerge(VcsProcess.layer),\n      Layer.provideMerge(PlatformServicesLive),\n    );\n  }),\n);\n\n// The CLI supplies configuration.\nexport const runServer = Layer.launch(makeServerLayer);\n","import * as Effect from \"effect/Effect\";\nimport { Command, GlobalFlag } from \"effect/unstable/cli\";\n\nimport { ServerConfig, type StartupPresentation } from \"../config.ts\";\nimport { runServer } from \"../server.ts\";\nimport { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from \"./config.ts\";\n\nexport const runServerCommand = (\n  flags: CliServerFlags,\n  options?: {\n    readonly startupPresentation?: StartupPresentation;\n    readonly forceAutoBootstrapProjectFromCwd?: boolean;\n  },\n) =>\n  Effect.gen(function* () {\n    const logLevel = yield* GlobalFlag.LogLevel;\n    const config = yield* resolveServerConfig(flags, logLevel, options);\n    return yield* runServer.pipe(Effect.provideService(ServerConfig, config));\n  });\n\nexport const startCommand = Command.make(\"start\", { ...sharedServerCommandFlags }).pipe(\n  Command.withDescription(\"Run the Synaptic Code server.\"),\n  Command.withHandler((flags) => runServerCommand(flags)),\n);\n\nexport const serveCommand = Command.make(\"serve\", { ...sharedServerCommandFlags }).pipe(\n  Command.withDescription(\n    \"Run the Synaptic Code server without opening a browser and print headless pairing details.\",\n  ),\n  Command.withHandler((flags) =>\n    runServerCommand(flags, {\n      startupPresentation: \"headless\",\n      forceAutoBootstrapProjectFromCwd: false,\n    }),\n  ),\n);\n","import { HostProcessExecutablePath, HostProcessPlatform } from \"@t3tools/shared/hostProcess\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as DateTime from \"effect/DateTime\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\n\nimport * as ProcessRunner from \"../processRunner.ts\";\nimport {\n  ensurePinnedRuntimeInstalled,\n  pinnedRuntimePaths,\n  PinnedRuntimeInstallError,\n} from \"./pinnedRuntime.ts\";\nimport {\n  SERVICE_LAUNCHER_FILE,\n  SERVICE_LAUNCHER_PROTOCOL,\n  SERVICE_STATE_FILE,\n  parseServiceState,\n  serviceStateHasPendingUpdate,\n  type ServiceState,\n} from \"./serviceProtocol.ts\";\n\n/**\n * Installs Synaptic Code as a per-user boot service. Linux-only for now: systemd\n * user unit + loginctl enable-linger. The service runs a stable or pinned\n * runtime, never an ephemeral `npx @dmccore/code` cache whose eviction could\n * break startup.\n */\n\n// Named after the fork's bin that installs it. The source project installs a\n// t3code.service, and one shared unit name on one machine would let each\n// product's `service install` overwrite the other's unit.\nconst BOOT_SERVICE_NAME = \"synaptic-code\";\nexport const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;\nexport const BOOT_SERVICE_UNIT_ENV = \"SYNAPTIC_BOOT_SERVICE_UNIT\";\n\n/** systemd expands `%` specifiers, including in unquoted append-log paths. */\nexport function escapeSystemdSpecifiers(value: string): string {\n  return value.replaceAll(\"%\", \"%%\");\n}\n\nexport function quoteSystemdValue(value: string): string {\n  const escaped = escapeSystemdSpecifiers(value);\n  return /[\\s\"'\\\\]/.test(escaped)\n    ? `\"${escaped.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`\n    : escaped;\n}\n\nexport interface BootServicePlan {\n  readonly nodePath: string;\n  readonly launcherPath: string;\n  readonly baseDir: string;\n  readonly logPath: string;\n  readonly unitPath: string;\n}\n\n/** Pure renderer: service units cannot rely on the user's shell or PATH. */\nexport function renderBootServiceUnit(plan: BootServicePlan): string {\n  // The user manager has no reliable network-online target; server networking retries itself.\n  return [\n    \"[Unit]\",\n    \"Description=Synaptic Code server\",\n    // Give up after 5 crashes in 5 minutes so a persistently broken install\n    // (deleted runtime, broken workspace) stops instead of restarting every\n    // 5s forever and growing the unrotated append log without bound.\n    \"StartLimitIntervalSec=300\",\n    \"StartLimitBurst=5\",\n    \"\",\n    \"[Service]\",\n    \"Type=simple\",\n    \"WorkingDirectory=%h\",\n    // The launcher this unit starts is copied from the pinned @dmccore/code\n    // runtime by the same service install, so both sides of the handshake\n    // are this fork's and one spelling is enough.\n    `Environment=SYNAPTIC_HOME=${quoteSystemdValue(plan.baseDir)}`,\n    `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,\n    `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,\n    // Let the launcher mark an explicit stop before it signals the server.\n    // systemd still SIGKILLs the whole cgroup if graceful shutdown times out.\n    \"KillMode=mixed\",\n    \"Restart=always\",\n    \"RestartSec=5\",\n    `StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,\n    `StandardError=append:${escapeSystemdSpecifiers(plan.logPath)}`,\n    \"\",\n    \"[Install]\",\n    \"WantedBy=default.target\",\n    \"\",\n  ].join(\"\\n\");\n}\n\nexport class BootServiceUnsupportedError extends Schema.TaggedErrorClass<BootServiceUnsupportedError>()(\n  \"BootServiceUnsupportedError\",\n  { platform: Schema.String },\n) {\n  override get message(): string {\n    return `Background setup currently supports Linux with systemd; this machine reports '${this.platform}'.`;\n  }\n}\n\nexport class BootServiceCommandError extends Schema.TaggedErrorClass<BootServiceCommandError>()(\n  \"BootServiceCommandError\",\n  {\n    step: Schema.String,\n    exitCode: Schema.optional(Schema.Number),\n    stdoutLength: Schema.optional(Schema.Number),\n    stderrLength: Schema.optional(Schema.Number),\n    cause: Schema.optional(Schema.Defect()),\n  },\n) {\n  override get message(): string {\n    return this.exitCode === undefined\n      ? `Background setup failed while ${this.step}.`\n      : `Background setup failed while ${this.step} (exit code ${this.exitCode}).`;\n  }\n}\n\nexport class BootServiceInstallError extends Schema.TaggedErrorClass<BootServiceInstallError>()(\n  \"BootServiceInstallError\",\n  { cause: Schema.Defect() },\n) {\n  override get message(): string {\n    return \"Could not set up the Synaptic Code background service.\";\n  }\n}\n\nexport class BootServiceUpdatePendingError extends Schema.TaggedErrorClass<BootServiceUpdatePendingError>()(\n  \"BootServiceUpdatePendingError\",\n  {},\n) {\n  override get message(): string {\n    return \"A remote server update is still pending. Wait for it to finish, then retry.\";\n  }\n}\n\nexport type BootServiceError =\n  | BootServiceUnsupportedError\n  | BootServiceCommandError\n  | BootServiceInstallError\n  | BootServiceUpdatePendingError;\n\nexport interface BootServiceStatus {\n  readonly supported: boolean;\n  readonly installed: boolean;\n  readonly current: boolean;\n  readonly unitPath: string;\n  readonly logPath: string;\n}\n\nexport class BootService extends Context.Service<\n  BootService,\n  {\n    readonly install: Effect.Effect<BootServicePlan, BootServiceError>;\n    readonly uninstall: Effect.Effect<boolean, BootServiceError>;\n    readonly status: Effect.Effect<BootServiceStatus, BootServiceError>;\n  }\n>()(\"t3/cloud/bootService\") {}\n\nexport interface BootServiceHost {\n  readonly execPath: string;\n  readonly launcherSourcePath?: string;\n}\n\nexport const make = Effect.fn(\"cloud.boot_service.make\")(function* (input: {\n  readonly baseDir: string;\n  readonly logsDir: string;\n  readonly cliVersion: string;\n  readonly host?: BootServiceHost;\n}) {\n  const hostExecPath = yield* HostProcessExecutablePath;\n  const platform = yield* HostProcessPlatform;\n  const homeDir = yield* Config.string(\"HOME\").pipe(Config.withDefault(\"\"));\n  const fs = yield* FileSystem.FileSystem;\n  const path = yield* Path.Path;\n  const runner = yield* ProcessRunner.ProcessRunner;\n  const host = input.host ?? { execPath: hostExecPath };\n\n  const unitDir = path.join(homeDir, \".config\", \"systemd\", \"user\");\n  const unitPath = path.join(unitDir, BOOT_SERVICE_UNIT_FILE);\n  const logPath = path.join(input.logsDir, \"boot-service.log\");\n  const launcherPath = path.join(input.baseDir, \"runtime\", SERVICE_LAUNCHER_FILE);\n  const statePath = path.join(input.baseDir, \"runtime\", SERVICE_STATE_FILE);\n  const runtimePaths = pinnedRuntimePaths(path, input.baseDir, input.cliVersion);\n  const launcherSourcePath =\n    host.launcherSourcePath ??\n    path.join(path.dirname(runtimePaths.entryPath), SERVICE_LAUNCHER_FILE);\n  const writeDurably = (filePath: string, contents: string) =>\n    Effect.scoped(\n      Effect.gen(function* () {\n        const directory = path.dirname(filePath);\n        yield* fs.makeDirectory(directory, { recursive: true });\n        const tempPath = yield* fs.makeTempFileScoped({ directory, prefix: \".service-write-\" });\n        yield* fs.writeFileString(tempPath, contents, { mode: 0o600 });\n        yield* (yield* fs.open(tempPath, { flag: \"r\" })).sync;\n        yield* fs.rename(tempPath, filePath);\n        yield* (yield* fs.open(directory, { flag: \"r\" })).sync;\n      }),\n    ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));\n  const plan: BootServicePlan = {\n    nodePath: host.execPath,\n    launcherPath,\n    baseDir: input.baseDir,\n    logPath,\n    unitPath,\n  };\n\n  const requireSystemdLinux = Effect.gen(function* () {\n    if (platform !== \"linux\" || homeDir === \"\") {\n      return yield* new BootServiceUnsupportedError({ platform });\n    }\n  });\n\n  const runStep = Effect.fn(\"cloud.boot_service.run_step\")(function* (\n    step: string,\n    command: string,\n    args: ReadonlyArray<string>,\n    options?: { readonly timeout?: Duration.Input },\n  ) {\n    return yield* runner.run({ command, args, timeout: options?.timeout }).pipe(\n      Effect.mapError((cause) => new BootServiceCommandError({ step, cause })),\n      Effect.filterOrFail(\n        (result) => result.code === 0,\n        (result) =>\n          new BootServiceCommandError({\n            step,\n            exitCode: Number(result.code),\n            stdoutLength: result.stdout.length,\n            stderrLength: result.stderr.length,\n          }),\n      ),\n      Effect.tapError((error) =>\n        DateTime.now.pipe(\n          Effect.flatMap((now) =>\n            fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\\n`, {\n              flag: \"a\",\n            }),\n          ),\n          Effect.ignore,\n        ),\n      ),\n    );\n  });\n\n  const install: BootService[\"Service\"][\"install\"] = Effect.gen(function* () {\n    yield* requireSystemdLinux;\n    yield* fs\n      .makeDirectory(input.logsDir, { recursive: true })\n      .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));\n\n    // Prepare every immutable artifact before stopping the installed unit.\n    yield* ensurePinnedRuntimeInstalled({\n      baseDir: input.baseDir,\n      version: input.cliVersion,\n      fs,\n      path,\n      runner,\n      validate: (runtime) =>\n        runner\n          .run({\n            command: host.execPath,\n            args: [runtime.entryPath, \"--version\"],\n            timeout: Duration.seconds(30),\n          })\n          .pipe(\n            Effect.mapError(\n              (cause) =>\n                new PinnedRuntimeInstallError({\n                  step: \"verifying the pinned server runtime\",\n                  cause,\n                }),\n            ),\n            Effect.flatMap((result) => {\n              const reportedVersion = /\\bv(\\S+)\\s*$/.exec(result.stdout)?.[1];\n              return result.code === 0 && reportedVersion === input.cliVersion\n                ? Effect.void\n                : Effect.fail(\n                    new PinnedRuntimeInstallError({\n                      step: \"verifying the pinned server runtime\",\n                      exitCode: Number(result.code),\n                      stdoutLength: result.stdout.length,\n                      stderrLength: result.stderr.length,\n                    }),\n                  );\n            }),\n          ),\n    }).pipe(\n      Effect.mapError((error) =>\n        error._tag === \"PinnedRuntimeInstallError\"\n          ? new BootServiceCommandError({\n              step: error.step,\n              exitCode: error.exitCode,\n              stdoutLength: error.stdoutLength,\n              stderrLength: error.stderrLength,\n              cause: error,\n            })\n          : new BootServiceInstallError({ cause: error }),\n      ),\n    );\n    const launcherSource = yield* fs\n      .readFileString(launcherSourcePath)\n      .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));\n\n    const installed = yield* fs\n      .exists(unitPath)\n      .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));\n    if (installed) {\n      yield* runStep(\"stopping the installed service\", \"systemctl\", [\n        \"--user\",\n        \"stop\",\n        BOOT_SERVICE_UNIT_FILE,\n      ]);\n    }\n\n    yield* Effect.gen(function* () {\n      if (installed) {\n        const previousStateText = yield* fs.readFileString(statePath).pipe(Effect.option);\n        if (\n          Option.isSome(previousStateText) &&\n          serviceStateHasPendingUpdate(previousStateText.value)\n        ) {\n          return yield* new BootServiceUpdatePendingError();\n        }\n      }\n      yield* fs\n        .makeDirectory(unitDir, { recursive: true })\n        .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));\n      yield* writeDurably(launcherPath, launcherSource);\n      yield* writeDurably(\n        statePath,\n        // @effect-diagnostics-next-line preferSchemaOverJson:off - fixed launcher-owned document.\n        `${JSON.stringify(\n          {\n            protocol: SERVICE_LAUNCHER_PROTOCOL,\n            activeVersion: input.cliVersion,\n          } satisfies ServiceState,\n          null,\n          2,\n        )}\\n`,\n      );\n      yield* writeDurably(unitPath, renderBootServiceUnit(plan));\n\n      yield* runStep(\"reloading systemd user units\", \"systemctl\", [\"--user\", \"daemon-reload\"]);\n      yield* runStep(\"enabling the service\", \"systemctl\", [\n        \"--user\",\n        \"enable\",\n        BOOT_SERVICE_UNIT_FILE,\n      ]);\n      yield* runStep(\"enabling lingering for this user\", \"loginctl\", [\"enable-linger\"]);\n      // Start last. No administrative state write occurs after this succeeds.\n      yield* runStep(\"starting the service\", \"systemctl\", [\n        \"--user\",\n        \"restart\",\n        BOOT_SERVICE_UNIT_FILE,\n      ]);\n    }).pipe(\n      Effect.tapError(() =>\n        installed\n          ? runStep(\"restarting the service after a failed update\", \"systemctl\", [\n              \"--user\",\n              \"restart\",\n              BOOT_SERVICE_UNIT_FILE,\n            ]).pipe(Effect.ignore)\n          : Effect.void,\n      ),\n    );\n    return plan;\n  }).pipe(Effect.withSpan(\"cloud.boot_service.install\"));\n\n  const uninstall: BootService[\"Service\"][\"uninstall\"] = Effect.gen(function* () {\n    yield* requireSystemdLinux;\n    if (\n      !(yield* fs\n        .exists(unitPath)\n        .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))))\n    )\n      return false;\n    yield* runStep(\"stopping the service\", \"systemctl\", [\n      \"--user\",\n      \"disable\",\n      \"--now\",\n      BOOT_SERVICE_UNIT_FILE,\n    ]);\n    yield* fs\n      .remove(unitPath)\n      .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause })));\n    yield* runStep(\"reloading systemd user units\", \"systemctl\", [\"--user\", \"daemon-reload\"]);\n    return true;\n  }).pipe(Effect.withSpan(\"cloud.boot_service.uninstall\"));\n\n  const status: BootService[\"Service\"][\"status\"] = Effect.gen(function* () {\n    if (platform !== \"linux\" || homeDir === \"\") {\n      return { supported: false, installed: false, current: false, unitPath, logPath };\n    }\n    if (!(yield* fs.exists(unitPath))) {\n      return { supported: true, installed: false, current: false, unitPath, logPath };\n    }\n    const [unit, launcherExists, runtimeEntryExists, runtimeSentinel, stateText] =\n      yield* Effect.all([\n        fs.readFileString(unitPath),\n        fs.exists(launcherPath),\n        fs.exists(runtimePaths.entryPath),\n        fs.readFileString(runtimePaths.sentinelPath).pipe(Effect.option),\n        fs.readFileString(statePath).pipe(Effect.option),\n      ]);\n    const state = Option.isSome(stateText) ? parseServiceState(stateText.value) : undefined;\n    return {\n      supported: true,\n      installed: true,\n      current:\n        unit === renderBootServiceUnit(plan) &&\n        launcherExists &&\n        runtimeEntryExists &&\n        Option.isSome(runtimeSentinel) &&\n        runtimeSentinel.value.trim() === input.cliVersion &&\n        state?.activeVersion === input.cliVersion &&\n        state?.update?.status !== \"pending\",\n      unitPath,\n      logPath,\n    };\n  }).pipe(\n    Effect.mapError((cause) => new BootServiceInstallError({ cause })),\n    Effect.withSpan(\"cloud.boot_service.status\"),\n  );\n\n  return BootService.of({ install, uninstall, status });\n});\n\nexport const layer = (input: {\n  readonly baseDir: string;\n  readonly logsDir: string;\n  readonly cliVersion: string;\n  readonly host?: BootServiceHost;\n}) => Layer.effect(BootService, make(input));\n","import * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Terminal from \"effect/Terminal\";\nimport { Command, GlobalFlag, Prompt } from \"effect/unstable/cli\";\n\nimport packageJson from \"../../package.json\" with { type: \"json\" };\nimport * as BootService from \"../cloud/bootService.ts\";\nimport type * as ServerConfig from \"../config.ts\";\nimport * as ProcessRunner from \"../processRunner.ts\";\nimport { projectLocationFlags, resolveCliAuthConfig } from \"./config.ts\";\n\nexport const bootServiceLayer = (config: ServerConfig.ServerConfig[\"Service\"]) =>\n  BootService.layer({\n    baseDir: config.baseDir,\n    logsDir: config.logsDir,\n    cliVersion: packageJson.version,\n  }).pipe(Layer.provide(ProcessRunner.layer));\n\nexport type ServiceReconcileResult =\n  | {\n      readonly changed: false;\n      readonly status: BootService.BootServiceStatus;\n    }\n  | {\n      readonly changed: true;\n      readonly previouslyInstalled: boolean;\n      readonly plan: BootService.BootServicePlan;\n    };\n\n/** Install, update, or repair the service using the CLI version running this command. */\nexport const reconcileService = Effect.fn(\"cli.service.reconcile\")(function* () {\n  const service = yield* BootService.BootService;\n  const status = yield* service.status;\n  if (status.installed && status.current) {\n    return { changed: false, status } satisfies ServiceReconcileResult;\n  }\n  const plan = yield* service.install;\n  return {\n    changed: true,\n    previouslyInstalled: status.installed,\n    plan,\n  } satisfies ServiceReconcileResult;\n});\n\nexport function formatServiceStatus(\n  status: BootService.BootServiceStatus,\n  cliVersion: string,\n): string {\n  if (!status.supported) {\n    return \"Synaptic Code service\\n  Status: unavailable on this machine\\n  Supported on: Linux with systemd\";\n  }\n  if (!status.installed) {\n    return \"Synaptic Code service\\n  Status: not installed\\n  Next: Run `synaptic-code service install`.\";\n  }\n  return [\n    \"Synaptic Code service\",\n    `  Status: ${status.current ? `installed · @dmccore/code@${cliVersion}` : \"needs an update or repair\"}`,\n    `  Unit: ${status.unitPath}`,\n    `  Logs: ${status.logPath}`,\n    ...(status.current ? [] : [\"  Next: Run `npx @dmccore/code@latest service update`.\"]),\n  ].join(\"\\n\");\n}\n\nconst runServiceCommand = Effect.fn(\"cli.service.run\")(function* <A, E>(\n  flags: { readonly baseDir: Parameters<typeof resolveCliAuthConfig>[0][\"baseDir\"] },\n  run: Effect.Effect<A, E, BootService.BootService>,\n) {\n  const logLevel = yield* GlobalFlag.LogLevel;\n  const config = yield* resolveCliAuthConfig(flags, logLevel);\n  return yield* run.pipe(Effect.provide(bootServiceLayer(config)));\n});\n\nconst serviceInstallCommand = Command.make(\"install\", projectLocationFlags).pipe(\n  Command.withDescription(\"Install Synaptic Code as a background service for this user.\"),\n  Command.withHandler((flags) =>\n    runServiceCommand(\n      flags,\n      Effect.gen(function* () {\n        const result = yield* reconcileService();\n        if (!result.changed) {\n          yield* Console.log(\n            `Synaptic Code service is already installed with @dmccore/code@${packageJson.version}.`,\n          );\n          return;\n        }\n        yield* Console.log(\n          `${result.previouslyInstalled ? \"Updated\" : \"Installed\"} Synaptic Code service with @dmccore/code@${packageJson.version}.\\nLogs: ${result.plan.logPath}`,\n        );\n      }),\n    ),\n  ),\n);\n\nconst serviceUpdateCommand = Command.make(\"update\", projectLocationFlags).pipe(\n  Command.withDescription(\n    \"Update or repair the background service using this CLI version. Use `npx @dmccore/code@latest service update` for the latest release.\",\n  ),\n  Command.withHandler((flags) =>\n    runServiceCommand(\n      flags,\n      Effect.gen(function* () {\n        const result = yield* reconcileService();\n        if (!result.changed) {\n          yield* Console.log(\n            `Synaptic Code service is already using @dmccore/code@${packageJson.version}.`,\n          );\n          return;\n        }\n        yield* Console.log(\n          `${result.previouslyInstalled ? \"Updated\" : \"Installed\"} Synaptic Code service with @dmccore/code@${packageJson.version}.\\nLogs: ${result.plan.logPath}`,\n        );\n      }),\n    ),\n  ),\n);\n\nconst serviceUninstallCommand = Command.make(\"uninstall\", projectLocationFlags).pipe(\n  Command.withDescription(\"Stop and remove the Synaptic Code background service.\"),\n  Command.withHandler((flags) =>\n    runServiceCommand(\n      flags,\n      Effect.gen(function* () {\n        const service = yield* BootService.BootService;\n        const removed = yield* service.uninstall;\n        yield* Console.log(\n          removed\n            ? \"Removed the Synaptic Code service.\"\n            : \"Synaptic Code service is not installed.\",\n        );\n      }),\n    ),\n  ),\n);\n\nconst serviceStatusCommand = Command.make(\"status\", projectLocationFlags).pipe(\n  Command.withDescription(\"Show whether the Synaptic Code background service is installed.\"),\n  Command.withHandler((flags) =>\n    runServiceCommand(\n      flags,\n      Effect.gen(function* () {\n        const service = yield* BootService.BootService;\n        yield* Console.log(formatServiceStatus(yield* service.status, packageJson.version));\n      }),\n    ),\n  ),\n);\n\nexport const offerServiceDuringOnboarding = Effect.gen(function* () {\n  const service = yield* BootService.BootService;\n  const { supported, installed, current } = yield* service.status;\n  if (!supported) {\n    return false;\n  }\n  if (installed && current) {\n    yield* Console.log(\"Synaptic Code is already set up to run in the background on this machine.\");\n    return true;\n  }\n  const wanted = yield* Prompt.run(\n    Prompt.confirm({\n      message: installed\n        ? \"The installed Synaptic Code service needs an update or repair. Update it now?\"\n        : \"Run Synaptic Code in the background whenever this machine boots? \" +\n          \"It stays reachable through Synaptic Connect even after you log out.\",\n      initial: true,\n    }),\n  );\n  if (!wanted) {\n    return false;\n  }\n  const result = yield* reconcileService();\n  if (result.changed) {\n    yield* Console.log(\n      `Background service ${result.previouslyInstalled ? \"updated\" : \"installed\"}. Logs: ${result.plan.logPath}`,\n    );\n  }\n  return true;\n});\n\nexport const recoverServiceOnboardingOffer = <R>(\n  offer: Effect.Effect<boolean, BootService.BootServiceError | Terminal.QuitError, R>,\n) =>\n  offer.pipe(\n    Effect.catchTags({\n      QuitError: () => Effect.succeed(false),\n      BootServiceUnsupportedError: (error) =>\n        Console.log(`Skipping background setup: ${error.message}`).pipe(Effect.as(false)),\n      BootServiceCommandError: (error) =>\n        Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),\n      BootServiceInstallError: (error) =>\n        Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),\n      BootServiceUpdatePendingError: (error) =>\n        Console.warn(`Background setup did not finish: ${error.message}`).pipe(Effect.as(false)),\n    }),\n  );\n\nexport const serviceCommand = Command.make(\"service\").pipe(\n  Command.withDescription(\"Manage the Synaptic Code background service.\"),\n  Command.withSubcommands([\n    serviceInstallCommand,\n    serviceUninstallCommand,\n    serviceUpdateCommand,\n    serviceStatusCommand,\n  ]),\n);\n","import * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport { Command, Flag } from \"effect/unstable/cli\";\n\nimport { runServicePreflight } from \"../cloud/servicePreflight.ts\";\n\nexport const servicePreflightCommand = Command.make(\"__service-preflight\", {\n  databasePath: Flag.string(\"database-path\"),\n  launcherProtocol: Flag.integer(\"launcher-protocol\"),\n}).pipe(\n  Command.withHidden,\n  Command.withHandler(({ databasePath, launcherProtocol }) =>\n    Console.log(JSON.stringify(runServicePreflight({ databasePath, launcherProtocol }))).pipe(\n      Effect.asVoid,\n    ),\n  ),\n);\n","import * as NodeRuntime from \"@effect/platform-node/NodeRuntime\";\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { Command } from \"effect/unstable/cli\";\n\nimport * as NetService from \"@t3tools/shared/Net\";\nimport packageJson from \"../package.json\" with { type: \"json\" };\nimport { authCommand } from \"./cli/auth.ts\";\nimport { pairCommand } from \"./cli/pair.ts\";\nimport { sharedServerCommandFlags } from \"./cli/config.ts\";\nimport { projectCommand } from \"./cli/project.ts\";\nimport { runServerCommand, serveCommand, startCommand } from \"./cli/server.ts\";\nimport { serviceCommand } from \"./cli/service.ts\";\nimport { servicePreflightCommand } from \"./cli/servicePreflight.ts\";\n\nconst CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);\n\n// The connect command in ./cli/connect.ts is deliberately not registered.\n// T3 Connect is the source project's hosted service, and this fork does not\n// run it. The module stays on disk so merges stay clean.\nexport const cli = Command.make(\"synaptic-code\", { ...sharedServerCommandFlags }).pipe(\n  Command.withDescription(\"Run the Synaptic Code server.\"),\n  Command.withHandler((flags) => runServerCommand(flags)),\n  Command.withSubcommands([\n    startCommand,\n    serveCommand,\n    pairCommand,\n    authCommand,\n    projectCommand,\n    serviceCommand,\n    servicePreflightCommand,\n  ]),\n);\n\nif (import.meta.main) {\n  Command.run(cli, { version: packageJson.version }).pipe(\n    Effect.scoped,\n    Effect.provide(CliRuntimeLayer),\n    NodeRuntime.runMain,\n  );\n}\n"],"x_google_ignoreList":[45,46,47,48,49,50,51,52,53,54,55,56,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,413,414,415,416,417],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,IAAa,WAAb,cAA8B,KAAK,YAAY,UAAU,CAAC,CAGvD,CAAC;AAEJ,MAAM,4BACJ,UAIA,UAAU,SAAS,KAAK,KACxB,UAAU,YA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SAAO,OAAO;CAChD,GAAG,yBAAyB;CAC5B,MAAM;CACN,SAAS;AACX,CAAC;AAGD,MAAM,4BAA4BA,SAAO,OAAO;CAC9C,GAAG,yBAAyB;CAC5B,MAAM;CACN,SAAS;AACX,CAAC;AAGqCA,SAAO,MAAM;CACjD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAqB+BA,SAAO,SAAS;CAAC;CAAW;CAAa;CAAe;AAAO,CAAC;AChrChG,MAAa,kCAAkC;CAC7C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAGA,MAAa,wCAAwC;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,MAAa,6BAA6B;CACxC;CACA;CACA,GAAG;AACL;AASA,MAAM,6BAA6B;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG,CA5BH,sBACA,GAAG,qCA2BA;CACH,GAAG;AACL;AAEA,MAAa,6BAA6BC,SAAO,gBAAgB;CAC/DA,SAAO,QAAQ,SAAS;CACxBA,SAAO,eAAe,MACpBA,SAAO,YAAA,EAAgC,GACvCA,SAAO,UAAU,sBAAsB,CACzC;CACAA,SAAO,QAAQ,MAAM;AACvB,CAAC;AAED,MAAa,oBAAoBA,SAAO,MAAM,CAC5CA,SAAO,SAAS,0BAA0B,GAC1C,0BACF,CAAC;AAGD,MAAa,kBAAkB,cAAc,MAC3CA,SAAO,YAAY,CAAC,GACpBA,SAAO,YAAA,EAAuC,CAChD;AAEA,MAAa,iBAAiB,cAAc,MAC1C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